I want to get p tag's text and other tag's text inside the p tag in order by bs4

Viewed 219

I selected a content from soup, there are three types.

  1. <p>first</p>
  2. <p><span>first</span></p>
  3. <p>first<span>second</span>third</p>

And I want to get text from the last in order like "first", "second", "third". First, I use '.text' and the last one returned "firstsecondthird". But I want to get text one by one. Is there a way?

I edited question so you can get more detail information.

contents_list = soup.select('blabla')

# contents_list =
# ['<p>first</p>',
# '<p><span>first</span></p>',
# '<p>first<span>second</span>third</p>']

for content in contents_list:
  print(content.text)

# I want to get
# first
# first
# first, second, third
1 Answers

To get the tags separated with a space, you can use the get_text() method with adding a space as the separator argument. .get_text(separator=" ").

from bs4 import BeautifulSoup


html = """
<p>first</p>
<p><span>first</span></p>
<p>first<span>second</span>third</p>

"""

soup = BeautifulSoup(html, "html.parser")

for tag in soup.find_all("p"):
    print(tag.get_text(separator=" "))

Output:

first
first
first second third
Related