Extract `src` attribute from `img` tag using BeautifulSoup

前端 未结 4 2044
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 09:13

I use bs4 an

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 09:49

    A link doesn't have attribute src you have to target actual img tag.

    import bs4
    
    html = """"""
    
    soup = bs4.BeautifulSoup(html, "html.parser")
    
    # this will return src attrib from img tag that is inside 'a' tag
    soup.a.img['src']
    
    >>> 'some'
    
    # if you have more then one 'a' tag
    for a in soup.find_all('a'):
        if a.img:
            print(a.img['src'])
    
    >>> 'some'
    

提交回复
热议问题