zoukankan      html  css  js  c++  java
  • Python抓取网页中的图片到本地

    今天在网上找了个从网页中通过图片URL,抓取图片并保存到本地的例子:

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 #   Author:    xixihuang
     5 #   Date  :     2016/08/28 10:12 AM
     6 #   Desc:       抓取网页,获取图片URL,抓取图片内容并保存到本地。
     7 
     8 import os
     9 import uuid
    10 import urllib2
    11 import cookielib
    12 '''获取文件后缀名'''
    13 def get_file_extension(file):
    14   return os.path.splitext(file)[1]
    15 '''創建文件目录,并返回该目录'''
    16 def mkdir(path):
    17   # 去除左右两边的空格
    18   path=path.strip()
    19   # 去除尾部 符号
    20   path=path.rstrip("\")
    21   if not os.path.exists(path):
    22     os.makedirs(path)
    23   return path
    24 '''自动生成一个唯一的字符串,固定长度为36'''
    25 def unique_str():
    26   return str(uuid.uuid1())
    27 '''
    28 抓取网页文件内容,保存到内存
    29 @url 欲抓取文件 ,path+filename
    30 '''
    31 def get_file(url):
    32   try:
    33     cj=cookielib.LWPCookieJar()
    34     opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    35     urllib2.install_opener(opener)
    36     req=urllib2.Request(url)
    37     operate=opener.open(req)
    38     data=operate.read()
    39     return data
    40   except BaseException, e:
    41     print e
    42     return None
    43 '''
    44 保存文件到本地
    45 @path 本地路径
    46 @file_name 文件名
    47 @data 文件内容
    48 '''
    49 def save_file(path, file_name, data):
    50   if data == None:
    51     return
    52   mkdir(path)
    53   if(not path.endswith("/")):
    54     path=path+"/"
    55   file=open(path+file_name, "wb")
    56   file.write(data)
    57   file.flush()
    58   file.close()
    59 #获取文件后缀名
    60 print get_file_extension("123.jpg");
    61 #創建文件目录,并返回该目录
    62 #print mkdir("d:/ljq")
    63 #自动生成一个唯一的字符串,固定长度为36
    64 print unique_str()
    65 url="http://qlogo1.store.qq.com/qzone/416501600/416501600/100?0";
    66 save_file("D:/test/", "123.jpg", get_file(url))
  • 相关阅读:
    Java泛型-类型擦除
    static加载问题
    当使用System,out.println()打印一个对象是自动调用toString方法
    python——变量作用域及嵌套作用域
    Python 构造函数、 Python 析构函数、Python 垃圾回收机制
    python——type()创建类
    HTML4,HTML5,XHTML 之间有什么区别?
    斐波那契数列算法分析
    python——iterator迭代器|iterator详解——20140918|
    django model filter 条件过滤,及多表连接查询、反向查询,某字段的distinct
  • 原文地址:https://www.cnblogs.com/xixihuang/p/5810501.html
Copyright © 2011-2022 走看看