James James - 2 months ago 9
HTML Question

How to use Python with beautifulsoup to merge siblings

How do I merge siblings together and display the output one beside each other.

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>jd@mail.com</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


When run it produces:

Name:
John
Last Name:
Doe
Email:
jd@mail.com


What I need:

Name: John
Last Name: Doe
Email: jd@mail.com


Can it be done in a list and every new "tr" tag put a new line?

EDIT:
alecxe answer worked but strangely after the output I would get "ValueError: need more than 1 value to unpack" To fix that just put a try:except block.

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

Answer

Why don't process the table row by row:

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())

Prints:

Name: John
Last Name: Doe
Email: jd@mail.com