使用扩展程序与Selenium (Python)

28

我目前正在使用Selenium来运行Chrome实例来测试网页。每次我的脚本运行时,一个干净的Chrome实例启动(没有扩展、书签、浏览历史等)。我想知道是否可能在我的脚本中运行Chrome扩展程序。我尝试搜索Python示例,但当我谷歌搜索时没有任何结果。

7个回答

37

您应该使用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()

希望这能帮到你。


1
你好,我测试了你的代码。但是有些东西似乎已经过时了。我收到了一个关于扩展目录的回溯错误 IsADirectoryError [Error 21]。我只想知道如何编写扩展的完整路径。我这里有 path/to/XXXXXXXXXXXXXXXXX/1.2.345,我应该在路径中加入这个版本号吗? - Joe
1
希望你能帮忙。我已经使用了这个答案来获取扩展的路径,所以你有什么想法为什么我会遇到这个错误?IsADirectoryError [Error 21]。提前致谢。 - Joe
一个问题:是否有一种设置可以阻止“感谢安装...”标签页? - rizerphe

15

领先的答案对我不起作用,因为我没有意识到你必须将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()

1
在无数个小时之后,这对我起作用了。谢谢。 - Kirell
很遗憾,对我来说它不起作用,你能提供一些需要放入 ext_dir = 'extension' 和 ext_file = 'extension.zip' 的值的示例吗? - neelmeg
ext_dir 应该是包含你想要加载的 Chrome 扩展的目录。我发布的脚本会将该目录压缩并创建 ext_file,然后您将其添加到浏览器选项中。最简单的扩展文件夹仅由 mainfest.jsonbackground.js 脚本组成。有关扩展的更多信息,您可以查看这个入门指南(https://developer.chrome.com/extensions/getstarted)和这个示例(https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/hello-world)。 - rer

6
这是因为Selenium期望打包的扩展作为扩展参数,其将具有.crx扩展名。 我已经在我的Chrome浏览器中安装了该扩展程序。以下是我打包现有扩展所遵循的步骤:

Chrome screenshot

  1. 点击浏览器扩展程序的“详细信息”。在我的Chrome版本中,它位于右上角点击(三个点)->“更多工具”->“扩展程序”。
  2. 启用开发者模式
  3. 点击“打包扩展程序”(如上所示)并进行打包。
  4. 这将被存储在扩展程序位置。对我而言,它在/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)

注意:您还可以在扩展程序的URL中找到“fdjsidgdhskifcclfjowijfwidksdj” ID作为查询参数。

3

另一种方法是使用未打包的文件夹方法。我发现在Selenium Grid上,crx和zip方法根本无法工作。在这种方法中,您需要从已经手动安装它的Chrome版本的用户数据中复制扩展名,长ID由很多字母组成,例如pehaalcefcjfccdpbckoablngfkfgfgj,将其复制到Selenium控制的Chrome的用户数据目录中(您可以在运行时使用此代码的第一行进行选择,并且它将自动填充)。 它应该在相同的等效目录(即Extensions)中。路径必须带您到其中有manifest.json的目录,因此在这个例子中是'1.1.0'。

chrome_options.add_argument("user-data-dir=C:/Users/charl/OneDrive/python/userprofile/profilename"
unpacked_extension_path = 'C:/Users/charl/OneDrive/python/userprofile/profilename/Default/Extensions/pehaalcefcjfccdpbckoablngfkfgfgj/1.1_0'
chrome_options.add_argument('--load-extension={}'.format(unpacked_extension_path))
driver = webdriver.Chrome(options=chrome_options)   

这对我有用!做得好,我的朋友! - Serhat

3
如果您想在 Selenium Python 脚本中导入任何 Chrome 扩展,请按照以下步骤操作:
  1. Put your extension.crx.crx file in the same folder as your code or give the path

  2. you can copy-paste this code and just change the file crx.crx name

    import os from selenium import webdriver from selenium.webdriver.chrome.options import Options

    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")
    
如果这段代码出现错误,也许这个能解决它。

1

我找到了最简单的方法。

之前尝试过制作 crx 文件等多种方式,但都没有成功。后来我发现只需要将未打包的扩展路径添加进去就可以了:

options.add_argument('--load-extension={}'.format("HERE YOUR EXTENSION PATH"))

将“HERE YOUR EXTENSION PATH”替换为您Chrome配置文件中的扩展路径。 在Windows上查找它,使用以下路径: C:\ Users [login_name] \ AppData \ Local \ Google \ Chrome \ User Data \ Default \ Extensions

然后,您必须选择扩展程序的文件夹,它是通过ID标识的,您可以在https://chrome.google.com/webstore/category/extensions中找到它,只需输入您的扩展程序名称,您将获得ID。 然后,在此文件夹中,将有您扩展程序的版本,例如:10.0.3,请选择它,它将成为您的路径,因此路径必须以版本结尾。

示例:

options.add_argument('--load-extension={}'.format(r'C:\Users\nevo\AppData\Local\Google\Chrome\User Data\Default\Extensions\nkbihfbeogaeaoehlefnkodbefgpgknn\10.20.0_0'))

请注意在字符串前加上“r”以使其成为原始字符串,否则我必须双倍反斜杠。
它可以工作!

这个完美运行,但是像你说的那样找到扩展的ID相对较难。我是通过右键单击扩展本身,然后点击“管理扩展程序”来找到它的。ID将显示在URL中或页面本身中。 - Prakash Dahal

1
我在使用Selenium时需要向Chrome添加扩展程序。我所做的是首先使用Selenium打开浏览器,然后像在Google Chrome中一样正常地向浏览器添加扩展程序。

1
如果您可以接受一些手动操作,那么这很有效。但对于那些试图在Selenium中完全自动化其工作的人来说,这并不理想。 - Michael Wu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接