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入门教程4. 元组基本操作 原创

前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作 >>> dir(tuple) #查看元组的属性和方法 ['__add__',...

Python中特殊函数集锦

Python中特殊函数集锦

以下内容主要针过滤函数filter , 映射和归并函数map/reduce , 装饰器@ 以及 匿名函数lamda,具体内容如下: 1. 过滤函数filte...

Python使用sort和class实现的多级排序功能示例

本文实例讲述了Python使用sort和class实现的多级排序功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- import random cl...

Python获取运行目录与当前脚本目录的方法

本文实例讲述了Python获取运行目录与当前脚本目录的方法。分享给大家供大家参考。具体实现方法如下: import os import sys #运行目录 CurrentPath =...

基于python 处理中文路径的终极解决方法

1 、据说python3就没有这个问题了 2 、u'字符串' 代表是unicode格式的数据,路径最好写成这个格式,别直接跟字符串'字符串'这类数据相加,相加之后type就是str,这样...