测试一个属性是否存在于 BeautifulSoup 的标签中 [英] Test if an attribute is present in a tag in BeautifulSoup
问题描述
我想获取文档中的所有 标签,然后根据某些属性的存在(或不存在)来处理每个标签.
I would like to get all the <script>
tags in a document and then process each one based on the presence (or absence) of certain attributes.
例如,对于每个 标记,如果存在
for
属性,则执行某些操作;否则,如果存在 bar
属性,则执行其他操作.
E.g., for each <script>
tag, if the attribute for
is present do something; else if the attribute bar
is present do something else.
这是我目前正在做的事情:
Here is what I am doing currently:
outputDoc = BeautifulSoup(''.join(output))
scriptTags = outputDoc.findAll('script', attrs = {'for' : True})
但通过这种方式,我过滤了所有带有 for
属性的 标签......但我丢失了其他标签(那些没有
for
属性).
But this way I filter all the <script>
tags with the for
attribute... but I lost the other ones (those without the for
attribute).
推荐答案
如果我理解的很好,你只是想要所有的脚本标签,然后检查其中的一些属性?
If i understand well, you just want all the script tags, and then check for some attributes in them?
scriptTags = outputDoc.findAll('script')
for script in scriptTags:
if script.has_attr('some_attribute'):
do_something()
这篇关于测试一个属性是否存在于 BeautifulSoup 的标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!