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 文件处理注意事项总结

Python 文件处理注意事项总结 文件处理在编程中是常见的操作,文件的打开,关闭,重命名,删除,追加,复制,随机读写非常容易理解和使用。需要注意的是文件的安全关闭,采用with语句轻松...

Python之PyUnit单元测试实例

本文实例讲述了Python之PyUnit单元测试,与erlang eunit单元测试很像,分享给大家供大家参考。具体方法如下: 1.widget.py文件如下: 复制代码 代码如下:#!...

一看就懂得Python的math模块

math模块 # 数学相关模块 import math r = math.floor(3.2) # 向下取整 print(r) r = math.ceil(4.5) # 向上取整...

python使用pyhook监控键盘并实现切换歌曲的功能

自己在玩dota的时候有时候喜欢边玩游戏边听音乐,但是切换下一曲的时候必须得切出游戏,而切换音乐的热键ctrl+alt+方向键在游戏的时候没有用,好事蛋疼,今天试试使用python来实现...

python基础之入门必看操作

python基础之入门必看操作

这里提供在使用python进行开发中常使用到的方法技巧,如有不对欢迎批评指正。 要点:开发中类、变量特性查询,类型就是类,断言的使用,深浅复制判断等 python脚本文件是使用UTF-8...