user3347713 user3347713 - 1 year ago 145
Python Question

BeautifulSoup parent tag

I have some html that I want to extract text from. Here's an example of the html:

<p>TEXT I WANT <i> &#8211; </i></p>

Now, there are, obviously, lots of
tags in this document. So,
is not a good way to get at the text I want to extract. However, that
tag is the only one in the document. So, I thought I could just find the
and then go to the parent.

I've tried:

up ='p i').parent


up ='i')

and I've tried it with
, I've tried
... But I always get:

'list' object has no attribute "parent"

What am I doing wrong?

Answer Source

This works:

i_tag = soup.find('i')
my_text = str(i_tag.previousSibling).strip()



As mentioned in other answers, find_all() returns a list, whereas find() returns the first match or None

If you are unsure about the presence of an i tag you could simply use a try/except block

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download