實現需求:批量下載聯想某型號的所有驅動程序。python
通常在作網絡爬蟲的時候,都是保存網頁信息爲主,或者下載單個文件。當涉及到多文件批量下載的時候,因爲下載所需時間不定,下載的文件名不定,因此有必定的困難。git
在涉及下載的時候,須要先對chromedriver
進行參數配置,設定默認下載目錄:github
global base_path profile = { 'download.default_directory': base_path } chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option('prefs', profile) driver = webdriver.Chrome(executable_path='../common/chromedriver', options=chrome_options) driver.implicitly_wait(10)
聯想官網上每一個型號的驅動下載頁面如上圖所示,雖然前面有一個登錄的遮罩,可是實際上並不影響點擊。須要注意的是:web
驅動列表,須要點擊才能夠顯示具體的下載項目表格,不然能夠找到對應元素但沒法獲取正確的信息chrome
driver_list.find_element_by_class_name('download-center_list_t_icon').click()
每一個下載列表的表頭建議作跳過處理api
if sub_list.find_element_by_class_name('download-center_usblist_td01').text == '驅動名稱': continue
在頁面中,找到「普通下載」的元素,點擊便可下載。最終實現結果是咱們但願根據網頁的列表進行重命名和從新歸檔到文件夾,可是咱們會發現以下幾個問題:網絡
在網上找了好久,也沒找到在下載時直接重命名的方法,因此最終選擇依次下載,當每次下載完成後進行重命名和歸檔,思路以下:函數
os
模塊,找到下載目錄中全部文件,並按建立時間排序,找到最新建立的文件.crdownload
(chrome),那麼根據後綴來判斷是否已完成下載,未完成的話繼續等待/
符號,不然會致使重命名失敗,須要作一下替換。在後期測試的時候,發現還有幾個坑須要注意:測試
.DS_Store
文件的處理。(Mac系統,Windows則須要考慮thumbs.db
)filter
函數來處理最新文件的排序查找實現以下:spa
def sort_file(): # 排序文件 dir_link = base_path dir_lists = list(filter(check_file, os.listdir(dir_link))) if len(dir_lists) == 0: return '' else: dir_lists.sort(key=lambda fn: os.path.getmtime(dir_link + os.sep + fn)) return os.path.join(base_path, dir_lists[-1]) def check_file(filename): # 忽略系統文件 if filename == '.DS_Store' or filename == 'thumbs.db': return False global base_path # 排除文件夾 return os.path.isfile(os.path.join(base_path, filename))
最終實現效果以下:
完整代碼參考:https://github.com/keejo125/w...
若是你們有更好的方法,也歡迎分享。