获取服务器返回内容:
- Response Content
import requests
r = requests.get('https://api.github.com/events')
print(r.text[0:20])
[{"id":"7843224643",
调整返回内容的编码方式
import requests
r = requests.get('https://api.github.com/events')
print(r.encoding)
r.encoding = 'ISO-8859-1'
print(r.text[0:20])
- Binary Response Content
import requests
r = requests.get('https://www.baidu.com/img/bd_logo1.png', {'where':'super'})
print(r.status_code)
print(r.content)
上面的bytes其实是一个图片,用PIL库来bytes,然后显示图片
import requests
r = requests.get('https://www.baidu.com/img/bd_logo1.png', {'where':'super'})
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
i.show()
- Json Response Content
import requests
r = requests.get('https://api.github.com/events')
print(r.json())
Requests用内建的json()方法处理JSON 数据,如果没有内容,返回204;
非JSON内容,则抛出ValueError:No Json object could be decoded的异常。
用r.raise_for_status()或r.status_code来检测request是否成功。
- Raw response content
加上"stream=True".
>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
如果要将raw保存到文本文件中,则不用r.raw,而用r.iter_content,iter_content能自动解码gzip和deflate transfer-encoding。
import requests
import os
r = requests.get('https://api.github.com/events', stream = True)
base_dir = os.path.dirname(__file__)
file_path = base_dir + '/file_raw.txt'
print(file_path)
with open(file_path, 'wb+') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
- Customer Headers:
如果需要给request加上http headers,传入一个headers参数,参数是字典形式的
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
- 复杂的POST Requests
传入字典参数,对于post,用'data='接受字典参数
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
C:\Python35\python.exe D:/pyjd/djanRestPro/api/tests.py
{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"json":null,"origin":"111.175.192.105","url":"http://httpbin.org/post"}
传入元组,也会被转换为字典
import requests
payload = (('key1','value1'),('key1','value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
C:\Python35\python.exe D:/pyjd/djanRestPro/api/tests.py
{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"json":null,"origin":"111.175.192.105","url":"http://httpbin.org/post"}
传入Json参数,注意这里要用'json='接受参数
import requests
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)
- 传入文件
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
显示的传入文件,content_type和headers
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}