python - 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。
解决方案
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']
推荐阅读
- angularjs - 为什么 angularjs 过滤器的命名过滤器不适用于第一个元素?
- php - 将另一个 URL 添加到下载脚本中
- javascript - 将javascript变量分配给php代码的简单方法
- python - Python脚本自动下载gmail附件
- filter - 如何将 null 或空传递给 FetchXML 过滤器?
- r - R data.table fread:指定列数据类型
- php - 统计所有具有搜索功能的产品
- php - php 文件未连接到 azure 数据库(应用服务的 mySQL-in-app)
- scala - 配置 Spark 写入 HDFS 的 Avro 文件大小
- c++ - 模板缓冲区不绘制部分图块