首页 > 解决方案 > BeautifulSoup 中的 findAll() 会跳过多个 id

问题描述

我在图像标签中有一个带有多个 id 的字符串:

<img id="webfast-uhyubv" alt="" data-type="image" id="comp-jefxldtzbalatamediacontentimage" src="http://webfast.co/images/webfast-logo.png" /> 

soup = bs4.BeautifulSoup(webpage,"html.parser")
images = soup.findAll('img')
for image in images:
    print image

上面的代码只返回id=comp-jefxldtzbalatamediacontentimage

更换

soup = bs4.BeautifulSoup(webpage,"html.parser")

soup = bs4.BeautifulSoup(webpage,"lxml")

返回第一个 id webfast-uhyubv

但是,我想按照它们在输入行中存在的顺序来获取两个 id。

标签: pythonbeautifulsouphtml-parsing

解决方案


BeautifulSoup 将标签的属性存储在字典中。由于字典不能有重复的键,一个id属性会覆盖另一个。您可以使用检查属性字典tag.attrs

>>> soup = BeautifulSoup(tag, 'html.parser')
>>> soup.img.attrs
{'id': 'comp-jefxldtzbalatamediacontentimage', 'alt': '', 'data-type': 'image', 'src': 'http://webfast.co/images/webfast-logo.png'}

>>> soup = BeautifulSoup(tag, 'lxml')
>>> soup.img.attrs
{'id': 'webfast-uhyubv', 'alt': '', 'data-type': 'image', 'src': 'http://webfast.co/images/webfast-logo.png'}

id正如你所看到的,我们使用不同的解析器得到不同的价值。这是因为不同的解析器工作方式不同

无法id使用 BeautifulSoup 获得这两个值。您可以使用 RegEx 获取它们。但是,请小心使用它并作为最后的手段!

>>> import re
>>> tag = '<img id="webfast-uhyubv" alt="" data-type="image" id="comp-jefxldtzbalatamediacontentimage" src="http://webfast.co/images/webfast-logo.png" />'
>>> ids = re.findall('id="(.*?)"', tag)
>>> ids
['webfast-uhyubv', 'comp-jefxldtzbalatamediacontentimage']

推荐阅读