如何使用python获取隐藏输入的值?

How to get the hidden input's value by using 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 ?