Beautifulsoup无法从img标签中提取src属性

时间:2013-04-14 10:05:50

标签: html beautifulsoup

这是我的代码:

html = '''<img onload='javascript:if(this.width>950) this.width=950'
src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg">'''
soup = BeautifulSoup(html)
imgs = soup.findAll('img')

print imgs[0].attrs

它会打印[(u'onload', u'javascript:if(this.width>950) this.width=950')]

那么src属性在哪里?

如果我用html = '''<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />'''

之类的内容替换html

我得到的结果为[(u'src', u'/image/fluffybunny.jpg'), (u'title', u'Harvey the bunny'), (u'alt', u'a cute little fluffy bunny')]

我是HTML和beautifulsoup的新手。我错过了一些知识吗?谢谢你的任何想法。

2 个答案:

答案 0 :(得分:8)

我使用BeautifulSoup的第3版和第4版对此进行了测试,并注意到bs4(版本4)似乎比版本3更好地修复了HTML。

使用BeautifulSoup 3:

>>> html = """<img onload='javascript:if(this.width>950) this.width=950' src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg">"""
>>> soup = BeautifulSoup(html) # Version 3 of BeautifulSoup
>>> print soup
<img onload="javascript:if(this.width&gt;950) this.width=950" />950) this.width=950' src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg"&gt;

请注意>现在是&gt;,有些位不合适。

另外,当你调用BeautifulSoup()时,它会将它分开。如果你要打印soup.img,你会得到:

<img onload="javascript:if(this.width&gt;950) this.width=950" />

所以你会错过细节。

使用bs4(BeautifulSoup 4,当前版本):

>>> html = '''<img onload='javascript:if(this.width>950) this.width=950' src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg">'''
>>> soup = BeautifulSoup(html) 
>>> print soup
<html><body><img onload="javascript:if(this.width&gt;950) this.width=950" src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg"/></body></html>

现在使用.attrs:在BeautifulSoup 3中,它返回一个元组列表,就像你发现的那样。在BeautifulSoup 4中,它返回一个字典:

>>> print soup.findAll('img')[0].attrs # Version 3
[(u'onload', u'javascript:if(this.width>950) this.width=950')]

>>> print soup.findAll('img')[0].attrs # Version 4
{'onload': 'javascript:if(this.width>950) this.width=950', 'src': 'http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg'}

那该怎么办? Get BeautifulSoup 4。它会更好地解析HTML。

顺便说一句,如果你想要的只是src,则不需要调用.attrs

>>> print soup.findAll('img')[0].get('src')
http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg

答案 1 :(得分:0)

这种方法很有用:

image=container.find("div",{"class":"ika-picture-flex-box"})
image=image.find_all("source")
image[1].get('srcset')
相关问题