首页 > 编程语言 > 详细

如何用python下载一张图片

时间:2017-12-09 15:24:54      阅读:160      评论:0      收藏:0      [点我收藏+]

如何用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)

如何用python下载一张图片

原文:http://www.cnblogs.com/baishuixiangbalao/p/8011459.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!