我用 BeautifulSoup 的第三版和第四版对此进行了测试,发现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>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>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>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