使用 BeautifulSoup 根据 name 属性获取属性值 [英] Get an attribute value based on the name attribute with BeautifulSoup

查看:46
本文介绍了使用 BeautifulSoup 根据 name 属性获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据名称打印一个属性值,举个例子

我想做这样的事情

soup = BeautifulSoup(f) # f 是一些包含上述元标记的 HTML对于汤中的元标签(meta"):如果 meta_tag[name"] == City":打印(meta_tag [内容"])

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

解决方案

很简单,用下面的-

<预><代码>>>>从 bs4 导入 BeautifulSoup>>>汤 = BeautifulSoup('<META NAME="City" content="Austin">')>>>汤.find(元",{名称":城市"})<meta name="City" content="Austin"/>>>>汤.find("meta", {"name":"City"})['content']你是奥斯汀

如果有什么不清楚的,请发表评论.

I want to print an attribute value based on its name, take for example

<META NAME="City" content="Austin">

I want to do something like this

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"])

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.

这篇关于使用 BeautifulSoup 根据 name 属性获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆