python - 如何使用 BeautifulSoup 匹配仅包含指定类而不包含任何其他类的标签?

标签 python python-3.x beautifulsoup

有没有办法使用 BeautifulSoup 来匹配指定的标签 class属性,不是指定的 class属性和其他?例如,在这个简单的 HTML 中:

<html>
 <head>
  <title>
   Title here
  </title>
 </head>
 <body>
  <div class="one two">
   some content here
  </div>
  <div class="two">
   more content here
  </div>
 </body>
</html>

是否可以只匹配 divclass="two" ,但不匹配 divclass="one two" ?除非我遗漏了什么,that section文档没有给我任何想法。这是我当前正在使用的代码:

from bs4 import BeautifulSoup

html = '''
<html>
 <head>
  <title>
   Title here
  </title>
 </head>
 <body>
  <div class="one two">
   should not be matched
  </div>
  <div class="two">
   this should be matched
  </div>
 </body>
</html>
'''

soup = BeautifulSoup(html)
div_two = soup.find("div", "two")
print(div_two.contents[0].strip())

我正在尝试打印此内容 this should be matched而不是should not be matched

编辑:在这个简单的示例中,我知道类的唯一选项是 "one two""two" ,但在生产代码中,我只知道我想要匹配的内容将具有类 "two" ;除了"two"之外,其他标签还可以有大量其他类。 ,这可能不为人所知。

在相关说明中,阅读 documentation for version 4 也很有帮助。 ,而不是我之前链接的版本 3。

最佳答案

尝试:

divs = soup.findAll('div', class="two")

for div in divs:
    if div['class'] == ['two']:
        pass # handle class="two"
    else:
        pass # handle other cases, including but not limited to "one two"

关于python - 如何使用 BeautifulSoup 匹配仅包含指定类而不包含任何其他类的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11508897/

相关文章:

降序排列的 Python 日志文件

python - 尝试将多个 .csv 读取到单独的数据框列中

python - 如何使用python selenium递归地点击一个按钮

python - 用汤获取多种元素

python - 无法刮

python - python 真值测试中 bool() 与 == 有什么区别吗?

python - argparse.Namespace 和 types.SimpleNamespace 之间的区别?

Python 线程与非线程

python - django 管道根本不工作

python - 如何打印美丽汤中表格行的所有单元格