python保存网页图片到本地的方法

yipeiwu_com6年前Python基础

本文实例为大家分享了python保存网页图片到本地的具体代码,供大家参考,具体内容如下

#!/usr/bin/env Python
#coding=utf-8 
 
import time
import datetime
import sys
import random
import math
import uuid
import cookielib
import urllib2
import os
 
class GetImage():
 reload(sys)
 sys.setdefaultencoding('utf8') 
 '''
 抓取网页文件内容,保存到内存
 
 @url 欲抓取文件 ,path+filename
 '''
 def get_file(self,url):
 try:
 cj=cookielib.LWPCookieJar()
 opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
 urllib2.install_opener(opener)
  
 req=urllib2.Request(url)
 operate=opener.open(req)
 data=operate.read()
 return data
 except BaseException, e:
 print e
 return None
 
 '''
 保存文件到本地
 
 @path 本地路径
 @file_name 文件名
 @data 文件内容
 '''
 def save_file(self,file_name, data):
 if data == None:
 return
  
 file=open(file_name, "wb")
 file.write(data)
 file.flush()
 file.close()
 def save_png_file(self,filename,url):
 self.save_file(filename,self.get_file(url))
  
if __name__=="__main__":
 
 h1 = GetImage()
 
 #h1.save_file('c:/log/124.png',h1.get_file('/zb_users/upload/202003/e0ue0egvman.png'))
 #url = '/zb_users/upload/202003/e0ue0egvman.png'
 #file_path ='c:/log/125.png'
 #h1.save_png_file(file_path,url) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python之虚拟环境virtualenv,pipreqs生成项目依赖第三方包的方法

Python之虚拟环境virtualenv,pipreqs生成项目依赖第三方包的方法

virtualenv简介 含义: virtual:虚拟,env:environment环境的简写,所以virtualenv就是虚拟环境,顾名思义,就是虚拟出来的一个新环境,比如我们使用的...

Python基于matplotlib实现绘制三维图形功能示例

Python基于matplotlib实现绘制三维图形功能示例

本文实例讲述了Python基于matplotlib实现绘制三维图形功能。分享给大家供大家参考,具体如下: 代码一: # coding=utf-8 import numpy as np...

Python pandas RFM模型应用实例详解

Python pandas RFM模型应用实例详解

本文实例讲述了Python pandas RFM模型应用。分享给大家供大家参考,具体如下: 什么是RFM模型 根据美国数据库营销研究所Arthur Hughes的研究,客户数据库中有3个...

利用Python的turtle库绘制玫瑰教程

利用Python的turtle库绘制玫瑰教程

turtle的文档:https://docs.python.org/3/library/turtle.html 用Python的turtle库绘图是很简单的,闲来无事就画了一个玫瑰花,下...

python实现二分查找算法

二分查找算法:简单的说,就是将一个数组先排序好,比如按照从小到大的顺序排列好,当给定一个数据,比如target,查找target在数组中的位置时,可以先找到数组中间的数array[mid...