2012-07-16 64 views
2

有沒有辦法使用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> 

是有可能只符合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也有幫助。

回答

4

嘗試:

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" 
+0

唯一的問題是,我不知道標籤會包含哪些其他類。 +1,但如果可能,請參閱我的編輯。 – 2012-07-16 17:06:44

+0

由於您的答案與我的答案基本相同,因此如果將編輯中引入的更改合併,我會接受並刪除自己的答案。 – 2012-07-16 17:18:25

+0

@RicardoAltamirano我很欣賞禮貌。編輯。 – 2012-07-16 17:22:28

0

希望,下面的代碼可以幫助你。雖然我沒有嘗試這個。

soup.find("div", { "class" : "two" }) 
+0

根據文檔,這與'soup.find(「div」,「two」) '相同。 – 2012-07-16 17:01:56

相關問題