Refer to How to get an attribute value based on the name attribute. record for myself and share with you.

BeautifulSoup4中查找tag的常见方法是:

1
2
>>> soup = BeautifulSoup('<div class="city">')
>>> soup.find("div", class_="city")

然而,有时候我们会遇到一种奇葩情况,就是属性也叫name,如:

1
>>> soup = BeautifulSoup('<div name="city">')

这种情况若采用常规方法是无法运行的,需要换一种思路。

1
>>> soup.find("div", name="city")

正确的方法参考如下,将属性部分用dict的方式表示即可:

1
2
3
4
>>> soup = BeautifulSoup('<META NAME="City" content="Austin">')
>>> soup.find("meta", {"name":"City"})
<meta name="City" content="Austin" />
>>> soup.find("meta", {"name":"City"})['content']