Requests库的使用

# -*- coding: utf-8

from requests import Request, Session
import requests
from contextlib import closing


r = requests.get('https://api.github.com/user/emails', auth=('[email protected]', 'liumeng123'))
#思考,如何从json中获取到想要的数据 
print(r.json())
s = requests.Session()
r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)

#~ r = s.get('http://httpbin.org/cookies')
#~ print(r.text)


url = 'https://api.github.com/user/emails'
s = Session()
headers = {'User-Agent':'fake1.3.4'}
req = Request('GET',url,auth=('[email protected]', 'liumeng123'),headers=headers)
prepped = req.prepare()
print(prepped.body)  #None
print(prepped.headers) #{'Authorization': 'Basic MTA3NDY4NTU5MEBxcS5jb206bGl1bWVuZzEyMw==', 'User-Agent': 'fake1.3.4'}

resp = s.send(prepped,timeout=5)
print(resp.status_code)
print(resp.request.headers)
print(resp.text)

#~ 下载图片
url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508318982440&di=473927e948dc884d4d69a3c4a055c267&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fbaike%2Fpic%2Fitem%2F0b55b319ebc4b745fab6b97cc6fc1e178a8215bd.jpg'
#~ #伪造头信息
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
response = requests.get(url,headers=headers,stream=True)
with closing(requests.get(url,headers=headers,stream=True)) as response:
    with open('demo.jpg','wb') as fd: #不存在的文件被自动创建 
        for chunk in response.iter_content(128):
            fd.write(chunk)
print(response.status_code)
print(response.reason)
print(response.headers)

def get_key_info(response,*args,**kwargs):
    #回调函数
    print(response.headers['Content-Type'])

#主函数
requests.get('https://www.baidu.com',hooks=dict(response=get_key_info))


你可能感兴趣的:(Requests库的使用)