打包 extension 為 zip, 在 selenium 加入 extension.
import os, zipfile
from selenium import webdriver
# Configure filepaths
chrome_exe = "path/to/chromedriver.exe"
ext_dir = 'extension'
ext_file = 'extension.zip'
# Create zipped extension
## Read in your extension files
file_names = os.listdir(ext_dir)
file_dict = {}
for fn in file_names:
with open(os.path.join(ext_dir, fn), 'r') as infile:
file_dict[fn] = infile.read()
## Save files to zipped archive
with zipfile.ZipFile(ext_file), 'w') as zf:
for fn, content in file_dict.iteritems():
zf.writestr(fn, content)
# Add extension
chrome_options = webdriver.ChromeOptions()
chrome_options.add_extension(ext_file)
# Start driver
driver = webdriver.Chrome(executable_path=chrome_exe, chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
driver.quit()