1.Requests模塊安裝:
推薦使用pip安裝:
pip install requests
2.Requests模塊基礎(chǔ)
#HTTP請(qǐng)求類(lèi)型
#get類(lèi)型
r = requests.get('https://github.com/timeline.json')
#post類(lèi)型
r = requests.post("http://m.ctrip.com/post")
#put類(lèi)型
r = requests.put("http://m.ctrip.com/put")
#delete類(lèi)型
r = requests.delete("http://m.ctrip.com/delete")
#head類(lèi)型
r = requests.head("http://m.ctrip.com/head")
#options類(lèi)型
r = requests.options("http://m.ctrip.com/get")
#獲取響應(yīng)內(nèi)容
print r.content #以字節(jié)的方式去顯示秩命,中文顯示為字符
print r.text #以文本的方式去顯示
#URL傳遞參數(shù)
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=日本
#獲取/修改網(wǎng)頁(yè)編碼
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
#定制請(qǐng)求頭
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
#復(fù)雜post請(qǐng)求
url = 'http://m.ctrip.com'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #如果傳遞的payload是string而不是dict掺涛,需要先調(diào)用dumps方法格式化一下
#post多部分編碼文件
url = 'http://m.ctrip.com'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
#響應(yīng)狀態(tài)碼
r = requests.get('http://m.ctrip.com')
print r.status_code
#響應(yīng)頭
r = requests.get('http://m.ctrip.com')
print r.headers
print r.headers['Content-Type']
print r.headers.get('content-type') #訪問(wèn)響應(yīng)頭部分內(nèi)容的兩種方式
#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) #發(fā)送cookies
#設(shè)置超時(shí)時(shí)間
r = requests.get('http://m.ctrip.com', timeout=0.001)
#設(shè)置訪問(wèn)代理
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://m.ctrip.com', proxies=proxies)
3.Requests接口實(shí)踐
#!/user/bin/env python
#coding=utf-8
import requests
import json
class url_request():
def__init__(self):
""" init """
if__name__=='__main__':
headers = {'Authorization':'PffLnU05NYUGHsxvfI',
'Content-Type':'application/json',
'Accept':'application/json'}
payload = {'user_id':'uid:U-XXXXXXXXXXXXXXX',
'idp_id':'XXXX',
'email':'xxx'
}
r = requests.post("http://127.x.x.x:xxxx/xxx/v1/userinfo",headers=headers,data=payload)
#r.encoding = 'utf-8'
data=r.json()
ifr.status_code!=200:
print"userinfo API Error "+str(r.status_code)
printjson.dumps(data,indent=4,sort_keys=True,ensure_ascii=False)#樹(shù)形打印json夺饲,ensure_ascii必須設(shè)為False否則中文會(huì)顯示為unicode