response对象:
利用response把流存储成图片或者文件
一个下载图片的实例
import requests def download_pic(): #headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36'} url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502704492717&di=8fa0fd715e093c769cd55ec3043d7c2d&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01578458056c9ea84a0d304f7fe50f.jpg" response = requests.get(url,stream=True) from contextlib import closing with closing(requests.get(url,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.headers) #print(response.content) download_pic()
事件钩子:事件驱动型开发,基于回调。
import requests def get_key_info(response,*args,**kwargs): print(response.headers['Content-Type']) def main(): requests.get('https://www.baidu.com',hooks=dict(response=get_key_info)) main()