2016-07-26 42 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一个特殊属性 –

相关问题