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设计】。

相关文章

利用setuptools打包python程序的方法步骤

利用setuptools打包python程序的方法步骤

一、准备工程文件 1.创建工程leeoo 2.在工程根目录下创建setup.py文件 3.在工程根目录下创建同名package 二、编辑setup.py 1.编辑setup.py文...

python之yield表达式学习

python中有一个略微奇怪的表达式叫yield expression,本文就来探究一下这是个什么东西。一步一步来。 iterable 复制代码 代码如下: mylist = [1,2,...

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

本文讲述了Python使用pip安装报错:is not a supported wheel on this platform的解决方法。分享给大家供大家参考,具体如下: 可能的原因1:安...

python3 shelve模块的详解

python3 shelve模块的详解 一、简介   在python3中我们使用json或者pickle持久化数据,能dump多次,但只能load一次,因为先前的数据已经被后面dump的...

Python异常处理操作实例详解

本文实例讲述了Python异常处理操作。分享给大家供大家参考,具体如下: 常见异常 在python中不同的异常可以用不同的类型(python中统一了类与类型,类型即类)去标识,不同的类对...