如何使用python获取隐藏输入的值? [英] How to get the hidden input's value by using python?

查看:195
本文介绍了如何使用python获取隐藏输入的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从html页面获取输入值

How can i get input value from html page

喜欢

<input type="hidden" name="captId" value="AqXpRsh3s9QHfxUb6r4b7uOWqMT" ng-model="captId">

我有输入名称 [ name="captId" ] 并且需要他的值

I have input name [ name="captId" ] and need his value

import re , urllib ,  urllib2
a = urllib2.urlopen('http://www.example.com/','').read()

谢谢

更新 1

我安装了 BeautifulSoup 并使用了它,但出现了一些错误

I installed BeautifulSoup and used it but there some errors

代码

 import re , urllib ,  urllib2
 a = urllib2.urlopen('http://www.example.com/','').read()
 soup = BeautifulSoup(a)
 value = soup.find('input', {'name': 'scnt'}).get('value')

错误

"soup = BeautifulSoup(a)NameError: name 'BeautifulSoup' 未定义"

"soup = BeautifulSoup(a) NameError: name 'BeautifulSoup' is not defined"

推荐答案

使用 re 模块解析 xml 或 html 通常被认为是不好的做法.仅当对您尝试解析的页面负责时才使用它.如果没有,要么您的正则表达式非常复杂,要么如果有人将 <input type="hidden" name=.../> 替换为 <input name=,您的脚本可能会中断"..." type="hidden" .../> 或几乎任何其他内容.

Using re module to parse xml or html is generally considered as bad practice. Use it only if you are responsable for the page you try to parse. If not, either your regexes are awfully complex, or your script could break if someone replaces <input type="hidden" name=.../> with <input name="..." type="hidden" .../> or almost anything else.

BeautifulSoup 是一个 html 解析器:

BeautifulSoup is a html parser that :

  • 自动修复小错误(未关闭的标签...)
  • 构建 DOM 树
  • 允许您浏览树,搜索具有特定属性的特定标签
  • 可用于 Python 2 和 3

除非您有充分的理由不这样做,否则您应该使用它而不是 re 进行 HTML 解析.

Unless you have good reasons not to do it, you should use it rather than re for HTML parsing.

例如假设 txt 包含整个页面,查找所有隐藏字段将像这样简单:

For example assuming that txt contains the whole page, find all hidden fields would be as simple as :

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 ?

这篇关于如何使用python获取隐藏输入的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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