Mic*_* Wu 17 python selenium google-chrome selenium-webdriver
我目前正在使用Selenium来运行Chrome实例以测试网页.每次我的脚本运行时,都会启动一个干净的Chrome实例(清除扩展名,书签,浏览历史记录等).我想知道是否可以使用Chrome扩展程序运行我的脚本.我已经尝试过搜索Python示例,但是当我用Google搜索时没有出现任何问题.
ale*_*cxe 22
您应该使用chrome webdriver 选项来设置要加载的扩展列表.这是一个例子:
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()
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
最主要的答案对我不起作用,因为我没有意识到您必须将webdriver选项指向一个.zip
文件。
即chrome_options.add_extension('path_to_extension_dir')
不起作用。
你需要:chrome_options.add_extension('path_to_extension_dir.zip')
搞清楚了这一点,并阅读后夫妇 的帖子关于如何创建通过命令行zip文件并将其加载到selenium
,只有它为我工作的方式是相同的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()
Run Code Online (Sandbox Code Playgroud)
这是因为 selenium 期望打包扩展作为带有.crx
扩展的扩展参数。
我的 chrome 中已经有这个扩展了。以下是我打包现有扩展程序所遵循的步骤,
- 单击您的扩展程序“详细信息”。在我的 Chrome 版本中,它是打开的
right top click (3 dots) -> 'More tools' -> 'Extensions'.
- 在 chrome 中启用开发者模式
- 点击“打包扩展”(如上图)并打包。
- 这将存储在扩展位置。对我来说是
/home/user/.config/google-chrome/Default/Extensions/fdjsidgdhskifcclfjowijfwidksdj/2.3.4_22.crx
就是这样,您可以在 selenium 中配置扩展作为参数。
extension='/home/user/.config/google-chrome/Default/Extensions/fdjsidgdhskifcclfjowijfwidksdj/2.3.4_22.crx'
options = webdriver.ChromeOptions()
options.add_extension(extension)
Run Code Online (Sandbox Code Playgroud)
注意:您还可以在扩展 URL 中找到“fdjsidgdhskifcclfjowijfwidksdj”id 作为查询参数
归档时间: |
|
查看次数: |
20070 次 |
最近记录: |