[英]How do I match a tag containing only the stated class, not any others, using 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>
是否有可能只匹配div
与class="two"
,但不能匹配div
与class="one two"
? 除非我缺少任何内容,否则文档的那部分不会给我任何想法。 这是我当前正在使用的代码:
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"
之外,其他标签可能还具有大量其他类别,这可能是未知的。
尝试:
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" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.