测试BeautifulGroup中的标记中是否存在属性

2024-04-20 05:01:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想获取文档中的所有<script>标记,然后根据某些属性的存在(或不存在)来处理每个标记。

例如,对于每个<script>标记,如果属性for存在,则执行某些操作;否则,如果属性bar存在,则执行其他操作。

以下是我目前正在做的事情:

outputDoc = BeautifulSoup(''.join(output))
scriptTags = outputDoc.findAll('script', attrs = {'for' : True})

但通过这种方式,我过滤了所有带有for属性的<script>标记。。。但是我失去了其他的(那些没有for属性的)。


Tags: 文档标记trueforoutput属性scriptbar
3条回答

不需要任何lambda来按属性过滤,只需在findfind_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$"))

如果我理解的好,你只需要所有的脚本标记,然后检查其中的一些属性?

scriptTags = outputDoc.findAll('script')
for script in scriptTags:
    if script.has_attr('some_attribute'):
        do_something()        

为了以后的参考,已经被弃用的是美化组4。现在你需要使用has_attr

scriptTags = outputDoc.findAll('script')
  for script in scriptTags:
    if script.has_attr('some_attribute'):
      do_something()  

相关问题 更多 >