前言
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理,
以下文章來源于APython ,作者鋁
1.Requests簡介
請求是唯一適用于Python的Non-GMO HTTP庫,可供人類安全使用,
Python爬蟲中繞過不開的就是requests庫,而Requests參考ur?llib在使用方面上引起開發者感到更加人性化,更加簡潔,更加舒適,以下摘自Requests官方檔案中的功能特性:
- 保持活力和連接池
- 國際化域名和URL
- 帶永久Cookie的會話
- 瀏覽器式的SSL認證
- 自動內容解碼
- 基本/摘要式的身份認證
- 優雅的鍵/值Cookie
- 自動解壓
- Unicode回應體
- HTTP(S)代理支持
- 檔案分塊上傳
- 流下載
- 連接超時
- 分塊請求
- 支持.netrc
2.要求安裝
請求是python的三方庫,所以我們需要使用pip安裝
pip install requests
或者通過二進制安裝
git clone git://github.com/kennethreitz/requests.git cd <requests目錄> python setup.py install
3.要求用例
常用的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 = https://www.cnblogs.com/hhh188764/p/{'name': 'APython-post','age': 24,} response = requests.post("https://getman.cn/echo", data=https://www.cnblogs.com/hhh188764/p/data) print(response.text)
回傳值response是一個Response物件,它的常用屬性和方法如下:
4.請求更多示例
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=https://www.cnblogs.com/hhh188764/p/data) print(response.text) #session 會話保持(會話物件可以跨請求保持某些引數) session = requests.session() session.get(url) session.post(url,data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/224926.html
標籤:Python
下一篇:Python學習筆記6:輸入輸出
