python 使用 requests 做 http 请求
生活随笔
收集整理的這篇文章主要介紹了
python 使用 requests 做 http 请求
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. get
import requests# 最簡單的get請求 r = requests.get(url) print(r.status_code) print(r.json())# url 中?key=value&key=value r = requests.get(url, params=params)# form 表單 params = {"username":"name", "password":"passw0rd"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = requests.get(url, params=params, headers=headers)# 下載 r = requests.get(url) r.raise_for_status() with open(target, 'wb') as f:for ch in r.iter_content(10000):result_file_size += f.write(ch)2. post請求
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' data = {'name':'train', 'device':'CN0989'} r = requests.post(url, json=data)#上傳 files = {"file": (os.path.basename(filepath), open(filepath, "rb"), "application/zip") } print('POST %s'%url) with open(filepath, 'rb') as f:r = requests.post(url, files=files) r = requests.post(url, json=json_dict, headers=headers)# 保持response流,保證接收完整 with requests.get('https://httpbin.org/get', stream=True) as r:# Do things with the response here.# 上傳文件 with open('massive-body', 'rb') as f:requests.post('http://some.url/streamed', data=f)# 上傳文件 2 指定文件格式 files = {'file': (filename, open(filename, 'rb), 'application/zip')} r = requests.post(url, files=files) print(r.status_code) print(r.json())# 上傳多個文件 url = 'https://httpbin.org/post' multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))] r = requests.post(url, files=multiple_files) r.text3. 登錄
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' _session = requests.Session()# login url = '%s/login'%_basic_url params = {"username":"admin", "password":"admin"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = _session.post(url, params=params, headers=headers)#做其他請求 r = _session.get(url)_session.close()4. 使用basic登錄
from requests.auth import HTTPBasicAuthr = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) r.encoding = 'utf-8' print r.status_code print r.text print r.json()總結(jié)
以上是生活随笔為你收集整理的python 使用 requests 做 http 请求的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬虫代码优化:使用生成器重构
- 下一篇: python if条件判断和while循