用 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']
相关文章