本文实例为大家分享了python保存网页图片到本地的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
#!/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('http://1.1.1.1/doc/images/public/ICON/norecord.png'))
#url = 'http://1.1.1.1/doc/images/public/ICON/norecord.png'
#file_path ='c:/log/125.png'
#h1.save_png_file(file_path,url)
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/huhuliuxia/article/details/42099475