Beautiful Soup .text and tag still attached

Viewed 51

So i'm using beautiful soup to get data from a table with 2 column. Here's my code

print('Bulan-Tahun', end ='   ')
print('Inflasi')
table = soup.find('table', attrs={'class':'table1'})
for row in table.find_all("tr")[1:]:
    col = row.findAll("td")
    print(col[0].text)
    print(col[1].text)

and this is the result

Bulan-Tahun   Inflasi

                    Juli 2020
                

                    1.54 %
                

                    Juni 2020
                

                    1.96 %
                

                  
            

The text result is located at the right because when i remove the .text, it's position is the exact position when the tag it still intact, but i want it to be only text without all the spacing. any solution? thank you

2 Answers

You might want to you use a .strip() method to remove the white space of the text.

Ex:

print(col[0].text.strip())
print(col[1].text.strip())

That should at least remove the white space around each col.

You can minimally use str.strip() for your code.
For instance:

print(col[0].text.strip())

will output results without leading and trailing whitespaces.

Related