Python requests庫輕松發(fā)送HTTP請求的終極指南
前言
在現(xiàn)代網(wǎng)絡(luò)編程中,HTTP請求是與Web服務(wù)交互的基礎(chǔ)。Python中的requests庫以其簡潔優(yōu)雅的API設(shè)計(jì),成為開發(fā)者發(fā)送HTTP請求的首選工具。本文將全面介紹requests庫的使用方法,從基礎(chǔ)請求到高級(jí)技巧,幫助你掌握網(wǎng)絡(luò)數(shù)據(jù)交互的核心技能。
一、requests庫簡介
requests是一個(gè)基于Python開發(fā)的HTTP庫,比Python標(biāo)準(zhǔn)庫中的urllib更加簡單易用。它具有以下特點(diǎn):
人性化的API設(shè)計(jì)
支持連接保持和連接池
支持文件上傳
自動(dòng)內(nèi)容解碼
國際化域名和URL
自動(dòng)實(shí)現(xiàn)持久連接
安裝requests
pip install requests
二、發(fā)送基本HTTP請求
1.GET請求
GET是最常用的HTTP方法,用于從服務(wù)器獲取資源。
import requests
# 基本GET請求
response = requests.get('https://www.example.com')
# 打印響應(yīng)狀態(tài)碼
print(response.status_code)
# 打印響應(yīng)內(nèi)容
print(response.text)
2.帶參數(shù)的GET請求
# 通過params參數(shù)傳遞查詢字符串
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
# 實(shí)際請求的URL
print(response.url) # 輸出: https://httpbin.org/get?key1=value1&key2=value2
3.POST請求
POST通常用于向服務(wù)器提交數(shù)據(jù)。
# 基本POST請求
data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
# 查看服務(wù)器返回的數(shù)據(jù)
print(response.json())
三、請求與響應(yīng)處理
1.響應(yīng)內(nèi)容解析
requests提供了多種方式訪問響應(yīng)內(nèi)容:
response = requests.get('https://www.example.com')
# 文本內(nèi)容
print(response.text)
# 二進(jìn)制內(nèi)容
print(response.content)
# JSON響應(yīng)(自動(dòng)解析)
print(response.json())
# 原始響應(yīng)(用于流式傳輸)
print(response.raw)
2.響應(yīng)狀態(tài)碼
response = requests.get('https://www.example.com')
# 狀態(tài)碼
print(response.status_code)
# 狀態(tài)碼是否成功(200-400范圍內(nèi))
print(response.ok)
# 拋出HTTP錯(cuò)誤(如果請求失敗)
response.raise_for_status()
3.請求頭與響應(yīng)頭
# 自定義請求頭
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json'
}
response = requests.get('https://www.example.com', headers=headers)
# 查看響應(yīng)頭
print(response.headers)
# 獲取特定響應(yīng)頭
print(response.headers['Content-Type'])
四、高級(jí)請求技巧
超時(shí)設(shè)置
# 設(shè)置超時(shí)時(shí)間(秒)
try:
response = requests.get('https://www.example.com', timeout=3)
except requests.exceptions.Timeout:
print("請求超時(shí)")
會(huì)話對(duì)象(Session)
使用Session可以保持某些參數(shù)跨請求,并重用TCP連接,提高性能。
# 創(chuàng)建會(huì)話
session = requests.Session()
# 設(shè)置公共參數(shù)
session.headers.update({'User-Agent': 'MyApp/1.0'})
# 使用會(huì)話發(fā)送請求
response1 = session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
response2 = session.get('https://httpbin.org/cookies')
print(response2.json()) # 會(huì)顯示之前設(shè)置的cookie
代理設(shè)置
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get('https://www.example.com', proxies=proxies)
文件上傳
files = {'file': open('report.xls', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
print(response.text)
流式請求
對(duì)于大文件下載,可以使用流式請求:
response = requests.get('https://www.example.com/bigfile', stream=True)
with open('bigfile', 'wb') as fd:
for chunk in response.iter_content(chunk_size=128):
fd.write(chunk)
五、錯(cuò)誤處理
requests提供了完善的異常處理機(jī)制:
from requests.exceptions import RequestException
try:
response = requests.get('https://www.example.com', timeout=5)
response.raise_for_status() # 檢查請求是否成功
except RequestException as e:
print(f"請求發(fā)生錯(cuò)誤: {e}")
主要異常類型包括:
- ConnectionError:網(wǎng)絡(luò)連接錯(cuò)誤
- Timeout:請求超時(shí)
- TooManyRedirects:重定向過多
- HTTPError:HTTP錯(cuò)誤響應(yīng)
- RequestException:所有requests異常的基類
六、實(shí)際應(yīng)用案例
調(diào)用REST API
# 獲取GitHub用戶信息
response = requests.get('https://api.github.com/users/octocat')
if response.status_code == 200:
user_data = response.json()
print(f"用戶名: {user_data['login']}")
print(f"倉庫數(shù): {user_data['public_repos']}")
else:
print(f"請求失敗,狀態(tài)碼: {response.status_code}")
網(wǎng)頁內(nèi)容抓取
from bs4 import BeautifulSoup
response = requests.get('https://www.example.com')
soup = BeautifulSoup(response.text, 'html.parser')
# 提取所有鏈接
for link in soup.find_all('a'):
print(link.get('href'))
下載文件
url = 'https://www.example.com/sample.pdf'
response = requests.get(url)
with open('sample.pdf', 'wb') as f:
f.write(response.content)
七、性能優(yōu)化建議
使用Session對(duì)象:對(duì)于需要發(fā)送多個(gè)請求到同一主機(jī)的場景,使用Session可以顯著提高性能。
啟用連接池:requests默認(rèn)使用連接池,確保在創(chuàng)建Session時(shí)保持默認(rèn)設(shè)置。
設(shè)置合理的超時(shí):避免請求長時(shí)間掛起,影響程序性能。
流式處理大響應(yīng):對(duì)于大文件下載,使用stream=True可以避免內(nèi)存問題。
合理設(shè)置請求頭:特別是Accept-Encoding可以啟用壓縮傳輸。
八、常見問題解答
Q1: 如何處理HTTPS證書驗(yàn)證?
# 禁用證書驗(yàn)證(不推薦生產(chǎn)環(huán)境使用)
response = requests.get('https://example.com', verify=False)
# 使用自定義CA證書
response = requests.get('https://example.com', verify='/path/to/cert.pem')
Q2: 如何處理重定向?
# 禁用重定向
response = requests.get('http://example.com', allow_redirects=False)
# 獲取重定向歷史
print(response.history)
Q3: 如何調(diào)試請求?
# 啟用詳細(xì)日志
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
結(jié)語
requests庫以其簡潔的API和強(qiáng)大的功能,成為Python開發(fā)者處理HTTP請求的首選工具。通過本文的介紹,相信你已經(jīng)掌握了從基礎(chǔ)到高級(jí)的各種用法。在實(shí)際開發(fā)中,合理運(yùn)用這些技巧可以大大提高開發(fā)效率和程序穩(wěn)定性。
到此這篇關(guān)于Python requests庫輕松發(fā)送HTTP請求的終極指南的文章就介紹到這了,更多相關(guān)Python requests發(fā)送HTTP請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python基礎(chǔ)入門學(xué)習(xí)筆記(Python環(huán)境搭建)
這篇文章主要介紹了python基礎(chǔ)入門學(xué)習(xí)筆記,這是開啟學(xué)習(xí)python基礎(chǔ)知識(shí)的第一篇,夯實(shí)Python基礎(chǔ),才能走的更遠(yuǎn),感興趣的小伙伴們可以參考一下2016-01-01
django創(chuàng)建簡單的頁面響應(yīng)實(shí)例教程
這篇文章主要給大家介紹了關(guān)于django如何創(chuàng)建簡單的頁面響應(yīng)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用django具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
django中賬號(hào)密碼驗(yàn)證登陸功能的實(shí)現(xiàn)方法
這篇文章主要介紹了django中賬號(hào)密碼驗(yàn)證登陸功能的實(shí)現(xiàn)方法,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07
Scrapy爬蟲文件批量運(yùn)行的實(shí)現(xiàn)
這篇文章主要介紹了Scrapy爬蟲文件批量運(yùn)行的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
python如何在pygame中設(shè)置字體并顯示中文詳解
再簡單的游戲界面中均涉及文字處理,下面這篇文章主要給大家介紹了關(guān)于python如何在pygame中設(shè)置字體并顯示中文的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01

