今天就跟大家聊聊有关怎么在Python中使用request模块下载图片,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
利用流传输下载图片
# -*- coding: utf-8 -*- import requests def 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"} #限定URL 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) 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()
运行结果(在当前目录下下载了一个demo.jpg文件):
看完上述内容,你们对怎么在Python中使用request模块下载图片有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。