脚本在解析链接时给出重复的结果

问题描述 投票:1回答:2

我正在尝试使用以下脚本从网页抓取图像链接,但是当我运行它时,脚本从那里获取两个链接(相同的链接两次)。为什么我会得到如此奇怪的结果?

我需要保持列表理解的格式,因为有几页我可以看到多个图像链接。但是,我不希望使用set()来踢出那些重复的图像链接。使用选择器时我有什么地方出错吗?

Link to that webpage

这是我的尝试:

import requests
from bs4 import BeautifulSoup

url = "check_out_the_link_above"

def get_image_links(s,link):
    s.headers["User-Agent"] = "Mozilla/5.0"
    res = s.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    images = [item.get("src") for item in soup.select("img.dp-gallery__image")]
    print(images)

if __name__ == '__main__':
    with requests.Session() as s:
        get_image_links(s,url)

结果我得到了:

['https://lid.zoocdn.com/645/430/f8eaf79c39145242e9a30e8d550972e07c0d15a1.jpg', 'https://lid.zoocdn.com/645/430/f8eaf79c39145242e9a30e8d550972e07c0d15a1.jpg']

单个链接两次,我不想要。

python python-3.x web-scraping beautifulsoup
2个回答
1
投票

有两个相同的图像:第一个位于noscript节点内并隐藏,第二个是可见的。

最好的一个是使用XPath //img[@class="dp-gallery__image" and not(ancestor::noscript)],但由于bs4不支持XPath,你可以试试CSS选择器

ul > li > img.dp-gallery__image

0
投票

源网站有两次图像链接,都在同一个类下。

<noscript>
    <li class="dp-gallery__list-item dp-gallery__list-item--orphan">
        <img src="https://lid.zoocdn.com/645/430/f8eaf79c39145242e9a30e8d550972e07c0d15a1.jpg" class="dp-gallery__image" alt="Swale Avenue, Peterborough, Cambridgeshire. PE4">
    </li>
</noscript>

    <li class="dp-gallery__list-item dp-gallery__list-item--orphan">
        <img src="https://lid.zoocdn.com/645/430/f8eaf79c39145242e9a30e8d550972e07c0d15a1.jpg" class="dp-gallery__image" alt="Swale Avenue, Peterborough, Cambridgeshire. PE4">
    </li>

如果你想避免第二个,我会在你的搜索中添加另一个过滤器,以确保你只获得其中一个。

假设内存不是一个大问题,更简单的解决方案就是拍摄图像[0]。

© www.soinside.com 2019 - 2024. All rights reserved.