我可以从img标记中使用BeautifulSoup刮取“value”属性吗?

2024-09-29 23:15:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在测试我对网页抓取的理解,无法将特定值拉到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”,没有任何改变。目前正在研究使用硒,看看是否有答案

任何帮助都将不胜感激


Tags: 代码标记com类型imgcontainer变体content
1条回答
网友
1楼 · 发布于 2024-09-29 23:15:58

这是因为您的第一个for循环返回所有元素。但是,当您将下一个for循环置于外部for循环之外时,它总是给您最后一个元素。它应该是内外循环

现在试试看

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)

输出

['EVGA', 'MSI', 'ASUS', 'MSI', 'Sapphire Tech', 'EVGA', 'GIGABYTE', 'XFX', 'ASUS', 'ASRock', 'EVGA', 'ASUS', 'EVGA', 'GIGABYTE', 'GIGABYTE', 'GIGABYTE', 'EVGA', 'EVGA', 'MSI', 'ASRock', 'EVGA', 'XFX', 'Sapphire Tech', 'ASRock', 'GIGABYTE', 'ASUS', 'MSI', 'MSI', 'MSI', 'MSI', 'MSI', 'EVGA', 'GIGABYTE', 'EVGA', 'ASUS', 'GIGABYTE']

如果您有BS4.7.1或更高版本,则可以使用此css选择器

webpage = requests.get('https://www.newegg.com/p/pl?Submit=StoreIM&Depa=1&Category=38')
content = webpage.content
soup = BeautifulSoup(content, 'lxml')

brand = []

for name_brand in soup.select(".item-container .item-info"):
        brand.append(name_brand.find_next('img').get("alt"))
print(brand)

相关问题 更多 >

    热门问题