2011-02-10 2 views
0
<table id="t_id" cellspacing="0" border="0" align="center" height="700" width="600" cellpadding="0"> 
<tbody> 
<tr><td> ..test... </td></tr> 
<tr><td> ..test... </td></tr> 
<tr><td> ..test... </td></tr> 
</tbody> 
</table> 

答えて

3

最近、人々はBeautifulSoupよりlxmlを好む傾向があります。

from lxml import etree 
data = """<table id="t_id" cellspacing="0" border="0" align="center" height="700" width="600" cellpadding="0"> 
<tbody> 
<tr><td> ..test... </td></tr> 
<tr><td> ..test... </td></tr> 
<tr><td> ..test... </td></tr> 
</tbody> 
</table> 
""" 
tree = etree.fromstring(data) 
table_element = tree.xpath("/table")[0] # because it returns a list of table elements 
print table_element.attrib['height'] + " and " + table_element.attrib['width'] 
+1

なぜ人々はlxmlを好むのですか?パフォーマンス上の理由? BeautifulSoupソリューションは短く、より多くのpythonic IMHOを表示するためです。 – DzinX

+1

私はBeautifulSoupのファンですが、それはドードーの道を行くように見えます:http://stackoverflow.com/questions/1922032/parsing-html-in-python-lxml-or-beautifulsoup-which -the-for-better-for-what/1922064#1922064 –

+0

"クリティカル"なものを構築していない場合でも、問題なく美しいスープを使用することができます。しかし、最新(3.1.0)バージョンには多くの変更があります。 BSを使用したい場合は、3.0.8を使用することをお勧めします。 –

1

これはあなたの全体のHTMLであれば、これは十分でしょう:

import BeautifulSoup 
soup = BeautifulSoup.BeautifulSoup("...your HTML...") 
print soup.table['width'], soup.table['height'] 
# prints: 600 700 

をあなたが最初のテーブルを検索する必要がある場合、それははるかに複雑ではありません、どちらか:これはどのように簡単に参照してください。

table = soup.find('table', id='t_id') 
print table['width'], table['height'] 
関連する問題