有沒有辦法使用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也有幫助。
唯一的問題是,我不知道標籤會包含哪些其他類。 +1,但如果可能,請參閱我的編輯。 – 2012-07-16 17:06:44
由於您的答案與我的答案基本相同,因此如果將編輯中引入的更改合併,我會接受並刪除自己的答案。 – 2012-07-16 17:18:25
@RicardoAltamirano我很欣賞禮貌。編輯。 – 2012-07-16 17:22:28