如果属性名称重复,如何使用BeautifulSoup获取属性值

时间:2018-06-15 10:05:31

标签: python beautifulsoup attributes find

我在下面写了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总是获取特定属性名称的最新值。

有关这种情况的任何建议吗?

1 个答案:

答案 0 :(得分: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将需要单独安装。

相关问题