- Python - 网络编程
- Python - 简介网络
- Python - 网络环境
- Python - 互联网协议
- Python - IP 地址
- Python - DNS 查找
- Python - 路由
- Python - HTTP 请求
- Python - HTTP 响应
- Python - HTTP 标头
- Python - 自定义 HTTP 请求
- Python - 请求状态代码
- Python - HTTP 身份验证
- Python - HTTP 数据下载
- Python - 连接重复使用
- Python - 网络接口
- Python - Socket 编程
- Python - HTTP 客户端
- Python - HTTP 服务器
- Python - 构建 URL
- Python - Web 表单提交
- Python - 数据库和 SQL
- Python - Telnet
- Python - 电子邮件
- Python - SMTP
- Python - POP3
- Python - IMAP
- Python - SSH
- Python - FTP
- Python - SFTP
- Python - Web 服务器
- Python - 数据上传
- Python - 代理服务器
- Python - 目录清单
- Python - 远程过程调用
- Python - RPC JSON 服务器
- Python - Google 地图
- Python - RSS 源
Python - Web 表单提交
通常,与网页交互需要通过 HTML 页面中显示的表单向服务器提交一些数据。这些 Web 表单通常用于以下流程:注册一个新帐户,或提供名称或学号等信息,以获取考试结果。requests 模块使用 POST 方法(其中包含所需参数)妥善处理此问题。
示例
在下面的示例中,我们通过提供用户 ID 和密码值来使用网站的注册表单。提交值后,我们将打印响应。
import requests
ID_USERNAME = 'signup-user-name'
ID_PASSWORD = 'signup-user-password'
USERNAME = 'username'
PASSWORD = 'yourpassword'
SIGNUP_URL = 'http://codepad.org/login'
def submit_form():
"""Submit a form"""
payload = {ID_USERNAME : USERNAME, ID_PASSWORD : PASSWORD,}
resp = requests.get(SIGNUP_URL)
print "Response to GET request: %s" %resp.content
resp = requests.post(SIGNUP_URL, payload)
print "Headers from a POST request response: %s" %resp.headers
#print "HTML Response: %s" %resp.read()
if __name__ == '__main__':
submit_form()
当我们运行上述程序时,会得到以下输出 -
Response to GET request: <!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
<meta HTTP-EQUIV="Expires" CONTENT="-1">
<title>Login - codepad</title>
<link href="/main.css" media="screen" rel="stylesheet" type="text/css" />
<style type="text/css">
</style>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function onRecaptcha(token) {
document.getElementById("editor-form").submit();
}
</script>
</head>
<body >
.....................
.....................
广告