這篇文章主要介紹了python中Requests庫有什么用,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
請求是唯一適用于Python的Non-GMO HTTP庫,可供人類安全使用。
Python爬蟲中繞過不開的就是requests庫。而Requests引用urllib在使用方面上引起開發者感到更加人性化,更加簡潔,更加舒適。以下摘自Requests官方文檔中的功能特性:
保持活力和連接池
國際化域名和URL
帶永久Cookie的會話
瀏覽器式的SSL認證
自動內容解碼
基本/摘要式的身份認證
優雅的鍵/值Cookie
自動解壓
Unicode響應體
HTTP(S)代理支持
文件分塊上傳
流下載
連接超時
分塊請求
支持.netrc
請求是python的三方庫,所以我們需要使用pip安裝
pip install requests
或者通過二進制安裝
git clone git://github.com/kennethreitz/requests.git cd <requests目錄> python setup.py install
常用的HTTP操作為GET和POST,其他不常用的操作可以參考官方文檔或串口調用相應方法即可。
import requests
# GET 請求
response = requests.get("https://getman.cn/echo")
print(response.text)
# GET 構造header,cookie,參數請求
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
}
cookie = {"user":"APython"}
params = {'my_name':'AL','name':'APython'}
response=requests.get("https://getman.cn/echo",headers=headers,cookies=cookie,params=params)
print(response.text)
#POST 請求
data = {'name': 'APython-post','age': 24,}
response = requests.post("https://getman.cn/echo", data=data)
print(response.text)
import requests
# 下載文件(一)小文件
url = 'https://raw.githubusercontent.com/psf/requests/master/ext/ss.png'
response = requests.get(url)
with open('demo.png', 'wb') as f:
f.write(response.content)
# 下載文件(二)大文件
file_url = "https://readthedocs.org/projects/python-guide/downloads/pdf/latest/"
response = requests.get(file_url)
with open("python.dpf", "wb") as pdf:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
pdf.write(chunk)
# POST 提交數據返回結果
url = 'https://api.github.com/some/endpoint'
data = {'some': 'APython'}
response = requests.post(url, data=data)
print(response.text)
#session 會話保持(會話對象可以跨請求保持某些參數)
session = requests.session()
session.get(url)
session.post(url,data)感謝你能夠認真閱讀完這篇文章,希望小編分享的“python中Requests庫有什么用”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。