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

相关文章

pygame游戏之旅 添加游戏界面按键图形

pygame游戏之旅 添加游戏界面按键图形

本文为大家分享了pygame游戏之旅的第10篇,供大家参考,具体内容如下 通过获取鼠标的位置然后进行高亮显示: mouse =pygame.mouse.get_pos() if 1...

python gdal安装与简单使用

python gdal安装与简单使用

gdal安装 方式一:在网址 https://www.lfd.uci.edu/~gohlke/pythonlibs/ 下载对应python版本的whl文件,在命令行中pip instal...

pymysql 开启调试模式的实现

pymysql 开启调试模式的实现

今天在排查线上一个奇怪的数据库连接问题,所以打开了 pymysql 的源码在阅读,发现 pymysql 在其 connections 模块里内置了一个 DEBUG 变量用于控制是否开启调...

pandas基于时间序列的固定时间间隔求均值的方法

pandas基于时间序列的固定时间间隔求均值的方法

如果index是时间序列就不用转datetime;但是如果时间序列是表中的某一列,可以把这一列设为index 例如: 代码: DF=df2.set_index(df1['time_...

python查找第k小元素代码分享

复制代码 代码如下:# -*- coding: utf-8 -*- from random import randintfrom math import ceil, floor def...