使用Selenium加载Chrome扩展程序

37

在运行selenium时,我需要从Web商店加载Chrome扩展程序。

有没有可能让selenium从Web商店加载扩展程序呢?


一个选择是在每次运行测试脚本时使用Java从Webstore下载CRX文件,然后将已下载的脚本加载到ChromeOptions中。 在Java中有许多从互联网下载文件的选项。这种方法对你来说可行吗? - parishodak
1
是的,即使从商店下载扩展并安装也可以。但我不确定我们是否可以下载CRX文件?我们有可用的下载URL吗? - D Deshmane
是的,使用Selenium是可能的。请参考此链接:在Selenium中通过ChromeDriver安装扩展程序 - sumit kumar pradhan
我没有看到任何提议的解决方案能够在没有人类交互的情况下完成这个任务 - 也就是说,手动加载crx文件。除了我的解决方案之外 - 我的解决方案提供了通过编程方式下载crx文件的功能。我们不讨论在启动Chrome之前使用load-extension或add.argument选项的问题。就这样。 - JB-007
8个回答

34

如果有人需要的话,我是使用Python完成这个操作的。

你只需要下载.crx文件(我使用了https://chrome-extension-downloader.com/),并将其保存在Python可以访问的地方。例如,我将它导入到与我的Python脚本相同的文件夹中,在那里加载exampleOfExtensionDownloadedToFolder.crx。

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

options = webdriver.ChromeOptions()
options.add_extension('./exampleOfExtensionDownloadedToFolder.crx')
driver = webdriver.Chrome(options=options) 
driver.get('http://www.google.com')

1
如果有人遇到了CRX验证失败的问题,这篇帖子可能会有所帮助 https://dev59.com/gbfna4cB1Zd3GeqPrV-P#58899807 - Jarad
这也适用于自定义打包扩展的压缩文件。 - Jossef Harush Kadouri
CRX验证无法解析扩展头。Chrome仅支持CRX3格式。扩展需要更新吗? - Rodrigo Vieira
请确保使用以下代码: options = Options() 而不是 options = webdriver.ChromeOptions() - zakaria kasmi

27

我不确定为什么你特别想从Webstore下载并安装到Chrome。

我找到了一些下载Chrome扩展的步骤:

-使用连接互联网的电脑,从扩展页面安装扩展:https://chrome.google.com/webstore/detail/
-导航到扩展源代码。在XP中,可以在此处找到:C:\Documents and Settings\\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
-您应该看到一个版本文件夹(即“0.0.21_0”)。复制此文件夹并将其移动到要安装的机器上。
-在已断开连接的计算机上打开chrome,并转到Wrench->工具->扩展
-单击Developer mode旁边的+以显示开发人员选项
-单击“打包扩展程序...”,并选择版本文件夹作为根目录。将私钥文件留空。这将创建一个.crx文件,以及一个私钥,就好像你是开发人员一样。

——或者——

1- 找到您感兴趣的扩展程序的ID。当在扩展程序的详细信息页面上时,它将类似于: bfbmjmiodbnnpllbbbfblcplfjjepjdn 之后 https://chrome.google.com/webstore/detail/

2- 将其粘贴到任何其他浏览器中(而不是Chrome): https://clients2.google.com/service/update2/crx?response=redirect&x=id%3D~~~~%26uc

3- 并用扩展ID替换~~~。 您将提示保存一个Crx文件。将此文件拖动到Chrome窗口中,并继续安装。

来源:https://productforums.google.com/forum/#!topic/chrome/g02KlhK12fU

最后,使用下载的.crx文件在ChromeOptions中加载扩展程序

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

来源: https://sites.google.com/a/chromium.org/chromedriver/extensions


我使用JS编写了一个函数,它会返回给定ID的下载URL。我的最终目标是拦截来自不同扩展程序的请求。为此,我使用了另一个扩展程序,在其中使用了'chrome.webRequest.onBeforeRequest' API来捕获请求。但是似乎Chrome不会将来自扩展程序的请求转发到我的处理程序。我可以使用的另一个API是'chrome.devtools.network.onRequestFinished',但只有在开发者工具打开时才能使用。现在我被卡住了,如何使用Selenium打开开发者工具?您能否评论一下我如何跟踪来自不同扩展程序的请求? - D Deshmane
我并不熟悉Chrome扩展程序的开发。请参考这篇文章https://dev59.com/03_aa4cB1Zd3GeqP-PY1,了解如何在JavaScript中修改扩展程序以包含用户所需的操作。不确定这是否有帮助。 - parishodak
5
回到2017年,似乎链接方法不再起作用了。有人可以确认吗? - firechant
1
@firechant 请参考 https://dev59.com/Jmw05IYBdhLWcg3wiyRJ#14099762 获取更新的方法。 - User

14

如何将Chrome扩展加载到Selenium Python中

日期=20-12-19
Chrome版本=79.0.3945.88

新版本的Chrome支持crx.crx(crx3),如果您使用crx,它会抛出错误。
仅在使用Chrome版本73或更高版本时才按照此步骤进行

1> 创建一个crx3文件。

1. 转到Chrome网上应用店并搜索您的扩展程序,复制扩展的链接。 截图
2. 转到网站,粘贴链接并下载适用于您的Chrome扩展的crx文件。
3. 转到GitHub页面,下载可将您的crx文件转换为crx3或crx.crx的模块。
4. 现在您有了crx.crx或(crx3)文件


2> Python代码添加Chrome扩展程序到Selenium

1. 将您的extension.crx.crx文件放在与您的代码相同的文件夹中,或者给出路径
2. 您可以复制并粘贴此代码,并更改`chrome_options.add_extension('YOUR - EXTENSION - NAME')`中的crx.crx文件名

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")

3
这是一篇很棒的回答,应该在2020年被采纳。非常感谢! - Danny
@Khan Saad,你能帮我指出任何博客文章或文档,解释如何在成功添加到驱动程序后执行扩展吗? - Dan
Github不会将crx转换为crx3,它会将文件夹转换为cr3。需要更多的解释吗? - Arnaud Hureaux
但最终它完成了工作,那还有什么关系呢? - Khan Saad

7
  1. Put chromedriver exe in your document file if you want to follow this and have a successful result.

  2. Download "GET CRX" extension from Google.

  3. Download your extension (i.e. mine is "DHS" for Rest API testing).

  4. Go to Chrome Web Store >> search for your extension (the one you've already downloaded) >> right click on it and click :: GET CRX
    (This should download the CRX file. For my case the CRX file is "extension_1_2_5.crx")

  5. Drop the CRX file in any Chrome window (this can reject it but no worries).

  6. Now, build your test and execute

    public static void openChromeExtension(){
    
        System.setProperty("webdriver.chrome.driver", "/Users/[your local name]/Documents/chromedriver");
    
        ChromeOptions options = new ChromeOptions();
        options.addExtensions(new File("/Users/[your local name]/Documents/extension_1_2_5.crx"));
    
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        ChromeDriver driver = new ChromeDriver(capabilities);
        System.out.println("Opening extension");
        driver.get("chrome-extension://**aejoelaoggembcahagimdiliamlcdmfm**/dhc.html"); 
    
        driver.navigate().refresh();
        System.out.println("Refresh successfully");
    }
    

    //this is the extension URL or you can get the id on chrome://extensions/ find the extension and copy the ID. However, the URL must be the extension URL.


它给我的文件是一个.bin文件而不是.crx文件。这正常吗? - MattCochrane
CRX验证无法解析扩展头。Chrome仅支持CRX3格式。扩展需要更新吗? - Rodrigo Vieira

3

不确定为什么,但有人删除了他们的回答,而那个回答是正确的。以下是内容(来自@parishodak):

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

这个例子是用Java编写的


我使用上述代码在 Selenium WD Java 中加载了 Chrome 扩展程序 - Google Tag Assistant。如何打开/观察标签助手面板? - Ripon Al Wasim

1
上述解决方案虽然从技术角度看起来是正确的,但并不总是按照预期工作。因此,我想到了另一种方法来解决问题。由于很多时候我需要手动完成很多事情,例如身份验证、某些cookie等,所以我使用文件夹作为配置文件,并运行以下命令:
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

然后我手动安装扩展程序并登录,现在每次我启动带有那个文件夹的Webdriver时,一切都在那里。

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see the Extensions and the logins done are present

优点是您可以使用多个带有不同设置和扩展的文件夹,而无需安装和卸载扩展,更改设置,更改登录等。

似乎这个不再起作用了。 - myalcin81
@myalcin81 你试过使用 from selenium.webdriver.chrome.options import Options 吗? - Eduard Florinescu
@myalcin81 你需要在这些实例之间手动添加扩展名。 - Eduard Florinescu
是的,我已经使用了ChromeOptions来添加Zip文件扩展,但仍然无法正常工作。 - myalcin81

0
using System.IO;
using System.IO.Compression;



  public static class ChromeExtension
        {
            public static string Execute()
            {
                var ParentPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
                var DirectoryPath = ParentPath.FullName.Remove(ParentPath.FullName.IndexOf(ParentPath.Name));

                string startPath = $"{DirectoryPath}\\Exchanger\\ChromeExtension";
                string zipPath = $"{DirectoryPath}Exchanger\\Extension.zip";

                if (System.IO.File.Exists(zipPath))
                {
                    System.IO.File.Delete(startPath);
                }

                ZipFile.CreateFromDirectory(startPath, zipPath);


                if (System.IO.File.Exists($"{DirectoryPath}\\Exchanger\\Extension.crx"))
                {
                    System.IO.File.Delete($"{DirectoryPath}\\Exchanger\\Extension.crx");
                }

                System.IO.File.Move(zipPath, $"{DirectoryPath}\\Exchanger\\Extension.crx");

                return $"{DirectoryPath}\\Exchanger\\Extension.crx";
            }

        }

....////....

Used: 
var options = new ChromeOptions();   
options.AddExtension(ChromeExtension.Execute());

....////....

0
使用selenium和Java添加任何Chrome扩展,我尝试了很多方法,但以下方法对我有效。通过使用该方法,我们可以通过脚本添加任何Chrome扩展/插件并启动它。
步骤1:打开Chrome扩展链接https://chrome.google.com/webstore/category/extensions driver.get("https://chrome.google.com/webstore/category/extensions");
在搜索框中搜索所需的扩展(如Google翻译),然后从自动建议列表中选择所需的扩展。然后点击扩展标题,即可打开扩展详情页面。
步骤2:除了使用步骤1,我们还可以通过插件ID直接打开扩展页面。直接打开以下链接也是一样的。 例如:https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb driver.get("https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb");
现在点击“添加到Chrome”,使用机器人按键(如TAB和EN)处理弹出窗口。
        Robot rb=new Robot();
        rb.keyPress(KeyEvent.VK_TAB);
        Thread.sleep(300);
        rb.keyRelease(KeyEvent.VK_TAB);
        Thread.sleep(1000);
        rb.keyPress(KeyEvent.VK_ENTER);
        Thread.sleep(300);
        rb.keyRelease(KeyEvent.VK_ENTER);

现在成功将Chrome扩展添加到Chrome浏览器中。要启动Chrome扩展,请为此安装的扩展创建一个快捷方式,并使用该快捷键在您想要启动/打开时打开扩展。
driver.get("chrome://extensions/shortcuts");

点击快捷图标并按下快捷键,例如:Control+Q。使用机器人键完成此操作。 一旦您通过按下此键添加了此快捷键,您就可以启动扩展程序。

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