最後更新日期:2025 年 03 月 23 日
Table of Contents
用途
1、取得網頁原始碼
2、類似 Postman 的 API Client
3、其他 HTTP i請求
安裝
pip install requests
範例程式碼
1、用 GET 方法取得網頁原始碼
import requests
response = requests.get('https://udn.com');
# 也可以用這種方式,功能完全相同
# response = requests.request('GET', 'https://udn.com')
# 列出網頁內容文字
print(response.text)
# 列出 HTTP 狀態碼
print(response.status_code)
# 列出網頁編碼
print(response.encoding)
# 列出 Response Header
print(response.headers)
2、在 GET 請求中加入 url 參數
import requests
params = {'q': 'python', 'start': 10}
response = requests.get('https://google.com/search', params=params)
# 列出請求的 url 位址
print(response.url)
3、在 api 請求中,加入 headers 參數
比較常用的是
1、指定認證用的 Token
2、說明要送出的資料型態為 json
import requests
url = 'http://apidemo.kirin.app/api/categories'
headers = {
'Authorization':'Bearer <你的Token>',
'Content-Type':'application/json'
}
response = requests.get(url, headers=headers)
print(response.text)
4、處理 api 取得的 json 資料
import requests
url = 'http://apidemo.kirin.app/api/categories/1'
response = requests.get(url, headers=headers)
print(response.text)
# 把 json 字串,轉成 array 或 dict
category = response.json()
# 這樣就可以存取其中的元素
print(category['name'])
5、使用 POST 方法新增表單 (F資料
這是模擬表單送出的狀況,但是,通常會遇到 CSRF 的問題而被伺服端拒絕,除非伺服端不做 CSRF 的確認。
表單欄位的資料會以字典 (Dictionary) 的型式指定給 data 參數。
import requests
url = 'https://apidemo.kirin.app/api/contacts'
headers = {
'Authorization':'Bearer <你的Token>',
}
payload = {'name': "John", 'phone': '0911222333'}
response = requests.post(url, headers=headers, data=payload)
print(response.text)
6、使用 POST 方法新增 json 資料
要注意的地方有 2 個:
1、在 headers 中加入 'Content-Type':'application/json'
2、要傳送的資料,要用 json.dumps()
處理
import requests
import json
url = 'http://localhost/api/v1/ssac/tenders/lab'
headers = {
'Authorization':'Bearer <你的Tonek>',
'Content-Type':'application/json'
}
payload = [{'name': "John", 'phone': '0911222333'}, {'name': 'Mary', 'phone': '0922333444'}]
response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.text)
參考資料
https://ithelp.ithome.com.tw/articles/10220161
https://www.youtube.com/playlist?list=PLQKDzuA2cCjoVnT8bnbCGNZvJxwYtRbKu
https://www.youtube.com/watch?v=j4zfEisXsP4&list=PL8VzFQ8k4U1L5QpSapVEzoSfob-4CR8zM&index=66
Comments