#GET參數實例 requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) #或 url = 'http://www.baidu.com' payload = {'key1': 'value1', 'key2': 'value2'} headers = { "Accept":"text/html,application/xhtml+xml,application/xml;", "Accept-Encoding":"gzip", "Accept-Language":"zh-CN,zh;q=0.8", "Referer":"http://www.example.com/", "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } res1 = requests.get(url, params=payload, headers=headers, timeout=1) #POST參數實例 requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '測試post'}) files = {'file': open('touxiang.png', 'rb')} #用於發送文件的post屬性 files = {'file': ('xxxx,jpg',open('/home/lyb/sjzl.mpg','rb'))} #設置文件名 #或 url = 'http://www.baidu.com' data={"user":"user","password":"pass"} res2 = requests.post(url1, data=data, headers=headers ,files=files)
POST發送JSON數據:php
import json r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'})) print(r.json()) r = requests.get('http://ip.taobao.com/service/getIpInfo.php?ip=122.88.60.28') print (r.json()['data']['country']) 添加代理: proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://www.zhidaow.com", proxies=proxies) 一些操做requests返回值的方法: r.text #字符串方式的響應體,會自動根據響應頭部的字符編碼進行解碼 r.content #得到二進制響應內容 r.raw #得到原始響應內容,須要stream=True r.raw.read(50) type(r.text) #返回解碼成unicode的內容 r.url r.history #追蹤重定向 r.cookies r.cookies['example_cookie_name'] r.headers #以字典對象存儲服務器的響應頭,但該字典比較特殊,字典鍵不區分大小寫,若鍵不存在返回None r.headers['Content-Type'] r.headers.get('content-type') r.json #講返回內容編碼爲json r.encoding #返回內容編碼 r.status_code #返回http狀態碼 r.raise_for_status() #返回錯誤狀態碼 若編碼出錯,則r.text.encode('utf-8') #初始化一個session對象 s = requests.Session() #使用這個session對象來進行訪問 prepped1 = requests.Request('POST', url1, data=data, headers=headers ).prepare() s.send(prepped1) #或 r = s.post(url,data = user) 其餘的一些訪問方式: >>> r = requests.put("http://httpbin.org/put") >>> r = requests.delete("http://httpbin.org/delete") >>> r = requests.head("http://httpbin.org/get") >>> r = requests.options("http://httpbin.org/get") json: json數據傳到requests的body headers: HTTP Headers的字典傳到requests的header cookies: 能夠使用字典或者CookieJar object files: 字典{'name': file-tuple} 來實現multipart encoding upload, 2參數元組 ('filename', fileobj), 3參數元組 ('filename', fileobj, 'content_type')或者 4參數元組 ('filename', fileobj, 'content_type', custom_headers), 其中'content-type' 用於定於文件類型和custom_headers文件的headers auth: Auth元組定義用於Basic/Digest/Custom HTTP Auth timeout: 鏈接等待時長 allow_redirects: 布爾型, True表明POST/PUT/DELETE只有的重定向是容許的 proxies: 代理的地址 verify: 用於認證SSL證書 stream: False表明返回內容馬上下載 cert: String表明ssl client證書地址(.pem) Tuple表明('cert', 'key')鍵值對