如何使用python获取隐藏输入的值?
问题内容:
我如何从HTML页面获取输入值
喜欢
<input type="hidden" name="captId" value="AqXpRsh3s9QHfxUb6r4b7uOWqMT" ng-model="captId">
我有输入名称[name =“ captId”]并需要他的值
import re , urllib , urllib2
a = urllib2.urlopen('http://www.example.com/','').read()
谢谢
更新1
我安装并使用了BeautifulSoup,但出现了一些错误
码
import re , urllib , urllib2
a = urllib2.urlopen('http://www.example.com/','').read()
soup = BeautifulSoup(a)
value = soup.find('input', {'name': 'scnt'}).get('value')
错误
“汤= BeautifulSoup(a)NameError:未定义名称’BeautifulSoup’”
问题答案:
re
通常认为使用模块来解析xml或html是不好的做法。仅当 您
负责尝试解析的页面时才使用它。如果不是,则您的正则表达式非常复杂,或者如果有人替换<input type="hidden" name=.../>
为<input name="..." type="hidden" .../>
或几乎替换为其他任何内容,则脚本可能会中断。
BeautifulSoup是一个HTML解析器,它可以:
- 自动修复较小的错误(未关闭的标签…)
- 建立一个DOM树
- 允许您浏览树,搜索具有特定属性的特定标签
- 适用于Python 2和3
除非有充分的理由不这样做,否则应使用它而不是re
HTML解析。
例如,假设txt
包含整个页面,则查找所有隐藏字段将非常简单:
from bs4 import BeautifulSoup
soup = BeautifulSoup(txt)
hidden_tags = soup.find_all("input", type="hidden")
for tag in hidden_tags:
# tag.name is the name and tag.value the value, simple isn't it ?