gpt4 book ai didi

python - 解析链接时脚本给出重复结果

转载 作者:行者123 更新时间:2023-12-01 08:52:09 26 4
gpt4 key购买 nike

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

我需要保持列表理解的格式,因为很少有页面可以看到多个图像链接。但是,我也不希望使用 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']

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

最佳答案

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

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

ul > li > img.dp-gallery__image

关于python - 解析链接时脚本给出重复结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53040943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com