python requests库

2017-01-06  本文已影响51人  赐我理由在披甲上阵

Python哲学:

beautiful is better than ugly!

simple is better than complex!

complex is better than complicate

http://cn.python-requests.org/zh_CN/latest/user/advanced.html#event-hooks

一些高级用法:

s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print r.text
# '{"cookies": {"sessioncookie": "123456789"}}'

# 登陆
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
 
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
# 参数会被合并

# 如果你想在一个session中删除一个参数,那么你只需要设置它为none,他便自动被删去。
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

# 响应的头部信息
print  r.headers

{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}

# 请求的头部信息
print r.request.headers

{'Accept-Encoding': 'identity, deflate, compress, gzip',
'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}


print r.text   #返回body,以文本的形式
....

print r.content # 非文本类型,以二进制形式
.....

print r.json # json格式
....

print r.encoding
'UTF-8'



 requests.get('https://kennethreitz.com', verify=True)
 # 指定 证书
 requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

with open('massive-body') as f:
    requests.post('http://some.url/streamed', data=f)
'''
还请支持分块传输编码传出和传入的请求。
要发送一个数据块编码的请求,
只是提供一个生成器(或任何没有长度的迭代器)为您的BODY:
'''
 
def gen():
    yield 'hi'
    yield 'there'
 
requests.post('http://some.url/chunked', data=gen())
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python',
hooks=dict(response=print_url))

def print_url(r, *args, **kwargs): 
    print(r.url)

你可以通过传递一个 { hook_name: callback_function} 字典给 hooks请求参数,为每个请求分配一个钩子函数。
callback_function会接受一个数据块作为它的第一个参数。print_url 函数就会以response作为第一个参数。
若回调函数返回一个值,默认以该值替换传进来的数据(response)。若函数未返回任何东西, 也没有什么其他的影响。

上一篇 下一篇

猜你喜欢

热点阅读