BS4 getText function producing unexpected output

Viewed 29

The Following html sample produces different results depending on the text style format Here is the sample when on one line

card = """
<ul class="wrapper--inline-block float--left margin-top--15 padding-left--20 font--weight-300"><li><span class="font--weight-500">Minimum Qualification:</span> Bachelor</li><li><span class="font--weight-500">Experience Level:</span> Graduate trainee</li><li><span class="font--weight-500">Experience Length:</span> 1 year</li></ul>
"""

Output:

Minimum Qualification: BachelorExperience Level: Graduate traineeExperience Length: 1 year

And when the html sample is formatted

card = """
<ul class="wrapper--inline-block float--left margin-top--15 padding-left--20 font--weight-300">
<li><span class="font--weight-500">Minimum Qualification:</span> Bachelor</li>
<li><span class="font--weight-500">Experience Level:</span> Graduate trainee</li>
<li><span class="font--weight-500">Experience Length:</span> 1 year</li>
</ul>
"""

The Output

Minimum Qualification: Bachelor
Experience Level: Graduate trainee
Experience Length: 1 year

Question is, how can make the first case produce the desired output like case two. Here is my current code

qualifications=  BeautifulSoup(card, "html.parser")
print(qualifications.getText())
2 Answers

Use separator="\n" to get desired output,

qualifications.getText(separator="\n")

Edit-1:

>>> card = """
<ul class="wrapper--inline-block float--left margin-top--15 padding-left--20 font--weight-300"><li><span class="font--weight-500">Minimum Qualification:</span> Bachelor</li><li><span class="font--weight-500">Experience Level:</span> Graduate trainee</li><li><span class="font--weight-500">Experience Length:</span> 1 year</li></ul>
"""

>>> qualifications=  BeautifulSoup(card, "html.parser")

>>> for li in qualifications.find_all('li'):
     print(li.get_text()) 
Minimum Qualification: Bachelor
Experience Level: Graduate trainee
Experience Length: 1 year

I guess that the case for bs4 prints the contents the same way it gets it(in one line or in different line). But for your specific question you can first find <li> tags and then print their content. The whole contents of each element will be printed in a different line.

qualifications=  BeautifulSoup(card, "html.parser")
soup = qualifications.findAll('li')
for i in soup:
     print(i.getText())

you'll get this:

Minimum Qualification: Bachelor
Experience Level: Graduate trainee
Experience Length: 1 year
Related