使用 BeautifulSoup 获取基于 name 属性的属性值

我想根据它的名称打印一个属性值,例如

<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 使用了 name,所以它不能用作关键字参数。

196566 次浏览

很简单,用以下方法:

>>> 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']
'Austin'

最严厉的回答是最好的解决方案,但是仅供参考,您遇到的问题与 Beautiful Soup 中的 Tag 对象的作用类似于 Python 字典这一事实有关。如果您访问标记[‘ name’]上没有‘ name’属性的标记,就会得到 KeyError。

最严厉的回答了这个问题,但是这里有另一种方法来做同样的事情。 此外,在您的示例中,您有大写的 NAME,在您的代码中,您有小写的 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

One can also try this solution :

查找在表的范围内写入的值

HtmlContent


<table>
<tr>
<th>
ID
</th>
<th>
Name
</th>
</tr>




<tr>
<td>
<span name="spanId" class="spanclass">ID123</span>
</td>


<td>
<span>Bonny</span>
</td>
</tr>
</table>

Python 代码


soup = BeautifulSoup(htmlContent, "lxml")
soup.prettify()


tables = soup.find_all("table")


for table in tables:
storeValueRows = table.find_all("tr")
thValue = storeValueRows[0].find_all("th")[0].string


if (thValue == "ID"): # with this condition I am verifying that this html is correct, that I wanted.
value = storeValueRows[1].find_all("span")[0].string
value = value.strip()


# storeValueRows[1] will represent <tr> tag of table located at first index and find_all("span")[0] will give me <span> tag and '.string' will give me value


# value.strip() - will remove space from start and end of the string.


# find using attribute :


value = storeValueRows[1].find("span", {"name":"spanId"})['class']
print value
# this will print spanclass

以下作品:

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']

晚了6年,但我一直在寻找如何提取 Html 元素的标记 属性值,所以:

<span property="addressLocality">Ayr</span>

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

我最终是如何做到的:

>>> 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'}

As it's a dict, you can then also use keys and 'values'

>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']

希望能帮到别人!

If tdd='<td class="abc"> 75</td>'
In Beautifulsoup


if(tdd.has_attr('class')):
print(tdd.attrs['class'][0])




Result:  abc