我一直在测试我对网页抓取的理解,无法将特定值拉到img标记中的属性。我可以缩小到适当的前导标记,但一旦我尝试提取归因于“alt”(img alt=“what\u I\u want”)的值,我就会得到一个none类型。或者在其他一些代码变体中,我只返回一个项目。据我所知,我试图获取的值在技术上不是一个文本或字符串,因此BS实际上没有任何东西可获取。这是正确的吗
我试图抓住每个容器中列出的“EVGA”和其他品牌名称:
[<a class="item-brand" href="https://www.newegg.com/EVGA/BrandStore/ID-1402">
<img alt="EVGA" src="//c1.neweggimages.com/Brandimage_70x28//Brand1402.gif" title="EVGA" />
</a>]
到目前为止,我得到的是:
webpage = requests.get('https://www.newegg.com/p/pl?Submit=StoreIM&Depa=1&Category=38')
content = webpage.content
soup = BeautifulSoup(content, 'lxml')
containers = soup.find_all("div", class_="item-container")
brand = []
for container in containers:
cont_brand = container.find_all("div",{"class":"item-info"})
for name_brand in cont_brand:
brand.append(name_brand.find("img").get("alt"))
print(brand)
这实际上会给我一个返回值[asu' ],它在我可以识别的容器列表中间。我无法在html代码中找到任何可能将此代码与其他代码区分开来的差异。另一种代码格式返回了最后一个值['ASRock'],但我同样找不到只返回该值的原因。我想这与BS4(查找)机制有关。。。? 使用(find_all)的大多数其他代码变体都会返回一个非类型错误,我想根据BS文档可以理解。 我试着换成“html.parser”,没有任何改变。目前正在研究使用硒,看看是否有答案
任何帮助都将不胜感激
这是因为您的第一个for循环返回所有元素。但是,当您将下一个for循环置于外部for循环之外时,它总是给您最后一个元素。它应该是内外循环
现在试试看
输出:
如果您有BS4.7.1或更高版本,则可以使用此css选择器
相关问题 更多 >
编程相关推荐