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

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.