Extracting an attribute value with beautifulsoup(用 beautifulsoup 提取属性值)
问题描述
我正在尝试提取单个值"的内容;特定输入"中的属性网页上的标签.我使用以下代码:
I am trying to extract the content of a single "value" attribute in a specific "input" tag on a webpage. I use the following code:
import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)
inputTag = soup.findAll(attrs={"name" : "stainfo"})
output = inputTag['value']
print str(output)
我得到一个 TypeError:列表索引必须是整数,而不是 str
I get a TypeError: list indices must be integers, not str
尽管从 Beautifulsoup 文档中我了解到字符串在这里应该不是问题......但我不是专家,我可能误解了.
even though from the Beautifulsoup documentation i understand that strings should not be a problem here... but i a no specialist and i may have misunderstood.
非常感谢任何建议!
推荐答案
.find_all()
返回所有找到的元素的列表,所以:
.find_all()
returns list of all found elements, so:
input_tag = soup.find_all(attrs={"name" : "stainfo"})
input_tag
是一个列表(可能只包含一个元素).取决于你到底想要什么,你应该做什么:
input_tag
is a list (probably containing only one element). Depending on what you want exactly you either should do:
output = input_tag[0]['value']
或使用 .find()
方法,它只返回一个(第一个)找到的元素:
or use .find()
method which returns only one (first) found element:
input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']
这篇关于用 beautifulsoup 提取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用 beautifulsoup 提取属性值


- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01