我用过BeautifulSoup的3和4两个版本,并且注意到bs4
(第四版)似乎比第三版更好地修复了你的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)
>>> print soup
<img onload="javascript:if(this.width>950) this.width=950" />950) this.width=950' src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg">
注意现在>
变成了>
,而且一些位子有点错乱。
此外,当你调用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
[(u'onload', u'javascript:if(this.width>950) this.width=950')]
>>> print soup.findAll('img')[0].attrs
{'onload': 'javascript:if(this.width>950) this.width=950', 'src': 'http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg'}
那么该怎么办呢?
下载BeautifulSoup 4。它可以更好地解析HTML。
顺便提一下,如果你只想得到
src
,就不需要调用
.attrs
:
>>> print soup.findAll('img')[0].get('src')
http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg