亲宝软件园·资讯

展开

Requests功能整理

jimywu 人气:0
import requests

# GET r = requests.get('https://api.github.com/events')

# POST
r = requests.post('https://httpbin.org/post', data = {'key':'value'})

# PUT DELETE HEAD OPTIONS
r = requests.put('https://httpbin.org/put', data = {'key':'value'})
r = requests.delete('https://httpbin.orghttps://img.qb5200.com/download-x/delete')
r = requests.head('https://httpbin.org/get')
r = requests.options('https://httpbin.org/get')

r 是请求响应(response),我们可以从r对象上获取任何我们想要的信息

 

传递URL参数方法

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('https://httpbin.org/get', params=payload)

使用 r.url  查询编码结果,注意字典payload的key对应value 为NONE时,将不会加入查询参数中

>>> print(r.url)
https://httpbin.org/get?key2=value2&key1=value1

 

响应response context

>>> import requests

>>> r = requests.get('https://api.github.com/events')
# 文本 >>> r.text u'[{"repository":{"open_issues":0,"url":"https://github.com/...
>>> r.encoding
'utf-8'

# 字节
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

# JSON
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
# 返回json并不代表正确返回response
# 检查返回结果
>>> r.status_code

# raw, 需要设置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'
 

返回图像数据的处理

>>> from PIL import Image
>>> from io import BytesIO

>>> i = Image.open(BytesIO(r.content))

stream 类型的保存,response.iter_content 会自动解码gzip类传输编码

with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size=128):
        fd.write(chunk)

 

自定义请求Headers

注意headers 优先级较低,会被很多参数覆盖

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

 

响应Headers

返回字典格式,不分大小写

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

 

响应Cookies

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

发送带cookies请求

>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

 

加载全部内容

相关教程
猜你喜欢
用户评论