用beautifulsoup提取一个属性值 [英] Extracting an attribute value with beautifulsoup

查看:65
本文介绍了用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)

我得到一个类型错误:列表索引必须是整数,而不是 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提取一个属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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