python批量下载图片的三种方法


Posted in Python onApril 22, 2013

有三种方法,一是用微软提供的扩展库win32com来操作IE,二是用selenium的webdriver,三是用python自带的HTMLParser解析。win32com可以获得类似js里面的document对象,但貌似是只读的(文档都没找到)。selenium则提供了Chrome,IE,FireFox等的支持,每种浏览器都有execute_script和find_element_by_xx方法,可以方便的执行js脚本(包括修改元素)和读取html里面的元素。不足是selenium只提供对python2.6和2.7的支持。HTMLParser则是需要自己写个类继承基类,重写解析元素的方法。个人感觉selenium用起来更方便,很容易操作html里的元素。
代码如下:

win32com:

#将滚动条滑到底,最多滑动20000像素
#模拟键盘右键,查看多张图片
import sys
import win32com.client,win32api
import urllib.request
import time
import os
def main():
    #获取参数
    url=sys.argv[1]
    #操作IE
    ie=win32com.client.Dispatch("InternetExplorer.Application")
    ie.Navigate(url)
    ie.Visible=True
    last_url=''
    dir_name=''
    while last_url!=url:
        print('\nThe URL is:',url,'\n')
        while ie.ReadyState != 4:    
            time.sleep(1)
        while ie.Document.readyState != "complete": 
            time.sleep(1)
        #滑动滚动条
        win=ie.Document.parentWindow
        lastY=-1;
        for i in range(40):
            win.scrollTo(0,500*i)
            nowY=win.pageYOffset
            if(nowY==lastY):
                break
            lastY=nowY
            time.sleep(0.4)
        print('Document load state:',ie.Document.readyState)
        doc=ie.Document
        #第一次需要创建目录
        if(dir_name==''):
            root_dir='E:\\img'
            dir_name=root_dir+'\\'+doc.title
            dir_name=dir_name.replace('|','-')
            if(os.path.exists(root_dir)!=True):
                os.mkdir(root_dir)
            if(os.path.exists(dir_name)!=True):
                os.mkdir(dir_name)
        all_image=doc.images
        print('共有',all_image.length,'张图片')
        count=0;
        for img in all_image:
            if(img.id=='b_img'):
                count=count+1
                print(count,img.src)
                time.sleep(1)
                img_file=urllib.request.urlopen(img.src)
                byte=img_file.read()
                print(count,'donwload complete!','-'*10,'size:','{:.3}'.format(byte.__len__()/1024),'KB')
                if(byte.__len__()>7000):
                    file_name=img.src.replace('/','_')
                    file_name=file_name.replace(':','_')
                    end=file_name.__len__()
                    if(file_name.rfind('!')!=-1):
                        end=file_name.rfind('!')
                    if(file_name.rfind('?')!=-1):
                        end=file_name.rfind('?')
                    file_name=file_name[:end]
                    write_file=open(dir_name+'\\'+file_name,'wb')
                    write_file.write(byte)
                    write_file.close()
                    print(count,file_name,'complete!')
        #下一张
        last_url=url
        win32api.keybd_event(39,0)
        time.sleep(1)
        url=ie.Document.url
        print(last_url,url)
    #ie.Quit()
if __name__ == '__main__':
    main()

selenium:

# -*- coding: cp936 -*-
import sys
import urllib
import time
import os
from selenium import webdriver
def main():
    #获取参数
    url=sys.argv[1]
    #操作IE
    driver=webdriver.Chrome()
    driver.get(url)
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    #创建目录
    dir_name=driver.find_element_by_tag_name('title').text
    print dir_name
    root_dir='E:\\img'
    dir_name=root_dir+'\\'+dir_name
    dir_name=dir_name.replace('|','-')
    if(os.path.exists(root_dir)!=True):
        os.mkdir(root_dir)
    if(os.path.exists(dir_name)!=True):
        os.mkdir(dir_name)
    images=driver.find_elements_by_tag_name('img')
    count=0
    for image in images:
        count=count+1
        image_url=str(image.get_attribute('src'))
        img_file=urllib.urlopen(image_url)
        byte=img_file.read()
        print count,'donwload complete!','-'*10,'size:',byte.__len__()/1024,'KB'
        if(byte.__len__()>7000):
            file_name=image_url.replace('/','_')
            file_name=file_name.replace(':','_')
            end=file_name.__len__()
            if(file_name.rfind('!')!=-1):
                end=file_name.rfind('!')
            if(file_name.rfind('?')!=-1):
                end=file_name.rfind('?')
            file_name=file_name[:end]
            write_file=open(dir_name+'\\'+file_name,'wb')
            write_file.write(byte)
            write_file.close()
            print count,file_name,'complete!'
    driver.quit()
if __name__ == '__main__':
    main()

HTMLParser:

# import modules used here -- sys is a very standard one
import sys
import urllib.request
# Gather our code in a main() function
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
    def handle_starttag(self,tag,attrs):
        if(tag=='img'):
            for attr in attrs:
                if(attr[0]=='src'):
                    img_file=urllib.request.urlopen(attr[1])
                    byte=img_file.read()
                    #文件大于1000b则生成文件,添加计数,下载多少图片,显示html代码
                    if(byte.__len__()>1000):
                        file_name=attr[1].replace('/','_')
                        file_name=file_name.replace(':','_')
                        end=file_name.__len__()
                        if(file_name.rfind('!')!=-1):
                            end=file_name.rfind('!')
                        if(file_name.rfind('?')!=-1):
                            end=file_name.rfind('?')
                        file_name=file_name[:end]
##                        print(file_name)
                        write_file=open('E:\\img\\'+file_name,'wb')
                        write_file.write(byte)
                        write_file.close()
def main():
    #获取参数
    url=sys.argv[1]
    print('\nThe URL is:',url,'\n')
    #读取url所指向的资源
    html_file=urllib.request.urlopen(url)
    byte_content=html_file.read()
    #将html网页保存起来
    url_file=open('E:\\img\\html\\result.htm','wb')
    url_file.write(byte_content)
    url_file.close()
    #从字节转换为字符串
    s=str(byte_content, encoding = "utf-8")
    #print(s)
    #bytes.decode(html_file.read())
    parser=MyHTMLParser(strict=False)
    parser.feed(s)
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
    main()
Python 相关文章推荐
python的re模块应用实例
Sep 26 Python
Python实现带百分比的进度条
Jun 28 Python
python 禁止函数修改列表的实现方法
Aug 03 Python
解析Python中的eval()、exec()及其相关函数
Dec 20 Python
Django JWT Token RestfulAPI用户认证详解
Jan 23 Python
python selenium登录豆瓣网过程解析
Aug 10 Python
浅谈PyTorch中in-place operation的含义
Jun 27 Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
Jul 14 Python
对pytorch中x = x.view(x.size(0), -1) 的理解说明
Mar 03 Python
python实现简单聊天功能
Jul 07 Python
ROS系统将python包编译为可执行文件的简单步骤
Jul 25 Python
python可视化分析绘制带趋势线的散点图和边缘直方图
Jun 25 Python
如何运行Python程序的方法
Apr 21 #Python
python读取注册表中值的方法
Apr 08 #Python
重命名批处理python脚本
Apr 05 #Python
Python编写的com组件发生R6034错误的原因与解决办法
Apr 01 #Python
Python中用Ctrl+C终止多线程程序的问题解决
Mar 30 #Python
python利用hook技术破解https的实例代码
Mar 25 #Python
利用python获得时间的实例说明
Mar 25 #Python
You might like
PHP中在数据库中保存Checkbox数据(1)
2006/10/09 PHP
PHP 数组排序方法总结 推荐收藏
2010/06/30 PHP
yii框架中的Url生产问题小结
2012/01/16 PHP
php中运用http调用的GET和POST方法示例
2014/09/29 PHP
使用PHP如何实现高效安全的ftp服务器(二)
2015/12/30 PHP
safari下载文件自动加了html后缀问题
2018/11/09 PHP
PHP设计模式之 策略模式Strategy详解【对象行为型】
2020/05/01 PHP
jQuery Mobile 导航栏代码
2013/11/01 Javascript
JavaScript中的值类型转换介绍
2014/12/31 Javascript
基于jQuery+JSON的省市二三级联动效果
2015/06/05 Javascript
轻松学习jQuery插件EasyUI EasyUI表单验证
2015/12/01 Javascript
JS Attribute属性操作详解
2016/05/19 Javascript
React教程之Props验证的具体用法(Props Validation)
2017/09/04 Javascript
Python中使用PyHook监听鼠标和键盘事件实例
2014/07/18 Python
python采集百度百科的方法
2015/06/05 Python
Python3之简单搭建自带服务器的实例讲解
2018/06/04 Python
Python面向对象之类和对象实例详解
2018/12/10 Python
Python玩转加密的技巧【推荐】
2019/05/13 Python
python+selenium实现简历自动刷新的示例代码
2019/05/20 Python
浅谈Python 敏感词过滤的实现
2019/08/15 Python
基于python traceback实现异常的获取与处理
2019/12/13 Python
Python函数式编程实例详解
2020/01/17 Python
手把手教你进行Python虚拟环境配置教程
2020/02/03 Python
Pyinstaller打包Scrapy项目的实现步骤
2020/09/22 Python
幼教个人求职信范文
2013/12/02 职场文书
保护动物倡议书
2014/04/15 职场文书
作文评语大全
2014/04/23 职场文书
医院院务公开实施方案
2014/05/03 职场文书
2014年党员创先争优承诺书
2014/05/29 职场文书
县政府办公室领导班子对照检查材料思想汇报
2014/09/28 职场文书
民事诉讼代理授权委托书
2014/10/11 职场文书
大学四年个人总结
2015/03/03 职场文书
五星级酒店前台接待岗位职责
2015/04/02 职场文书
小学教师工作总结2015
2015/04/07 职场文书
二婚主持词
2015/06/30 职场文书
2016大一新生入学教育心得体会
2016/01/23 职场文书