Get immediate parent tag with BeautifulSoup in Python
You need to check parent
's name
:
for img in soup.find_all('img'): if img.parent.name == 'a': print "Parent is a link"
Demo:
>>> from bs4 import BeautifulSoup>>> >>> data = """... <body>... <a href="google.com"><img src="image.png"/></a>... </body>... """>>> soup = BeautifulSoup(data)>>> img = soup.img>>> >>> img.parent.namea
You can also retrieve the img
tags that have a direct a
parent using a CSS selector:
soup.select('a > img')