python+selenium+chrome批量檔案下載並自動建立資料夾例項
實現效果:通過url所繫結的關鍵名建立目錄名,每次訪問一個網頁url後把檔案下載下來
程式碼:
其中 data[i][0]、data[i][1] 是代表 關鍵詞(檔案儲存目錄)、網站連結(要下載檔案的網站)
def getDriverHttp(): for i in range(reCount): # 建立Chrome瀏覽器配置物件例項 chromeOptions = webdriver.ChromeOptions() # 設定下載檔案的儲存目錄為d盤的tudi目錄, # 如果該目錄不存在,將會自動建立 prefs = {"download.default_directory": "e:\\tudi\\{0}".format(data[i][0]),"profile.default_content_setting_values.automatic_downloads":1} # 將自定義設定新增到Chrome配置物件例項中 chromeOptions.add_experimental_option("prefs",prefs) # 啟動帶有自定義設定的Chrome瀏覽器 # driver = webdriver.Chrome(executable_path="e:\\chromedriver",chrome_options=chromeOptions) driver = webdriver.Chrome(chrome_options=chromeOptions) driver.get(data[i][1]) info2 = re.findall(r'<a href="#" rel="external nofollow" onclick="(.*?)" cssclass="xz_pic">',driver.page_source,re.S) print(len(info2)) for js in info2: driver.execute_script(js) def main(): getDriverHttp()
注意:python 使用selenium下載檔案時,chrome會提示是否下載多個檔案(Download multiple files)
prefs = {"download.default_directory": "e:\\tudi\\{0}".format(data[i][0]),"profile.default_content_setting_values.automatic_downloads":1}
設定允許多個檔案下載。
補充知識:python專案實現配置統一管理的操作
一個比較大的專案總是會涉及到很多的引數,最好的方法就是在一個地方統一管理這些引數。最近看了不少的python專案,總結了兩種很有意思的配置管理方法。
第一種 基於easydict實現的配置管理
首先需要安裝numpy、easydict以及yaml:
pip install numpy
pip install easydict
pip install yaml
就可以了。
然後定義配置類config.py:
import numpy as np from easydict import EasyDict as edict import yaml # 建立dict __C = edict() cfg = __C # 定義配置dict __C.dev = edict() __C.dev.name = 'dev-xingoo' __C.dev.age = 20 __C.test = edict() __C.test.name = 'test-xingoo' __C.test.age = 30 # 內部方法,實現yaml配置檔案到dict的合併 def _merge_a_into_b(a,b): """Merge config dictionary a into config dictionary b,clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k,v in a.items(): # a must specify keys that are in b if k not in b: raise KeyError('{} is not a valid config key'.format(k)) # the types must match,too old_type = type(b[k]) if old_type is not type(v): if isinstance(b[k],np.ndarray): v = np.array(v,dtype=b[k].dtype) else: raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]),type(v),k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k],b[k]) except: print(('Error under config key: {}'.format(k))) raise else: b[k] = v # 自動載入yaml檔案 def cfg_from_file(filename): """Load a config file and merge it into the default options.""" with open(filename,'r',encoding='utf-8') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg,__C)
使用的時候很簡單,main.py:
from config import cfg_from_file from config import cfg cfg_from_file('config.yml') print(cfg.dev.name) print(cfg.test.name)
同級目錄下建立配置檔案config.yaml
dev:
name: xingoo-from-yml
輸出:
xingoo-from-yml
test-xingoo
總結
這樣的好處就是在任何的Python檔案中只要from config import cfg就可以使用配置檔案。
第二種 基於Class實現
這種基於普通的python物件實現的,建立config2.py:
class Config: def __init__(self): self.name = 'xingoo-config2' self.age = 100
使用的時候直接建立一個新的物件,如何python模組之間需要引用這個變數,那麼需要把配置物件傳過去:
import config2 as config2 cfg2 = config2.Config() print(cfg2.name) print(cfg2.age)
輸出為:
xingoo-config2
100
總結
第二種方法簡單粗暴...不過每次傳遞引數也是很蛋疼。還是喜歡第一種方式。
以上這篇python+selenium+chrome批量檔案下載並自動建立資料夾例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。