Reputation: 167
find_parent()
method is different from find_parents()
method because it returns the first immediate parent, unlike find_parents()
which returns the entire matching parent tags. But why this code is supposed to be correct?
print(soup.a.string.find_parent("p"))
given :
<p>
<a>"...."</a>
</p>
p isn't the immediate parent of the string.
Upvotes: 0
Views: 3060
Reputation: 12168
parents
means ancestor, find_parent("p")
means find the first ancestor which name is p
In [5]: soup.a.string.parents
Out[5]: <generator object parents at 0x7f2ee14558e0>
In [6]: list(_)
Out[6]:
[<a>"...."</a>, <p>
<a>"...."</a>
</p>, <body><p>
<a>"...."</a>
</p></body>, <html><body><p>
<a>"...."</a>
</p></body></html>, <html><body><p>
<a>"...."</a>
</p></body></html>]
In [7]: for a in soup.a.string.parents:
...: if a.name == "p":
...: print(a)
...: break
...:
<p>
<a>"...."</a>
</p>
Upvotes: 2