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

for*_*tyj 4 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
Run Code Online (Sandbox Code Playgroud)

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

那么src属性在哪里?

如果我用类似的东西替换html html = '''<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />'''

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

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

Ter*_*ryA 8

我用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&gt;950) this.width=950" />950) this.width=950' src="http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg"&gt;
Run Code Online (Sandbox Code Playgroud)

注意>现在&gt;和一些位是不合适的.

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

<img onload="javascript:if(this.width&gt;950) this.width=950" />
Run Code Online (Sandbox Code Playgroud)

所以你会错过细节.

使用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>
Run Code Online (Sandbox Code Playgroud)

现在.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'}
Run Code Online (Sandbox Code Playgroud)

那么该怎么办?获取BeautifulSoup 4.它会更好地解析HTML.

顺便说一下,如果您想要的只是src,.attrs那么就不需要打电话:

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