Mika Schiller
Mika Schiller

Reputation: 425

How do I pull <p> tags without attributes using Beautiful Soup?

Say a web page contains the following:

<p style="display: none;"><input id="ak_js" name="ak_js" type="hidden" value="68"/></p>

<p><b>Lack of sales.. ANY sales.</b></p>

I'm trying to write code that would pull only the second tag. Basically all paragraph tags that don't contain attributes. I tried the following two pieces of code below, but they don't get me the results I want.

text = BeautifulSoup(requests.get(url).text)

for tag in text.find_all("p", attrs = False):
    .....

for tag in text.find_all(re.compile("^<p>$")):
    ....

What's the best way to solve this?

Upvotes: 1

Views: 1589

Answers (1)

Cyrbil
Cyrbil

Reputation: 6478

You can give a lambda to find_all and filter with it.

soup.find_all(lambda tag: tag.name == 'p' and not tag.attrs)

Upvotes: 5

Related Questions