Get immediate parent tag with BeautifulSoup in Python

后端 未结 1 750
眼角桃花
眼角桃花 2020-12-30 01:58

I\'ve researched this question but haven\'t seen an actual solution to solving this. I\'m using BeautifulSoup with Python and what I\'m looking to do is get all image tags f

相关标签:
1条回答
  • 2020-12-30 02:50

    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.name
    a
    

    You can also retrieve the img tags that have a direct a parent using a CSS selector:

    soup.select('a > img')
    
    0 讨论(0)
提交回复
热议问题