【问题标题】:Can I scrape a "value" attribute with BeautifulSoup from an img Tag?我可以从 img 标签中使用 BeautifulSoup 刮出“价值”属性吗?
【发布时间】:2020-08-15 00:28:58
【问题描述】:

我一直在测试我对网络抓取的理解,并且无法将特定值提取到 img 标记中的属性。我可以缩小到正确的前导标签,但是一旦我尝试提取归因于“alt”(img alt="what_i_want")的值,我就会得到一个无类型。或者在其他一些代码变体中,我只返回一个项目。据我了解,我试图获取的价值在技术上不是文本或字符串,因此 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) 

这实际上会给我一个 ['ASUS'] 的返回值,它位于我可以识别的容器列表的中间位置。我无法在 html 代码中找到任何差异,这些差异可能会将这一代码与其他代码区别开来。另一种代码格式返回了最后一个值 ['ASRock'],但我还是找不到那个原因。我认为它与BS4(查找)机制有关......? 使用 (find_all) 的大多数其他代码变体将返回一个 NoneType 错误,我认为我根据 BS 文档了解该错误。 我试过换掉'html.parser'而没有改变。目前正在研究使用 Selenium 看看是否有答案。

任何帮助将不胜感激。

【问题讨论】:

    标签: python html beautifulsoup screen-scraping


    【解决方案1】:

    这是因为您的第一个 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']
    

    如果你有 BS 4.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)
    

    【讨论】:

    • 谢谢!我应该在 2 天前发布这个问题(但我已经学到了很多东西)。我可以发誓我试过了,但显然不正确。
    猜你喜欢
    • 1970-01-01
    • 2017-10-14
    • 2019-06-03
    • 2021-07-27
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多