- 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 >
.....................
.....................
廣告