python - 用 beautifulsoup 提取属性值

标签 python parsing attributes beautifulsoup

我正在尝试在网页上的特定“输入”标签中提取单个“值”属性的内容。我使用以下代码:

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

尽管从 Beautifulsoup 文档中我了解到字符串在这里应该不是问题......但我不是专家,我可能误解了。

非常感谢任何建议!

最佳答案

.find_all() 返回所有找到的元素的列表,所以:

input_tag = soup.find_all(attrs={"name" : "stainfo"})

input_tag 是一个列表(可能只包含一个元素)。取决于你到底想要什么,你应该做什么:

output = input_tag[0]['value']

或使用 .find() 方法,它只返回一个(第一个)找到的元素:

input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']

关于python - 用 beautifulsoup 提取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2612548/

相关文章:

python - OpenCV断言失败,并带有负值

c++ - 为什么从 std::istream 读取记录结构字段失败,我该如何解决?

ruby-on-rails - Ruby 解析数组(特殊情况)

r - 根据R中的属性表值导出栅格

python - 当 uwsgi 重新加载到 flask 中时保留全局数据

python - GAE python : Process terminated because the backend was stopped

python - 使用当前日期时间和过去的历史预测用户输入

java - 正在解析HH :mm (with two digits minute) to LocalTime with JodaTime

css - 如何通过 TagHelper 获取 HTML 属性的值?

c# - 你能强制将枚举值序列化为整数吗?