【问题标题】:Beautifulsoup can't extract src attribute from img tagBeautifulsoup 无法从 img 标签中提取 src 属性
【发布时间】:2013-04-06 13:05:19
【问题描述】:

这是我的代码:

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&gt;950) this.width=950')]

那么src 属性在哪里?

如果我用 html = '''&lt;img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" /&gt;''' 之类的东西替换 html

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

我对 HTML 和 beautifulsoup 很陌生。我缺少一些知识吗?感谢您的任何想法。

【问题讨论】:

    标签: html beautifulsoup


    【解决方案1】:

    我用 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;
    

    注意&amp;gt; 现在是&amp;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
    

    【讨论】:

    • 感谢您的出色回答和所有细节。我没有将 SO 配置为自动向我的电子邮件发送回复,所以我读到了这篇文章。我安装了 bs4,它正在工作!
    • @foresightyj 哈哈没问题:)
    【解决方案2】:

    这种方法很有用:

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

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2017-10-14
      • 1970-01-01
      • 2022-10-21
      • 2020-12-01
      • 1970-01-01
      • 2016-10-29
      • 2018-01-07
      • 2018-07-18
      相关资源
      最近更新 更多