Requests 是使用 Apache2 Licensed 許可證的 HTTP 庫。用 Python 編寫,真正的爲人類着想。html
Python 標準庫中的 urllib2 模塊提供了你所須要的大多數 HTTP 功能,可是它的 API 太渣了。它是爲另外一個時代、另外一個互聯網所建立的。它須要巨量的工做,甚至包括各類方法覆蓋,來完成最簡單的任務。python
在Python的世界裏,事情不該該這麼麻煩。git
Requests 使用的是 urllib3,所以繼承了它的全部特性。Requests 支持 HTTP 鏈接保持和鏈接池,支持使用 cookie 保持會話,支持文件上傳,支持自動肯定響應內容的編碼,支持國際化的 URL 和 POST 數據自動編碼。現代、國際化、人性化。github
(以上轉自Requests官方文檔)web
二、Requests模塊安裝
點此下載apache
而後執行安裝json
1
|
$ python setup.py install
|
我的推薦使用pip安裝cookie
1
|
pip install requests
|
也可使用easy_install安裝app
1
|
easy_install requests
|
嘗試在IDE中import requests,若是沒有報錯,那麼安裝成功。webapp
三、Requests模塊簡單入門
#HTTP請求類型 #get類型 r = requests.get('https://github.com/timeline.json') #post類型 r = requests.post("http://m.ctrip.com/post") #put類型 r = requests.put("http://m.ctrip.com/put") #delete類型 r = requests.delete("http://m.ctrip.com/delete") #head類型 r = requests.head("http://m.ctrip.com/head") #options類型 r = requests.options("http://m.ctrip.com/get") #獲取響應內容 print r.content #以字節的方式去顯示,中文顯示爲字符 print r.text #以文本的方式去顯示 #URL傳遞參數 payload = {'keyword': '日本', 'salecityid': '2'} r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) print r.url #示例爲http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本 #獲取/修改網頁編碼 r = requests.get('https://github.com/timeline.json') print r.encoding r.encoding = 'utf-8' #json處理 r = requests.get('https://github.com/timeline.json') print r.json() #須要先import json #定製請求頭 url = 'http://m.ctrip.com' headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'} r = requests.post(url, headers=headers) print r.request.headers #複雜post請求 url = 'http://m.ctrip.com' payload = {'some': 'data'} r = requests.post(url, data=json.dumps(payload)) #若是傳遞的payload是string而不是dict,須要先調用dumps方法格式化一下 #post多部分編碼文件 url = 'http://m.ctrip.com' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files) #響應狀態碼 r = requests.get('http://m.ctrip.com') print r.status_code #響應頭 r = requests.get('http://m.ctrip.com') print r.headers print r.headers['Content-Type'] print r.headers.get('content-type') #訪問響應頭部份內容的兩種方式 #Cookies url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) r.cookies['example_cookie_name'] #讀取cookies url = 'http://m.ctrip.com/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies) #發送cookies #設置超時時間 r = requests.get('http://m.ctrip.com', timeout=0.001) #設置訪問代理 proxies = { "http": "http://10.10.10.10:8888", "https": "http://10.10.10.100:4444", } r = requests.get('http://m.ctrip.com', proxies=proxies)
四、Requests示例
json請求
1 #!/user/bin/env python 2 #coding=utf-8 3 import requests 4 import json 5 6 class url_request(): 7 def __init__(self): 8 """ init """ 9 10 if __name__=='__main__': 11 headers = {'Content-Type' : 'application/json'} 12 payload = {'CountryName':'中國', 13 'ProvinceName':'陝西省', 14 'L1CityName':'漢中', 15 'L2CityName':'城固', 16 'TownName':'', 17 'Longitude':'107.33393', 18 'Latitude':'33.157131', 19 'Language':'CN' 20 } 21 r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload) 22 #r.encoding = 'utf-8' 23 data=r.json() 24 if r.status_code!=200: 25 print "LBSLocateCity API Error " + str(r.status_code) 26 print data['CityEntities'][0]['CityID'] #打印返回json中的某個key的value 27 print data['ResponseStatus']['Ack'] 28 print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #樹形打印json,ensure_ascii必須設爲False不然中文會顯示爲unicode
xml請求
#!/user/bin/env python #coding=utf-8 import requests class url_request(): def __init__(self): """ init """ if __name__=='__main__': headers = {'Content-type': 'text/xml'} XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>' url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx' r = requests.post(url,headers=headers,data=XML) #r.encoding = 'utf-8' data = r.text print data
五、參考文檔
http://cn.python-requests.org/en/latest/
http://docs.python-requests.org/en/latest/user/quickstart.html