2016-10-05 17 views
2

兄弟をまとめて結合し、それぞれの隣に出力を表示するにはどうすればいいですか?beautifulsoupでPythonを使用して兄弟をマージする方法

EX。

dat=""" 
<div class="col-md-1"> 
<table class="table table-hover"> 
<tr> 
<th>Name:</th> 
<td><strong>John</strong></td> 
</tr> 
<tr> 
<th>Last Name:</th> 
<td>Doe</td> 
</tr> 
<tr> 
<th>Email:</th> 
<td>[email protected]</td> 
</tr> 
</table> 
</div> 
""" 

soup = BeautifulSoup(dat, 'html.parser') 
for buf in soup.find_all(class_="table"): 
    ope = buf.get_text("\n", strip=True) 
    print ope 

実行すると、それが生成する:

Name: 
John 
Last Name: 
Doe 
Email: 
[email protected] 

を私は必要なもの:

Name: John 
Last Name: Doe 
Email: [email protected] 

は、それがリストと、すべての新しい "TR" タグプットで行うことができます新しい行?

EDIT: alecxe答えが働いていたが、妙に出力した後、私は「とValueError:解凍する必要以上1つの値」になるだろう:ブロックを除いてちょうど試みを置くことを修正するには。

soup = BeautifulSoup(dat, 'html.parser') 
for row in soup.select(".table tr"): 
    label, value = row.find_all(["th", "td"]) 
    print(label.get_text() + " " + value.get_text()) 

プリント:

soup = BeautifulSoup(dat, 'html.parser') 
for row in soup.select(".table tr"): 
try: 
     (label, value) = row.find_all(["th", "td"]) 
    print(label.get_text() + " " + value.get_text()) 
except ValueError: 
    continue 

答えて

1

なぜ行によってテーブル行を処理しません

Name: John 
Last Name: Doe 
Email: [email protected] 
+0

ありがとうございました。外出後に少し変わっていましたが、ValueError:解凍するには1つ以上の値が必要です。 – James

0

使用この

soup = BeautifulSoup(dat, 'html.parser') 
table = soup.find_all('table', attrs={'class': ['table', 'table-hover']}) 
for buf in table: 
    for row in buf.find_all('tr'): 
     print(row.th.string, row.td.string) 

出力

Name: John 
Last Name: Doe 
Email: [email protected] 
+0

ありがとうございましたが、 "(u '...'、u '...')タグを削除する方法を理解できませんでした。 – James

関連する問題