Extract attribute from tag using BeautifulSoup

PHOTO EMBED

Sun Oct 25 2020 06:35:44 GMT+0000 (Coordinated Universal Time)

Saved by @ianh #python #beautifulsoup

import bs4

html = """<div class="someClass">
    <a href="href">
        <img alt="some" src="some"/>
    </a>
</div>"""

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'
content_copyCOPY

https://stackoverflow.com/questions/43982002/extract-src-attribute-from-img-tag-using-beautifulsoup/47166671