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

首頁 > 編程 > Python > 正文

Python Requests庫基本用法示例

2020-02-15 22:47:09
字體:
來源:轉載
供稿:網友

本文實例講述了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解碼

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 铜山县| 上高县| 阿合奇县| 柘城县| 秀山| 高邑县| 宁陕县| 武川县| 南澳县| 承德市| 称多县| 尉氏县| 都兰县| 闻喜县| 湟中县| 额尔古纳市| 东莞市| 沅江市| 鹿泉市| 辽宁省| 枣阳市| 贵溪市| 扎赉特旗| 桐乡市| 盐津县| 乐山市| 晴隆县| 宣汉县| 石林| 永吉县| 普兰店市| 南充市| 内丘县| 道孚县| 武山县| 达拉特旗| 屯昌县| 闵行区| 上高县| 乌兰察布市| 巴青县|