Python:BeautifulSoup - 根据name属性获取属性值

Rut*_*uth 80 python beautifulsoup

我想根据其名称打印属性值,例如

<META NAME="City" content="Austin">
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情

soup = BeautifulSoup(f) //f is some HTML containing the above meta tag
for meta_tag in soup('meta'):
    if meta_tag['name'] == 'City':
         print meta_tag['content']
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了一个KeyError: 'name',我相信这是因为BeatifulSoup使用了name,所以它不能用作关键字参数.

the*_*est 138

这很简单,使用以下 -

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<META NAME="City" content="Austin">')
>>> soup.find("meta", {"name":"City"})
<meta name="City" content="Austin" />
>>> soup.find("meta", {"name":"City"})['content']
u'Austin'
Run Code Online (Sandbox Code Playgroud)

如果有任何不清楚的地方发表评论.


Del*_*ous 23

theharshest回答了这个问题,但这是另一种做同样事情的方法.此外,在您的示例中,您有大写的NAME,在您的代码中,您有小写的名称.

s = '<div class="question" id="get attrs" name="python" x="something">Hello World</div>'
soup = BeautifulSoup(s)

attributes_dictionary = soup.find('div').attrs
print attributes_dictionary
# prints: {'id': 'get attrs', 'x': 'something', 'class': ['question'], 'name': 'python'}

print attributes_dictionary['class'][0]
# prints: question

print soup.find('div').get_text()
# prints: Hello World
Run Code Online (Sandbox Code Playgroud)


小智 8

以下作品:

from bs4 import BeautifulSoup

soup = BeautifulSoup('<META NAME="City" content="Austin">', 'html.parser')

metas = soup.find_all("meta")

for meta in metas:
    print meta.attrs['content'], meta.attrs['name']
Run Code Online (Sandbox Code Playgroud)


Leo*_*son 7

theharshest的答案是最好的解决方案,但是你遇到的问题仅与美丽汤中的Tag对象就像Python字典这样的事实有关.如果您在没有'name'属性的标记上访问标记['name'],您将获得KeyError.


don*_*don 7

晚了6年,但是我一直在寻找如何提取html元素的tag 属性值,因此:

<span property="addressLocality">Ayr</span>
Run Code Online (Sandbox Code Playgroud)

我想要“ addressLocality”。我一直被引导回到这里,但是答案并没有真正解决我的问题。

我最终如何做到的:

>>> from bs4 import BeautifulSoup as bs

>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}
Run Code Online (Sandbox Code Playgroud)

因为这是命令,所以您还可以使用keys和'值'

>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助其他人!