有没有办法使用 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>
是否可以只匹配 div
与 class="two"
,但不匹配 div
与 class="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/