Getting the content of a <p> tag inside a <div> class="some_class"> tag using Beautiful Soup in Python

Viewed 1156

I have a HTML code having a div tag with class="some_class". And there is a p tag inside this div tag:

<div class="some_class">

<p>blah blah blah...</p>

</div>

I need to get the p tag's content and store it in a variable. I did it in two steps:

1)Get the div tag using findAll('div', class_='some_class'),

2)Using split at the p tag

Is there any direct way of doing this without having to do the complex splitting?

2 Answers

You can just use find_all again as in #1.

However, if you don't need the div you can use #2

import bs4 

html = """
<div class="some_class">
  <p>blah blah blah...</p>
</div>
"""

soup = bs4.BeautifulSoup(html)

# 1
for div in soup.find_all('div', class_='some_class'):
    for p in div.find_all('p'):
        print(p.text)
# 2
for p_in_some_class in soup.select('div.some_class p'):
    print(p.text)

If you have only one div tag and only one p tag in it, you can do this:

content = soup.findAll('div', class_= 'some_class')[0].findAll('p')[0].contents[0]

Related