zoukankan      html  css  js  c++  java
  • 怎样使用python爬虫进行网页图片抓取

    本文通过python 来实现这样一个简单的爬虫功能,把我们想要的图片爬取到本地。
    下面就看看如何使用python来实现这样一个功能。

    # -*- coding: utf-8 -*-
    import urllib
    import re
    import time
    import os
     
    #显示下载进度
    def schedule(a,b,c):
        '''''
        a:已经下载的数据块
        b:数据块的大小
        c:远程文件的大小
       '''
        per = 100.0 * a * b / c
        if per > 100 :
           per = 100
       print '%.2f%%' % per
     
    def getHtml(url):
        page = urllib.urlopen(url)
        html = page.read()
        return html
     
    def downloadImg(html):
        reg = r'src="(.+?.jpg)" pic_ext'
        imgre = re.compile(reg)
       imglist = re.findall(imgre, html)
        #定义文件夹的名字
        t = time.localtime(time.time())
        foldername = str(t.__getattribute__("tm_year"))+"-"+str(t.__getattribute__("tm_mon"))+"-"+str(t.__getattribute__("tm_mday"))
        picpath = 'D:\ImageDownload\%s' % (foldername) #下载到的本地目录
        
        if not os.path.exists(picpath):   #路径不存在时创建一个
           os.makedirs(picpath)   
        x = 0
        for imgurl in imglist:
            target = picpath+'\%s.jpg' % x
          print 'Downloading image to location: ' + target + '
    url=' + imgurl
           image = urllib.urlretrieve(imgurl, target, schedule)
          x += 1
       return image;
     
      
       
    if __name__ == '__main__':
       print '''            *************************************
                **      Welcome to use Spider      **
               **     Created on  2014-05-13      **
                **       @author: cruise           **
             *************************************'''
       
       html = getHtml("http://tieba.baidu.com/p/2460150866")
     
        downloadImg(html)
        print "Download has finished."
    

      

    这里的核心是用到了urllib.urlretrieve()方法,直接将远程数据下载到本地。
    下面我们再来看看 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。

    1>>> help(urllib.urlretrieve)
    2    Help on function urlretrieve in module urllib:
    3     
    4    urlretrieve(url, filename=None, reporthook=None, data=None)

    参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。
    参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。
      通过一个for循环对获取的图片连接进行遍历,为了使图片的文件名看上去更规范,对其进行重命名,命名规则通过x变量加1。保存的位置默认为程序的存放目录。
    在python shell中看到的信息如下:

    程序运行完成,将在目录下看到下载到本地的文件。

  • 相关阅读:
    SQL查询
    redis 命令行常用命令
    linux ss ip
    jdk下载地址
    requests.session保持会话
    Python通过重写sys.stdout将控制台日志重定向到文件
    解决Python3 控制台输出InsecureRequestWarning问题
    uniapp实现iframe效果
    模拟登录 react 的页面
    vueX的五大属性和使用方法包括辅助函数
  • 原文地址:https://www.cnblogs.com/jiguangdongtaiip/p/13607859.html
Copyright © 2011-2022 走看看