<div class="someClass">
<a href="href">
<img alt="some" src="some"/>
</a>
</div>
我使用bs4而且我不能使用a.attrs [‘src’]来获取src,但我可以得到href.我该怎么办?
解决方法:
您可以使用BeautifulSoup来提取html img标记的src属性.在我的示例中,htmlText包含img标记本身,但是这也可以用于URL以及urllib2.
对于URL
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']
对于带有img标签的文本
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']