## 初識(shí)Requests:安裝和基本使用

我們需要安裝Requests庫(kù)。打開(kāi)命令行,輸入:

```python

pip install requests

安裝完成后,我們就可以開(kāi)始使用啦!先來(lái)看一個(gè)最簡(jiǎn)單的GET請(qǐng)求:

import requests

# 發(fā)送GET請(qǐng)求

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

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

print(response.text) # 打印響應(yīng)內(nèi)容

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

1.GET請(qǐng)求進(jìn)階:添加參數(shù)和請(qǐng)求頭

在實(shí)際開(kāi)發(fā)中,我們經(jīng)常需要傳遞查詢參數(shù)和自定義請(qǐng)求頭。Requests讓這些操作變得超級(jí)簡(jiǎn)單:

# 添加查詢參數(shù)

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, # 查詢參數(shù)會(huì)自動(dòng)拼接到URL中

headers=headers # 自定義請(qǐng)求頭

)

2.POST請(qǐng)求:發(fā)送數(shù)據(jù)

發(fā)送POST請(qǐng)求同樣簡(jiǎn)單,Requests支持多種格式的數(shù)據(jù):

# 發(fā)送表單數(shù)據(jù)

form_data = {

'username': 'xiaomage',

'password': '123456'

}

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

# 發(fā)送JSON數(shù)據(jù)

json_data = {

'name': '小碼哥',

'age': 18,

'skills': ['Python', 'API測(cè)試']

}

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

小貼士:使用json參數(shù)時(shí),Requests會(huì)自動(dòng)將Python字典轉(zhuǎn)換為JSON格式,并設(shè)置正確的Content-Type頭部!

3.異常處理和超時(shí)設(shè)置

在網(wǎng)絡(luò)請(qǐng)求中,異常處理特別重要。

來(lái)看看如何優(yōu)雅地處理可能的錯(cuò)誤:

try:

# 設(shè)置5秒超時(shí)

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

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

except requests.exceptions.Timeout:

print('請(qǐng)求超時(shí)了!')

except requests.exceptions.RequestException as e:

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

4.會(huì)話管理:保持登錄狀態(tài)

如果需要維持登錄狀態(tài)或者復(fù)用TCP連接,可以使用會(huì)話(Session)對(duì)象:

# 創(chuàng)建會(huì)話

session = requests.Session()

# 登錄

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

# 后續(xù)請(qǐng)求會(huì)自動(dòng)帶上登錄信息(比如Cookie)

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

5.實(shí)戰(zhàn)小練習(xí)

來(lái)做個(gè)小練習(xí)吧!調(diào)用免費(fèi)的天氣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}”

# 測(cè)試一下

print(get_weather('北京'))

本文章轉(zhuǎn)載微信公眾號(hào)@小七學(xué)Python

上一篇:

LLM之RAG實(shí)戰(zhàn)(二十)|Chunk RAG分塊策略的五個(gè)level

下一篇:

基于 RAG 的 LLM 應(yīng)用程序構(gòu)建(一):詳述數(shù)據(jù)源準(zhǔn)備工作
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)