Python:BeautifulSoup-根据名称属性获取属性值 [英] Python: BeautifulSoup - get an attribute value based on the name attribute
本文介绍了Python:BeautifulSoup-根据名称属性获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据属性名称打印属性值,例如
I want to print an attribute value based on its name, take for example
<META NAME="City" content="Austin">
我想做这样的事情
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']
上面的代码给出了KeyError: 'name'
,我相信这是因为BeatifulSoup使用了名称,所以它不能用作关键字参数.
The above code give a KeyError: 'name'
, I believe this is because name is used by BeatifulSoup so it can't be used as a keyword argument.
推荐答案
这很简单,请使用以下命令-
It's pretty simple, use the following -
>>> 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'
如果不清楚,请发表评论.
Leave a comment if anything is not clear.
这篇关于Python:BeautifulSoup-根据名称属性获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文