Skip to main content
 首页 » 编程设计

python之BeautifulSoup 中的 findAll() 会跳过多个 id

2024年12月31日14虾米哥

我在图像标签中有一个包含多个 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。

请您参考如下方法:

BeautifulSoup 存储 attributes of a tag in a dictionary .由于字典不能有重复的键,一个 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 获取了不同的值。这发生为 different parsers work differently .

无法使用 BeautifulSoup 获取两个 id 值。您可以使用 RegEx 获取它们。但是,use it carefully and as a last resort!

>>> 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']