本文主要是介绍python request 下载 图片 demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
利用流传输下载图片
# -*- coding: utf-8 -*-
import requestsdef download_image():"""demo:下载图片:return:"""headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"}url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491366667515&di=8dad3d86740af2c49d3d0461cfd81f63&imgtype=0&src=http%3A%2F%2Fhdn.xnimg.cn%2Fphotos%2Fhdn521%2F20120528%2F1615%2Fh_main_LBxi_2917000000451375.jpg"response = requests.get(url, headers=headers, stream=True)#print str(response.text).decode('ascii').encode('gbk')with open('demo.jpg', 'wb') as fd:for chunk in response.iter_content(128):fd.write(chunk)download_image()def download_image_improved():"""demo: 下载图片"""#伪造headers信息headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"}#限定URLurl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491366667515&di=8dad3d86740af2c49d3d0461cfd81f63&imgtype=0&src=http%3A%2F%2Fhdn.xnimg.cn%2Fphotos%2Fhdn521%2F20120528%2F1615%2Fh_main_LBxi_2917000000451375.jpg"response = requests.get(url, headers=headers, stream=True)from contextlib import closing#用完流自动关掉with closing(requests.get(url, headers=headers, stream=True)) as response:#打开文件with open('demo1.jpg', 'wb') as fd:#每128写入一次for chunk in response.iter_content(128):fd.write(chunk)download_image_improved()
这篇关于python request 下载 图片 demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!