国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python批量下載圖片的三種方法

2019-11-25 18:39:20
字體:
來源:轉載
供稿:網友

有三種方法,一是用微軟提供的擴展庫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()

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平潭县| 顺昌县| 八宿县| 沂水县| 沾益县| 榆中县| 元朗区| 沅陵县| 沂源县| 天等县| 翁源县| 霸州市| 治县。| 清水县| 芦山县| 平阳县| 井冈山市| 贵德县| 敖汉旗| 綦江县| 新宁县| 微山县| 晋州市| 文山县| 民权县| 微山县| 乌鲁木齐市| 毕节市| 社旗县| 闵行区| 慈利县| 长岛县| 扬中市| 喀什市| 新龙县| 白朗县| 赤城县| 遵化市| 精河县| 东宁县| 监利县|