python接口自动化测试-requests下载图片

如:

import requestsdef down_image():
    '''
    demo:下载图片
    '''
    headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}
    url = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2160522519,3825740687&fm=26&gp=0.jpg'
    response = requests.get(url, headers=headers, stream=True)
    print(response.status_code)
    with open('demo.jpg','wb') as fd:
        for chunk in response.iter_content(128):
            fd.write(chunk)
def down_image_improved():
    '''
    demo:下载图片
    '''
    #伪造headers信息
    headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}
    #限定url
    url = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2160522519,3825740687&fm=26&gp=0.jpg'
    response = requests.get(url, headers=headers, stream=True)
    from contextlib import closing
    print(response.status_code)
    #打开传输流后最后会关上
    with closing(requests.get(url, headers=headers, stream=True)) as response:
        #打开文件
        with open('demo.jpg', 'wb') as fd:
            #每128写入一次
            for chunk in response.iter_content(128):
                fd.write(chunk)
down_image_improved()

posted @ 2020-03-21 22:27  忆梦,惊梦  阅读(402)  评论(0编辑  收藏  举报