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 提取属性值
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
