Scraping table with BeautifulSoup, How to separate the elements with a newline?

Viewed 143

This is how the rows of my HTML table looks like:

<tr class='row'><td>100
    <td >George</a>
    <td class=a>123<td class=a>321
    <td>Alby<td>Dalton

This is my python code:

for tr in tabel.find('tr'):
    td = tr.find('td')
    print(td.text)

My output:

100
George
123321
AlbyDalton

The output that I would like to get:

100
George
123
321
Alby
Dalton
1 Answers

You can use the get_text() method with adding a newline \n as the separator argument.

from bs4 import BeautifulSoup

html = """
<tr class='row'><td>100
    <td >George</a>
    <td class=a>123<td class=a>321
    <td>Alby<td>Dalton
    """
soup = BeautifulSoup(html, "html.parser")

for tag in soup.find_all("tr", class_="row"):
    print(tag.get_text(separator="\n", strip=True))

Output:

100
George
123
321
Alby
Dalton
Related