現在、Seleniumを使用してChromeのインスタンスを実行してWebページをテストしています。スクリプトが実行されるたびに、Chromeのクリーンなインスタンスが起動します(拡張機能のクリーンアップ、ブックマーク、閲覧履歴など)Chrome拡張機能でスクリプトを実行できるかどうか疑問に思っていました。Pythonの例を検索してみました、しかし私がこれをググったとき何も思いつきませんでした。
ロードする拡張機能のリストを設定するには、Chrome WebDriver options を使用する必要があります。以下に例を示します。
import os
from Selenium import webdriver
from Selenium.webdriver.chrome.options import Options
executable_path = "path_to_webdriver"
os.environ["webdriver.chrome.driver"] = executable_path
chrome_options = Options()
chrome_options.add_extension('path_to_extension')
driver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
driver.quit()
お役に立てば幸いです。
Webドライバーのオプションを_.Zip
_ファイルに向ける必要があることに気づかなかったため、最初の答えはうまくいきませんでした。
つまりchrome_options.add_extension('path_to_extension_dir')
は機能しません。
次のものが必要です:chrome_options.add_extension('path_to_extension_dir.Zip')
それを理解し、コマンドラインでZipファイルを作成してSelenium
にロードする方法について coupleposts を読んだ後、それが機能する唯一の方法私にとっては、同じpythonスクリプト内で拡張ファイルを圧縮することでした。これは、拡張に加えた変更を自動的に更新するための素晴らしい方法であることが判明しました:
_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()
_
chrome Seleniumの拡張機能をインポートする場合python scrip
Extension.crx.crxファイルをコードと同じフォルダーに配置するか、パスを指定します
このコードをコピーして貼り付け、ファイルcrx.crxの名前を変更するだけです
seleniumからosをインポートしますSelenium.webdriver.chrome.optionsからインポートwebdriverインポートオプション
executable_path = "/webdrivers"
os.environ["webdriver.chrome.driver"] = executable_path
chrome_options = Options()
chrome_options.add_extension(' YOUR - EXTIONTION - NAME ')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
このコードがおそらくエラーをスローしている場合 this はそれを解決します