4.1 處理回應
模組 requests 提供了方便的方法來處理伺服器的回應。
狀態碼
除了回應,伺服器還會附帶請求處理的狀態。狀態資訊包含在 status_code 和 reason 欄位中。以下是範例:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.status_code) # 輸出回應的狀態碼
print(response.reason) # 輸出狀態的文字描述
print(response.ok) # 如果狀態碼小於400,回傳True
標頭
當然,哪個 HTTP 請求能沒有標頭呢?如果你需要請求的標頭或回應的標頭,可以透過 headers 欄位來取得:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.headers) # 輸出回應的標頭
print(response.headers['Content-Type']) # 輸出特定標頭的值
回應的主體
伺服器的回應可能包含一些位元組、文字、json 或 xml。如果你知道你向伺服器請求的是什麼,可以直接使用以下的 方法/欄位來取得所需的物件:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.text) # 以文字形式輸出回應的主體
print(response.json()) # 以JSON形式輸出回應的主體
print(response.content) # 以位元組形式輸出回應的主體
更多關於標頭 (headers) 和回應狀態的詳情,你將在網路結構的課程中學到。
4.2 錯誤處理
模組 requests 提供了用於錯誤處理的例外狀況。
HTTP 標準不假定例外狀況,而是使用錯誤碼 (status_code)。如果你希望不成功的請求能生成一個 Python 的例外,需要 顯式調用 函數 raise_for_status()。
範例:
import requests
try:
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
response.raise_for_status() # 為狀態碼4xx和5xx生成例外
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
except Exception as err:
print(f"Other error occurred: {err}")
else:
print("Success!")
更多關於錯誤碼的詳情你可以從網路結構的課程中了解。
4.3 發送數據
在發明 JSON 之前,大量資料是透過「表單」傳送的。表單是瀏覽器頁面上的一個特殊物件(和 HTTP 的資料標準)。如果你想以 「表單」的方式發送資料,那麼只需在請求中附帶 data 參數。
重要! GET 請求不支持表單,因為它們不包含請求的主體。所有資料只能在 URL 中傳輸。
在 GET 請求 中發送數據
在 GET 請求 中,資料是通過 URL 參數傳送的。這裡有個範例:
import requests
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url) # 輸出帶有增加參數的URL
發送表單數據
我們將使用 POST 請求 來向伺服器發送資料。
範例:
import requests
data = {
'username': 'example',
'password': 'password'
}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json())
發送文件
如果你想在網路上發送二進位資料,例如,上傳圖片,那麼你需要在請求中透過 files 參數來傳遞你的文件或多個文件。
範例:
import requests
files = {'file': open('example.txt', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
print(response.json())
簡單如ABC。如果你想發送多個文件,只需在 files 變數中列出它們。
重要! 請記得在發送後關閉文件,以避免資源泄露。最好使用 with 結構,這樣可以在操作完成後自動關閉文件:
import requests
with open('example.txt', 'rb') as f:
files = {'file': f}
response = requests.post('https://httpbin.org/post', files=files)
print(response.json())
4.4 登錄和授權
API (Application Programming Interface) 是一組規則和協議,允許不同的程式相互交互。許多網站和服務只允許經過登入的使用者 發送請求並使用其 API。
成功登入後,你會得到一個特別的物件——會話 (session),它包含了你與伺服器的「已授權會話」的唯一編號。對於未來的請求,你 需要使用這個物件。
身份驗證
為了登入伺服器,需要進行身份驗證(登入過程),並在請求中附帶憑證。
import requests
from requests.auth import HTTPBasicAuth
response = requests.get('https://httpbin.org/basic-auth/user/pass', \
auth=HTTPBasicAuth('user', 'pass'))
print(response.status_code)
這就是授權的過程,但通常與會話一起使用。
使用會話
會話允許在多次請求之間保存參數,比如 cookies 或用戶的授權資訊。
import requests
payload = {
'username': 'your_username',
'password': 'your_password'
}
# 創建會話
session = requests.Session()
# 登入站點
login_response = session.post('https://example.com/login', data = payload)
# 作為已登入用戶進行進一步的會話操作
data_response = session.get('https://example.com/api/data')
print(data_response.json())
GO TO FULL VERSION