一、?Requests的介紹
????????Requests 是一個簡單易用的 HTTP 庫,用于發送各種 HTTP 請求。它由 Kenneth Reitz 創建,并廣泛用于 Python 社區中。
二、?Requests的特點
1、人性化的 API:簡潔的接口使得編寫請求代碼變得簡單直觀。
2、跨平臺:在 Windows、OS X、Linux 等多種操作系統上都可以使用。
3、只包含核心功能:專注于提供基本的 HTTP 請求功能,易于擴展。
4、自動處理 Cookies:自動處理客戶端的 Cookies。
5、自動處理重定向:遵循 HTTP 重定向。
6、SSL 驗證:支持 HTTPS 請求,并默認驗證 SSL 證書。
三、Requests的安裝使用
安裝 Requests 庫
Requests 庫不是 Python 的標準庫,因此需要單獨安裝。可以通過 pip 安裝:
pip install requests
使用 Requests 庫
以下是使用 Requests 庫發送 HTTP 請求的基本步驟:
1. 發送 GET 請求
import requests# 發送 GET 請求
response = requests.get('https://api.github.com')# 獲取響應內容
data = response.text# 打印響應內容
print(data)
2. 發送 POST 請求
import requests# 發送 POST 請求
response = requests.post('https://httpbin.org/post', data={'key': 'value'})# 獲取響應內容
data = response.json() # 響應內容為 JSON 格式# 打印響應內容
print(data)
3. 處理響應
Requests 庫提供了多種方法來處理響應:
response.text
:返回響應內容作為 Unicode 字符串。response.content
:返回響應內容作為字節序列。response.json()
:將響應內容解析為 JSON 格式。
# 假設響應內容為 JSON 格式
data = response.json()
print(data)
4. 發送帶有 Headers 的請求
import requestsheaders = {'User-Agent': 'my-app/0.0.1','Accept': 'application/json',
}response = requests.get('https://api.github.com', headers=headers)
5. 發送帶有認證信息的請求
import requestsusername = 'user'
password = 'pass'response = requests.get('https://api.github.com', auth=(username, password))
6. 發送帶有超時的請求
import requeststry:response = requests.get('https://api.github.com', timeout=0.01)
except requests.exceptions.Timeout:print("請求超時")
四、Requests的詳細使用
以下是一些 Python Requests 庫的高級示例代碼,這些示例展示了如何使用 Requests 庫進行更復雜的操作,如會話管理、文件上傳、代理設置、異常處理等。
1. 會話管理
使用會話(Session)可以在多個請求之間保持某些參數,比如 cookies。
import requests# 創建一個會話對象
with requests.Session() as session:session.headers.update({'x-requested-with': 'XMLHttpRequest'})response = session.get('https://api.example.com/data')print(response.text)
2. 文件上傳
使用 Requests 上傳文件。
import requestsurl = 'https://httpbin.org/post'
files = {'file': open('example.txt', 'rb')}response = requests.post(url, files=files)print(response.text)
3. 代理設置
通過代理發送請求。
import requestsproxies = {'http': 'http://10.10.1.10:3128','https': 'http://10.10.1.10:1080',
}response = requests.get('https://api.example.com/data', proxies=proxies)
print(response.text)
4. 異常處理
處理請求過程中可能出現的異常。
import requests
from requests.exceptions import HTTPErrorurl = 'https://api.example.com/data'try:response = requests.get(url)response.raise_for_status() # 將捕獲HTTP錯誤
except HTTPError as http_err:print(f'HTTP error occurred: {http_err}')
except Exception as err:print(f'Other error occurred: {err}')
else:print(response.text)
5. JSON 數據請求
發送 JSON 數據并解析響應的 JSON。
import requests
import jsonurl = 'https://httpbin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}response = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})
data = response.json()print(data)
6. 流式請求
用于處理大量數據的流式請求。
import requestsurl = 'https://files.pythonhosted.org/packages/source/r/requests/requests-2.25.1.tar.gz'
response = requests.get(url, stream=True)with open('requests-2.25.1.tar.gz', 'wb') as file:for chunk in response.iter_content(chunk_size=1024):file.write(chunk)
7. 自定義認證
使用自定義認證方式,例如基本認證。
import requests
from requests.auth import HTTPBasicAuthurl = 'https://api.example.com/data'
response = requests.get(url, auth=HTTPBasicAuth('username', 'password'))print(response.text)
8. 使用 SSL 證書
當需要驗證 SSL 證書時,可以指定證書路徑。
import requestsurl = 'https://api.example.com/data'
response = requests.get(url, cert='/path/to/certfile')print(response.text)
五、注意事項
- Requests 庫默認不發送?
Accept
?頭部,如果你需要處理 JSON 數據,可能需要手動設置。 - 出于安全考慮,默認情況下 Requests 會驗證 SSL 證書。如果需要跳過 SSL 驗證(不推薦),可以設置?
verify=False
。