问题
<div class="someClass">
<a href="href">
<img alt="some" src="some"/>
</a>
</div>
I use bs4 and I cannot use a.attrs['src'] to get the src, but I can get href. What should I do?
回答1:
You can use BeautifulSoup to extract src attribute of an html img tag. In my example, the htmlText contains the img tag itself but this can be used for a URL too along with urllib2.
For URLs
from BeautifulSoup import BeautifulSoup as BSHTML
import urllib2
page = urllib2.urlopen('http://www.youtube.com/')
soup = BSHTML(page)
images = soup.findAll('img')
for image in images:
#print image source
print image['src']
#print alternate text
print image['alt']
For Texts with img tag
from BeautifulSoup import BeautifulSoup as BSHTML
htmlText = """<img src="https://src1.com/" <img src="https://src2.com/" /> """
soup = BSHTML(htmlText)
images = soup.findAll('img')
for image in images:
print image['src']
回答2:
A link doesn't have attribute src you have to target actual img tag.
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'
来源:https://stackoverflow.com/questions/43982002/extract-src-attribute-from-img-tag-using-beautifulsoup