原文的文件地址:http://blog.csdn.net/shanzhizi/article/details/50903748php
經過pip安裝html
或者,下載代碼後安裝:python
基本的語法:git
支持的 請求:github
requests.get(‘https://github.com/timeline.json’) #GET請求
requests.post(「http://httpbin.org/post」) #POST請求
requests.put(「http://httpbin.org/put」) #PUT請求
requests.delete(「http://httpbin.org/delete」) #DELETE請求
requests.head(「http://httpbin.org/get」) #HEAD請求
requests.options(「http://httpbin.org/get」) #OPTIONS請求ajax
GET請求:json
import requests requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) #GET參數實例 params={'wd': 'python'}可參數話 : --------------------------------------------------- payload={'wd': 'python'} import requests requests.get('http://www.dict.baidu.com/s', params=payload)
————————————————————----------api
POST請求:服務器
import requests requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '測試POST'}) #POST參數實例
-------------------------------------cookie
POST發送JSON數據:
import requests import json r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'})) print(r.json())
定製header:
import requests import json data = {'some': 'data'} headers = {'content-type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers) print(r.text)
r = requests.get('http://www.itwhy.org')
r.status_code #響應狀態碼
r.raw #返回原始響應體,也就是 urllib 的 response 對象,使用 r.raw.read() 讀取
r.content #字節方式的響應體,會自動爲你解碼 gzip 和 deflate 壓縮
r.text #字符串方式的響應體,會自動根據響應頭部的字符編碼進行解碼
r.headers #以字典對象存儲服務器響應頭,可是這個字典比較特殊,字典鍵不區分大小寫,若鍵不存在則返回None
#*特殊方法*#
r.json() #Requests中內置的JSON解碼器
r.raise_for_status() #失敗請求(非200響應)拋出異常
import requests url = 'http://127.0.0.1:5000/upload' files = {'file': open('/home/lyb/sjzl.mpg', 'rb')} #files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))} #顯式的設置文件名 r = requests.post(url, files=files) print(r.text)
更加方便的是,你能夠把字符串當着文件進行上傳:
import requests url = 'http://127.0.0.1:5000/upload' files = {'file': ('test.txt', b'Hello Requests.')} #必需顯式的設置文件名 r = requests.post(url, files=files) print(r.text)
基自己份認證(HTTP Basic Auth):
import requests from requests.auth import HTTPBasicAuth r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd')) # r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd')) # 簡寫 print(r.json())
另外一種很是流行的HTTP身份認證形式是摘要式身份認證,Requests對它的支持也是開箱便可用的:
requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))
若是某個響應中包含一些Cookie,你能夠快速訪問它們:
import requests r = requests.get('http://www.google.com.hk/') print(r.cookies['NID']) print(tuple(r.cookies))
要想發送你的cookies到服務器,能夠使用 cookies 參數:
import requests url = 'http://httpbin.org/cookies' cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'} # 在Cookie Version 0中規定空格、方括號、圓括號、等於號、逗號、雙引號、斜槓、問號、@,冒號,分號等特殊符號都不能做爲Cookie的內容。 r = requests.get(url, cookies=cookies) print(r.json())
會話對象讓你可以跨請求保持某些參數,最方便的是在同一個Session實例發出的全部請求之間保持cookies,且這些都是自動處理的,甚是方便。
下面就來一個真正的實例,以下是快盤簽到腳本:
import requests headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept-Language': 'en-us;q=0.5,en;q=0.3', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} s = requests.Session() s.headers.update(headers) # s.auth = ('superuser', '123') s.get('https://www.kuaipan.cn/account_login.htm') _URL = 'http://www.kuaipan.cn/index.php' s.post(_URL, params={'ac':'account', 'op':'login'}, data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'}) r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'}) print(r.json()) s.get(_URL, params={'ac':'common', 'op':'usersign'})
timeout 僅對鏈接過程有效,與響應體的下載無關。
>>> requests.get('http://github.com', timeout=0.001) Traceback (most recent call last): File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
全部Requests顯式拋出的異常都繼承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。