Python Web表单提交

通常,与网页的交互需要一些数据通过html页面中的表单提交给服务器。这些网络表单通常用于诸如注册新帐户或提供一些信息(例如姓名或卷号)以检索检查结果的过程。requests模块使用带有所需参数的POST方法优雅地处理此问题。

示例

在下面的示例中,我们通过提供用户名和密码值来使用网站的注册表单。提交值后,将打印响应的结果。

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 >

    .....................
    .....................

上一篇:Python构建URL

下一篇:Python数据库和SQL

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程