如何使用BeautifulSoup匹配仅包含指定类的标签,而不是其他任何标签?
问题描述:
有没有办法使用BeautifulSoup来匹配标签只有 012df属性,而不是class
属性和其他?例如,在这个简单的HTML:如何使用BeautifulSoup匹配仅包含指定类的标签,而不是其他任何标签?
<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"
答
希望,下面的代码可以帮助你。虽然我没有尝试这个。
soup.find("div", { "class" : "two" })
+0
根据文档,这与'soup.find(“div”,“two”) '相同。 – 2012-07-16 17:01:56
唯一的问题是,我不知道标签会包含哪些其他类。 +1,但如果可能,请参阅我的编辑。 – 2012-07-16 17:06:44
由于您的答案与我的答案基本相同,因此如果将编辑中引入的更改合并,我会接受并删除自己的答案。 – 2012-07-16 17:18:25
@RicardoAltamirano我很欣赏礼貌。编辑。 – 2012-07-16 17:22:28