python使用requests庫(kù)實(shí)現(xiàn)輕松發(fā)起HTTP請(qǐng)求
requests是Python中一個(gè)非常流行的用于發(fā)送HTTP請(qǐng)求的第三方庫(kù)。它提供了簡(jiǎn)潔的API,使得發(fā)送各種HTTP請(qǐng)求(如GET、POST、PUT、DELETE等)變得非常容易。
以下是一些基本的用法示例:
安裝
首先,你需要安裝requests庫(kù)。如果你還沒(méi)有安裝,可以使用pip進(jìn)行安裝:
> pip install requests
發(fā)送GET請(qǐng)求
import requests # mock data url: https://jsonplaceholder.typicode.com/ resp = requests.get("http://jsonplaceholder.typicode.com/posts/3") if resp.status_code == 200: # 獲取響應(yīng)內(nèi)容(JSON格式) data = resp.json() print(data) else: print(f"請(qǐng)求失敗,狀態(tài)碼:{resp.status_code}")
發(fā)送GET請(qǐng)求帶參數(shù)
import requests # mock data url: https://jsonplaceholder.typicode.com/ param = { "userId": 2 } resp = requests.get("http://jsonplaceholder.typicode.com/posts", params=param) if resp.status_code == 200: # 獲取響應(yīng)內(nèi)容(JSON格式) data = resp.json() print(data) else: print(f"請(qǐng)求失敗,狀態(tài)碼:{resp.status_code}")
發(fā)送POST請(qǐng)求
import requests data = { "userId": 11, "title": "requests post demo", "body": "requests post body" } resp = requests.post("http://jsonplaceholder.typicode.com/posts", data=data) if resp.status_code == 200 or resp.status_code == 201: # 獲取響應(yīng)內(nèi)容(JSON格式) data = resp.json() print(data) else: print(f"請(qǐng)求失敗,狀態(tài)碼:{resp.status_code}")
設(shè)置請(qǐng)求頭
import requests import json # mock data url: https://jsonplaceholder.typicode.com/ data = { "userId": 11, "title": "requests post demo", "body": "requests post body" } header = { 'Content-Type': 'application/json_demo' } resp = requests.post("http://jsonplaceholder.typicode.com/posts", data=json.dumps(data), headers=header) if resp.status_code == 200 or resp.status_code == 201: # 獲取響應(yīng)內(nèi)容(JSON格式) data = resp.json() print(data) else: print(f"請(qǐng)求失敗,狀態(tài)碼:{resp.status_code}")
設(shè)置Cookie和獲取Cookie
import requests # mock data url: https://jsonplaceholder.typicode.com/ cookies = { 'session_id': '12345', 'user_token': 'abcdef' } # 發(fā)送請(qǐng)求,并帶上 cookies resp = requests.get("http://jsonplaceholder.typicode.com/posts/1", cookies=cookies) # 從響應(yīng)中獲取 cookies cookies = resp.cookies.get_dict() print(cookies)
使用Session管理Cookies
當(dāng)你需要跨多個(gè)請(qǐng)求保持cookies時(shí),requests.Session對(duì)象特別有用。它允許你在會(huì)話(huà)期間自動(dòng)存儲(chǔ)和發(fā)送cookies。
import requests # 創(chuàng)建一個(gè)會(huì)話(huà)對(duì)象 session = requests.Session() # 發(fā)送第一個(gè)請(qǐng)求,服務(wù)器可能會(huì)設(shè)置一些 cookies response = session.get('https://example.com/login') # 發(fā)送第二個(gè)請(qǐng)求,這次請(qǐng)求會(huì)自動(dòng)帶上之前設(shè)置的 cookies response = session.get('https://example.com/profile') # 你可以檢查響應(yīng)中的 cookies print(session.cookies.get_dict())
處理響應(yīng)
response.status_code:HTTP狀態(tài)碼
response.text:響應(yīng)內(nèi)容的字符串形式
response.content:響應(yīng)內(nèi)容的二進(jìn)制形式
response.json():將響應(yīng)內(nèi)容解析為JSON對(duì)象(前提是響應(yīng)內(nèi)容是JSON格式)
異常處理
在發(fā)送請(qǐng)求時(shí),你可能會(huì)遇到各種異常,如網(wǎng)絡(luò)問(wèn)題、無(wú)效的URL等。
可以使用try-except塊來(lái)捕獲這些異常:
import requests try: response = requests.get('https://api.example.com/data') response.raise_for_status() # 如果響應(yīng)狀態(tài)碼不是 200,則引發(fā) HTTPError 異常 data = response.json() print(data) except requests.exceptions.HTTPError as errh: print(f"HTTP 錯(cuò)誤:{errh}") except requests.exceptions.ConnectionError as errc: print(f"連接錯(cuò)誤:{errc}") except requests.exceptions.Timeout as errt: print(f"請(qǐng)求超時(shí):{errt}") except requests.exceptions.RequestException as err: print(f"請(qǐng)求錯(cuò)誤:{err}")
打印完整的請(qǐng)求和響應(yīng)報(bào)文包含頭
import http import logging import requests # 配置logging logging.basicConfig(level=logging.DEBUG) logging.getLogger('requests').setLevel(logging.DEBUG) http.client.HTTPConnection.debuglevel = 1 # mock data url: https://jsonplaceholder.typicode.com/ resp = requests.get("http://jsonplaceholder.typicode.com/posts/3") if resp.status_code == 200: # 獲取響應(yīng)內(nèi)容(JSON格式) data = resp.json() print(data) else: print(f"請(qǐng)求失敗,狀態(tài)碼:{resp.status_code}")
到此這篇關(guān)于python使用requests庫(kù)實(shí)現(xiàn)輕松發(fā)起HTTP請(qǐng)求的文章就介紹到這了,更多相關(guān)python requests發(fā)起HTTP請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用python requests模塊發(fā)送http請(qǐng)求及接收響應(yīng)的方法
- Python中的HTTP請(qǐng)求庫(kù)Requests的具體使用
- Python使用requests模塊發(fā)送http請(qǐng)求的方法介紹
- python接口自動(dòng)化使用requests庫(kù)發(fā)送http請(qǐng)求
- 如何基于Python + requests實(shí)現(xiàn)發(fā)送HTTP請(qǐng)求
- python用requests實(shí)現(xiàn)http請(qǐng)求代碼實(shí)例
- python 使用 requests 模塊發(fā)送http請(qǐng)求 的方法
相關(guān)文章
使用Keras畫(huà)神經(jīng)網(wǎng)絡(luò)準(zhǔn)確性圖教程
這篇文章主要介紹了使用Keras畫(huà)神經(jīng)網(wǎng)絡(luò)準(zhǔn)確性圖教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06Python簡(jiǎn)單實(shí)現(xiàn)控制電腦的方法
這篇文章主要介紹了Python簡(jiǎn)單實(shí)現(xiàn)控制電腦的方法,涉及Python基于os及win32api等模塊調(diào)用系統(tǒng)命令操作電腦的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-01-01python代碼實(shí)現(xiàn)將列表中重復(fù)元素之間的內(nèi)容全部濾除
這篇文章主要介紹了python代碼實(shí)現(xiàn)將列表中重復(fù)元素之間的內(nèi)容全部濾除,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05在Python 不同級(jí)目錄之間模塊的調(diào)用方法
今天小編就為大家分享一篇在Python 不同級(jí)目錄之間模塊的調(diào)用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Python用selenium實(shí)現(xiàn)自動(dòng)登錄和下單的項(xiàng)目實(shí)戰(zhàn)
本文主要介紹了Python用selenium實(shí)現(xiàn)自動(dòng)登錄和下單的項(xiàng)目實(shí)戰(zhàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02