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

4

这是我的代码:

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替换为像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还很陌生。 我是不是缺少一些知识? 谢谢任何想法。

2个回答

9

我用过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) # 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'}

那么该怎么办呢?下载BeautifulSoup 4。它可以更好地解析HTML。
顺便提一下,如果你只想得到src,就不需要调用.attrs
>>> print soup.findAll('img')[0].get('src')
http://ww4.sinaimg.cn/mw600/c3107d40jw1e3rt4509j.jpg

感谢您提供的出色答案和详细信息。我没有配置SO自动发送回复到我的电子邮件,所以我看到这个有点晚了。我安装了bs4,它正在工作! - foresightyj

0

这种方法可能很有用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接