使用 BeautifulSoup 根据名称属性获取属性值
- 2025-04-16 08:57:00
- admin 原创
- 17
问题描述:
我想根据属性名称打印属性值,例如
<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 使用,所以它不能用作关键字参数。
解决方案 1:
这很简单,使用以下命令:
>>> 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'
解决方案 2:
theharshest回答了这个问题,但这里有另一种方法可以实现同样的效果。另外,在你的例子中,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
解决方案 3:
虽然晚了 6 年,但我一直在寻找如何提取html 元素的标签 属性值,因此:
<span property="addressLocality">Ayr</span>
我想要“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'}
因为它是一个字典,所以你也可以使用keys
和“值”
>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']
希望它能帮助别人!
解决方案 4:
theharshest 的答案是最好的解决方案,但仅供参考,您遇到的问题与 Beautiful Soup 中的 Tag 对象的作用类似于 Python 字典有关。如果您在没有 'name' 属性的标签上访问 tag['name'] ,则会收到 KeyError 错误。
解决方案 5:
以下作品:
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内容
<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
解决方案 7:
If tdd='<td class="abc"> 75</td>'
In Beautifulsoup
if(tdd.has_attr('class')):
print(tdd.attrs['class'][0])
Result: abc
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD