You need to check parent 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.name a
You can also get img tags that have a direct parent a using the CSS selector :
soup.select('a > img')
source share