兄弟をまとめて結合し、それぞれの隣に出力を表示するにはどうすればいいですか?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
ありがとうございました。外出後に少し変わっていましたが、ValueError:解凍するには1つ以上の値が必要です。 – James