如何用python下载一张图片

如何用python下载一张图片


  • 这里要用到的主要工具是requests这个工具,需要先安装这个库才能使用,该库衍生自urllib这个库,但是要比它更好用。多数人在做爬虫的时候选择它,是个不错的选择。

  • 例如下载http://p1.pstatp.com/large/4af100050861e28b06ca这张图片,我们可以参考下面这个例子


import requests
import os
import time

image_response=requests.get('http://p1.pstatp.com/large/4af100050861e28b06ca')
//利用time工具获取一个时间,作为文件名,避免重复。
t=str(time.time()).replace('.','')
//主要用来获取当前路径
file_path='{0}\\{1}.{2}'.format(os.getcwd(),t,'jpg')
//content方法以二进制的方法读取网页内容,text则是以文本方式
image=image_response.content
//注意图片使用二进制‘wb’,使用with方法进行文件读写,是一个比较好的选择
with open(file_path,'wb') as image_file:
    image_file.write(image)
posted @ 2017-12-09 15:04  白水乡巴佬  阅读(322)  评论(0编辑  收藏  举报