## 初識Requests:安裝和基本使用

我們需要安裝Requests庫。打開命令行,輸入:

```python

pip install requests

安裝完成后,我們就可以開始使用啦!先來看一個最簡單的GET請求:

import requests

# 發送GET請求

response = requests.get('https://api.example.com/users')

print(response.status_code) # 打印狀態碼

print(response.text) # 打印響應內容

小貼士:response.text返回的是字符串格式,如果響應是JSON格式,可以直接用response.json()轉換成Python字典!

1.GET請求進階:添加參數和請求頭

在實際開發中,我們經常需要傳遞查詢參數和自定義請求頭。Requests讓這些操作變得超級簡單:

# 添加查詢參數

params = {

'page': 1,

'size': 10,

'keyword': 'python'

}

headers = {

'User-Agent': 'Mozilla/5.0',

'Authorization': 'Bearer your-token'

}

response = requests.get(

'https://api.example.com/search',

params=params, # 查詢參數會自動拼接到URL中

headers=headers # 自定義請求頭

)

2.POST請求:發送數據

發送POST請求同樣簡單,Requests支持多種格式的數據:

# 發送表單數據

form_data = {

'username': 'xiaomage',

'password': '123456'

}

response = requests.post('https://api.example.com/login', data=form_data)

# 發送JSON數據

json_data = {

'name': '小碼哥',

'age': 18,

'skills': ['Python', 'API測試']

}

response = requests.post('https://api.example.com/users', json=json_data)

小貼士:使用json參數時,Requests會自動將Python字典轉換為JSON格式,并設置正確的Content-Type頭部!

3.異常處理和超時設置

在網絡請求中,異常處理特別重要。

來看看如何優雅地處理可能的錯誤:

try:

# 設置5秒超時

response = requests.get('https://api.example.com/data', timeout=5)

response.raise_for_status() # 如果狀態碼不是2xx,會拋出異常

except requests.exceptions.Timeout:

print('請求超時了!')

except requests.exceptions.RequestException as e:

print(f'遇到錯誤啦:{e}')

4.會話管理:保持登錄狀態

如果需要維持登錄狀態或者復用TCP連接,可以使用會話(Session)對象:

# 創建會話

session = requests.Session()

# 登錄

session.post('https://api.example.com/login', data={'username': 'xiaomage'})

# 后續請求會自動帶上登錄信息(比如Cookie)

response = session.get('https://api.example.com/profile')

5.實戰小練習

來做個小練習吧!調用免費的天氣API獲取天氣信息:

import requests

def get_weather(city):

“”“獲取城市天氣信息”“”

url = f'http://wthrcdn.etouch.cn/weather_mini?city={city}'

try:

response = requests.get(url)

data = response.json()

if data['status'] == 1000:

weather = data['data']['forecast'][0]

return f“{city}今天{weather['type']},{weather['low']}到{weather['high']}”

return f“未找到{city}的天氣信息”

except Exception as e:

return f“獲取天氣信息失敗:{e}”

# 測試一下

print(get_weather('北京'))

本文章轉載微信公眾號@小七學Python

上一篇:

LLM之RAG實戰(二十)|Chunk RAG分塊策略的五個level

下一篇:

基于 RAG 的 LLM 應用程序構建(一):詳述數據源準備工作
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費