Python 網(wǎng)絡(luò)請求庫 requests 的十個(gè)基本用法
大家好!今天我們要聊聊Python中非常實(shí)用的一個(gè)庫——requests。這個(gè)庫讓發(fā)送HTTP請求變得超級簡單。無論你是想抓取網(wǎng)頁數(shù)據(jù)還是測試API接口,requests都能派上大用場。下面我們就一起來看看如何使用requests完成一些常見的任務(wù)。
引言
隨著互聯(lián)網(wǎng)技術(shù)的發(fā)展,HTTP請求成為開發(fā)者們?nèi)粘9ぷ髦胁豢苫蛉钡囊徊糠帧ython語言以其簡潔易用的特點(diǎn),成為眾多開發(fā)者首選的編程語言之一。而requests庫作為Python中最受歡迎的HTTP客戶端庫之一,更是大大簡化了發(fā)送HTTP請求的過程。本文將詳細(xì)介紹如何利用requests庫執(zhí)行各種類型的HTTP請求,從基礎(chǔ)的GET請求到復(fù)雜的認(rèn)證、文件上傳等高級功能。
發(fā)送GET請求
首先,你需要安裝requests庫。打開命令行工具,輸入以下命令:
pip install requests
安裝完成后,就可以開始使用了。最簡單的GET請求如下:
import requests
# 發(fā)送GET請求
response = requests.get('https://api.github.com')
# 輸出響應(yīng)的內(nèi)容
print(response.text)
這里的response.text會(huì)打印出響應(yīng)的內(nèi)容。如果你想獲取特定信息,可以解析返回的數(shù)據(jù)。比如,如果返回的是JSON格式的數(shù)據(jù),可以用response.json()方法將其轉(zhuǎn)換為Python字典。
獲取頁面的二進(jìn)制數(shù)據(jù)
有時(shí)候我們需要獲取圖片或文件等二進(jìn)制數(shù)據(jù),這時(shí)可以使用requests.get方法并指定stream=True來實(shí)現(xiàn)。
response = requests.get('https://example.com/image.jpg', stream=True)
if not response.ok:
print("Something went wrong")
else:
# 將數(shù)據(jù)保存到本地
with open('image.jpg', 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
這段代碼會(huì)將圖片下載到當(dāng)前目錄下。
添加查詢參數(shù)
很多時(shí)候,我們需要向URL添加查詢參數(shù)。這可以通過傳遞一個(gè)字典給params參數(shù)來實(shí)現(xiàn):
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=payload)
print(response.url) # 輸出: https://httpbin.org/get?key1=value1&key2=value2
這里httpbin.org是一個(gè)測試HTTP請求的好地方。
發(fā)送POST請求
發(fā)送POST請求也很簡單,只需要調(diào)用requests.post方法,并傳入要發(fā)送的數(shù)據(jù)即可:
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.text) # 輸出POST請求的內(nèi)容
處理JSON數(shù)據(jù)
當(dāng)服務(wù)器返回JSON格式的數(shù)據(jù)時(shí),我們可以直接使用response.json()來解析它:
response = requests.get('https://api.github.com/events')
json_response = response.json()
for event in json_response:
print(event['type'])
這段代碼會(huì)打印出GitHub API返回的所有事件類型。
設(shè)置自定義Header
如果你需要設(shè)置HTTP頭部信息,可以通過headers參數(shù)來實(shí)現(xiàn):
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.example.com', headers=headers)
print(response.text[:100]) # 打印前100個(gè)字符
設(shè)置User-Agent可以幫助我們模擬瀏覽器行為。
發(fā)送帶認(rèn)證信息的請求
有時(shí)我們需要訪問需要認(rèn)證的網(wǎng)站或API。requests庫提供了多種認(rèn)證方式,包括基本認(rèn)證(Basic Auth)和OAuth等。下面我們來看一個(gè)基本認(rèn)證的例子:
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth('username', 'password')
response = requests.get('https://api.example.com/secure', auth=auth)
print(response.text)
在這個(gè)例子中,我們使用了HTTPBasicAuth類來提供用戶名和密碼進(jìn)行認(rèn)證。
發(fā)送帶有表單數(shù)據(jù)的請求
當(dāng)我們需要提交表單數(shù)據(jù)時(shí),可以使用requests.post方法,并通過data參數(shù)傳遞字典形式的數(shù)據(jù):
data = {'name': 'John Doe', 'email': 'john@example.com'}
response = requests.post('https://example.com/submit', data=data)
print(response.text)
這段代碼會(huì)發(fā)送包含名字和郵箱的POST請求。
發(fā)送帶有文件的請求
在上傳文件時(shí),可以使用requests.post方法,并通過files參數(shù)傳遞文件對象:
files = {'file': open('example.txt', 'rb')}
response = requests.post('https://example.com/upload', files=files)
print(response.text)
這段代碼會(huì)上傳名為example.txt的文件到服務(wù)器。
處理重定向和超時(shí)
在處理網(wǎng)絡(luò)請求時(shí),我們可能會(huì)遇到重定向和超時(shí)問題。requests庫提供了相應(yīng)的參數(shù)來處理這些問題。
處理重定向:
# 默認(rèn)情況下,requests會(huì)自動(dòng)處理重定向
response = requests.get('http://github.com', allow_redirects=False)
print(response.status_code) # 輸出: 301 (表示重定向)
print(response.headers['location']) # 輸出: https://github.com/
如果不需要自動(dòng)重定向,可以設(shè)置allow_redirects=False。
處理超時(shí):
try:
response = requests.get('https://www.example.com', timeout=5) # 超時(shí)時(shí)間為5秒
except requests.exceptions.Timeout:
print("The request timed out")
else:
print(response.text)
這段代碼設(shè)置了請求的超時(shí)時(shí)間為5秒,如果超過這個(gè)時(shí)間沒有響應(yīng),則會(huì)拋出Timeout異常。
實(shí)戰(zhàn)案例:獲取天氣信息
假設(shè)我們需要獲取某個(gè)城市的天氣信息,可以使用OpenWeatherMap提供的API來實(shí)現(xiàn)。以下是具體的步驟:
- 1注冊一個(gè)OpenWeatherMap賬戶并獲取API密鑰。
- 使用requests庫發(fā)送GET請求獲取天氣數(shù)據(jù)。
下面是完整的代碼示例:
import requests
# API密鑰
api_key = 'your_api_key_here'
city = 'Beijing'
# 構(gòu)建請求URL
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
# 發(fā)送GET請求
response = requests.get(url)
# 檢查響應(yīng)狀態(tài)碼
if response.status_code == 200:
data = response.json()
temperature = data['main']['temp']
description = data['weather'][0]['description']
print(f"Temperature in {city}: {temperature} K")
print(f"Weather description: {description}")
else:
print("Failed to get weather data")
在這段代碼中,我們使用了requests.get方法發(fā)送GET請求,并通過response.json()方法解析返回的JSON數(shù)據(jù)。然后,我們提取了溫度和天氣描述信息并打印出來。
總結(jié)
本文介紹了如何使用requests庫執(zhí)行各種類型的HTTP請求,包括發(fā)送GET/POST請求、處理JSON數(shù)據(jù)、設(shè)置自定義Header、發(fā)送帶認(rèn)證信息的請求、上傳文件、處理重定向和超時(shí)等問題。通過實(shí)戰(zhàn)案例展示了如何利用requests獲取天氣信息,希望這些知識(shí)能夠幫助你在實(shí)際開發(fā)過程中更加高效地處理HTTP請求。