国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python Requests庫基本用法示例

2020-01-04 14:41:04
字體:
來源:轉載
供稿:網友

本文實例講述了Python Requests庫基本用法。分享給大家供大家參考,具體如下:

requests是python的一個http client庫,提供了一套簡捷的API供開發者使用。下面簡單介紹一下其安裝和使用。這里是官方文檔。

0 安裝

pip install requests

1 發送請求

r=requests.get('https://www.baidu.com')print r.status_code,r.textr=requests.post('http://httpbin.org/post')r=requests.put('http://httpbin.org/put')r=requests.delete('http://httpbin.org/delete')r=requests.head('http://httpbin.org/head')r=requests.options('http://httpbin.org/')

2 發送get參數

param={'key1':value1,'key2':value2}r=requests.get('http://www.baidu.com/',params=param)

3 發送post參數

param={'key1':value1,'key2':value2}r=requests.post('http://www.baidu.com/',params=param) #表單格式r=requests.post('http://www.baidu.com/',json=param) #json格式數據file= {'file':open('1.txt','rb')}r=reuqest.post('http://httpbin.org/post',files=file)

4 文件下載

with open('1.pic','wb') as pic:  for chunk in response.iter_content(size):    pic.write(chunk)

5 攜帶header

header={'key1':value1,'key2':value2}r=requests.get('http://www.baidu.com/',headers=header)

6 攜帶cookie

cookie={'key1':value1,'key2':value2}r=requests.get('http://www.baidu.com/',cookies=cookie)

7 重定向

默認requests是允許重定向的,并將重定向的歷史保存在response.history數組中
如果不需要重定向,可以通過開關來關閉

r=requests.get('http://www.baidu.com/',allow_redirects=False)

8 使用代理

使用socks代理需要安裝三方擴展包

pip install requests[socks]
proxy={  'http':'http://127.0.0.1:8000',  'https':'https://127.0.0.1:8080'  'http':'socks5://user:pass@127.0.0.1:8132'}r=requests.get('https://www.github.com/',proxies=proxy)

9 設置連接超時

r=requests.get('http://www.baidu.com/',timeout=2.5)

10 ssl證書

證書驗證

requests.get('https://kennethreitz.com', verify=True)requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

如果指定本地證書及密鑰,則密鑰需要是解密的。

11 requests對象

r.url
r.text
r.headers

12 Response對象

response.request 對應的請求對象
response.raw socket上直接獲得的數據
response.text 根據響應頭進行解碼的文本數據
response.content 不解碼,返回二進制數據
response.json() 對返回數據進行json解碼
response.headers 詞典形式存儲返回的headers
response.cookies 詞典形式存儲返回的cookies

希望本文所述對大家Python程序設計有所幫助。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 仙桃市| 永泰县| 磐石市| 象山县| 云南省| 雷波县| 攀枝花市| 运城市| 康马县| 沛县| 杭锦旗| 辉县市| 沭阳县| 东乡县| 稻城县| 招远市| 宣武区| 尉犁县| 万源市| 舒城县| 濮阳市| 隆化县| 临夏市| 凌云县| 山西省| 铜梁县| 朝阳市| 中阳县| 卢氏县| 郓城县| 什邡市| 华亭县| 柞水县| 于田县| 长宁县| 高碑店市| 平阴县| 敦煌市| 新河县| 新巴尔虎左旗| 鄂伦春自治旗|