测试BeautifulSoup中标签是否存在某个属性
我想要获取文档中的所有<script>
标签,然后根据某些属性的有无来处理每一个标签。
比如,对于每个<script>
标签,如果有for
这个属性,就做某件事;如果没有这个属性,但有bar
这个属性,就做另一件事。
这是我现在的做法:
outputDoc = BeautifulSoup(''.join(output))
scriptTags = outputDoc.findAll('script', attrs = {'for' : True})
但是这样的话,我只筛选出了带有for
属性的<script>
标签……结果把没有for
属性的标签给漏掉了。
7 个回答
38
为了将来参考,beautifulsoup 4 中的 has_key 已经不再使用了。现在你需要用 has_attr 来代替它。
scriptTags = outputDoc.find_all('script')
for script in scriptTags:
if script.has_attr('some_attribute'):
do_something()
49
你不需要用任何复杂的函数来根据属性进行筛选,只需在 find
或 find_all
中使用 some_attribute=True
就可以了。
script_tags = soup.find_all('script', some_attribute=True)
# or
script_tags = soup.find_all('script', {"some-data-attribute": True})
这里还有其他方法的更多例子:
soup = bs4.BeautifulSoup(html)
# Find all with a specific attribute
tags = soup.find_all(src=True)
tags = soup.select("[src]")
# Find all meta with either name or http-equiv attribute.
soup.select("meta[name],meta[http-equiv]")
# find any tags with any name or source attribute.
soup.select("[name], [src]")
# find first/any script with a src attribute.
tag = soup.find('script', src=True)
tag = soup.select_one("script[src]")
# find all tags with a name attribute beginning with foo
# or any src beginning with /path
soup.select("[name^=foo], [src^=/path]")
# find all tags with a name attribute that contains foo
# or any src containing with whatever
soup.select("[name*=foo], [src*=whatever]")
# find all tags with a name attribute that endwith foo
# or any src that ends with whatever
soup.select("[name$=foo], [src$=whatever]")
你也可以在 find
或 find_all
中使用正则表达式:
import re
# starting with
soup.find_all("script", src=re.compile("^whatever"))
# contains
soup.find_all("script", src=re.compile("whatever"))
# ends with
soup.find_all("script", src=re.compile("whatever$"))
148
如果我理解得没错,你只是想要获取所有的脚本标签,然后检查里面的一些属性,对吧?
scriptTags = outputDoc.findAll('script')
for script in scriptTags:
if script.has_attr('some_attribute'):
do_something()