【问题标题】:How to use BeautifulSoup to get attribute value if the attribute name duplicated如果属性名称重复,如何使用 BeautifulSoup 获取属性值
【发布时间】:2018-06-15 10:05:31
【问题描述】:

我在下面写了 Python 代码来通过 BeautifulSoup 解析 HTML:

parsed_html = BeautifulSoup('<img id = \'defualtPagePic\' src="http://my.com/images/realTarget.jpg" alt="test" src="http://my.com/images/fakeTarget.jpg" alt="too bad" onError="this.src=\'http://my.com/images/veryBad.jpg\';" />', "html.parser")
print("a >> "+ str(parsed_html.find(id="defualtPagePic").attrs))
print("b >> "+ str(parsed_html.find(id="defualtPagePic")['src']))

这是执行结果:

a >> {'id': 'defualtPagePic', 'src': 'http://my.com/images/fakeTarget.jpg', 'alt': 'too bad', 'onerror': "this.src='http://my.com/images/veryBad.jpg';"}
b >> http://my.com/images/fakeTarget.jpg

我想获得“realTarget.jpg”,但我失败了并获得了“fakeTarget.jpg”。 我认为原因是 BeautifulSoup 总是获取特定属性名称的最新值。

对这种情况有什么建议吗?

【问题讨论】:

    标签: python beautifulsoup attributes find


    【解决方案1】:

    您可以切换到使用lxml 解析器,如下所示:

    html = '<img id = \'defualtPagePic\' src="http://my.com/images/realTarget.jpg" alt="test" src="http://my.com/images/fakeTarget.jpg" alt="too bad" onError="this.src=\'http://my.com/images/veryBad.jpg\';" />'
    
    soup = BeautifulSoup(html, "lxml")
    print(soup.img['src'])
    

    然后会显示:

    http://my.com/images/realTarget.jpg
    

    如果没有,lxml 需要单独安装。

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2020-10-05
      • 2012-03-13
      • 2013-09-14
      • 2013-11-27
      • 2017-08-28
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多