create the zip file via the command line and load it into selenium

打包 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()

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *