Mike S.
Mike S.

Reputation: 215

Extract element from HTML

I have html:

<div class="img-holder">
 <h1>Sample Image</h1>
 <img src="http://sample.com/img.jpg"/>
</div>

With:

s = soup.find('div', {'class' : 'img-holder'}).h1
s = s.get_text()

Displays the 'Sample image'.

How do i get the image src using the same format?

Upvotes: 0

Views: 57

Answers (2)

Rakesh
Rakesh

Reputation: 82785

Use img.attrs["src"]

Ex:

from bs4 import BeautifulSoup
s = """<div class="img-holder">
 <h1>Sample Image</h1>
 <img src="http://sample.com/img.jpg"/>
</div>"""

soup = BeautifulSoup(s, "html.parser")
s = soup.find('div', {'class' : 'img-holder'})
print( s.img.attrs["src"] )

Upvotes: 2

ScottMcC
ScottMcC

Reputation: 4460

Like this?

soup.find('img')['src']

Upvotes: 0

Related Questions