使用 Python 程式設計的 GET 和 POST 請求


Python 可用於訪問網頁以及將內容釋出到網頁。有很多模組,如 httplib、urllib、httplib2 等,但請求模組是最簡單的,可用於編寫涉及 GET 和 POST 方法的更簡單但功能更強大的程式。

GET 方法

GET 方法是用於從網路 URL 獲取資料的 python 請求模組的一部分。在下面的示例中,我們訪問自己的網站並透過 get 方法找出各種響應。我們獲得編碼、響應時間以及標頭和正文部分。

範例

 即時演示

import requests

req = requests.get('https://tutorialspoint.tw/')

# Page encoding
e = req.encoding
print("Encoding: ",e)

# Response code
s = req.status_code
print("Response code: ",s)

# Response Time
t = req.elapsed
print("Response Time: ",t)


t = req.headers['Content-Type']
print("Header: ",t)

z = req.text
print("\nSome text from the web page:\n",z[0:200])

輸出

執行以上程式碼會產生以下結果 -

Encoding: UTF-8
Response code: 200
Response Time: 0:00:00.103850
Header: text/html; charset=UTF-8

Some text from the web page:

POST 方法

POST 方法用於主要透過表單將資料傳送到伺服器以在伺服器中建立或更新資料。請求模組為我們提供 post 方法,該方法可直接透過獲取 URL 和資料引數的值來發送資料。

在下面的示例中,我們透過 post 方法將一些資料釋出到 httpbin.org 網站並獲得有關如何釋出資料的響應。

範例

 即時演示

import requests
in_values = {'username':'Jack','password':'Hello'}
res = requests.post('https://httpbin.org/post',data = in_values)
print(res.text)

輸出

執行以上程式碼會產生以下結果 -

{
"args": {},
"data": "",
"files": {},
"form": {
"password": "Hello",
"username": "Jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "28",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5ef75488-969f97a68bb72642b97b6d50"
},
"json": null,
"origin": "122.xxx.yy.zzz",
"url": "https://httpbin.org/post"
}

更新於: 10-07-2020

3K+ 瀏覽量

開啟您的 職業

完成課程以獲取認證

開始學習
廣告
© . All rights reserved.