2016-07-26 56 views
1

Beautifulsoup對於python中的html解析非常方便,下面的代碼結果可以幫助我。屬性「class」的優惠券返回列表,而其他屬性的值爲

from bs4 import BeautifulSoup 
tr =""" 
<table> 
    <tr class="passed" id="row1"><td>t1</td></tr> 
    <tr class="failed" id="row2"><td>t2</td></tr> 
</table> 
""" 
table = BeautifulSoup(tr,"html.parser") 
for row in table.findAll("tr"): 
    print row["class"] 
    print row["id"] 

結果:

[u'passed'] 
row1 
[u'failed'] 
row2 

爲什麼屬性class收益爲數組?而id是正常值?

beautifulsoup4-4.5.0python 2.7

回答

1

class使用是在BeautifulSoup特殊multi-valued attribute

HTML 4定義了可以具有多個值的一些屬性。 HTML 5 刪除了其中的幾個,但定義了幾個。最常見的 多值屬性是class(即一個標籤可以有不止一個 CSS類)

有時,這是有問題的處理 - 例如,當你想申請定期表達class屬性值作爲一個整體:

你可以turn this behavior off by tweaking the tree builder,但我不建議這樣做。

1

因爲元素可能有多個類。

考慮這個例子:

從BS4進口BeautifulSoup

tr =""" 
<table> 
    <tr class="passed a b c" id="row1"><td>t1</td></tr> 
    <tr class="failed" id="row2"><td>t2</td></tr> 
</table> 
""" 
table = BeautifulSoup(tr,"html.parser") 
for row in table.findAll("tr"): 
    print row["class"] 
    print row["id"] 

['passed', 'a', 'b', 'c'] 
row1 
['failed'] 
row2 
+0

感謝快速回答,從@alecxe接受的答案,我注意到'class'是HTML和BS4一個特殊屬性 –

相關問題