【问题标题】:How to Open a Google Chrome with extension in Selenium?如何在 Selenium 中打开带有扩展名的 Google Chrome?
【发布时间】:2021-04-05 19:25:21
【问题描述】:

我一直在寻找这个。我需要在 selenium 中打开带有扩展名的 Google Chrome。扩展名应从网上应用店添加,而不是使用.crx 文件。

我浏览过很多网站。就像this 网站一样,它显示了两种方法。通过使用第二种方式,我可以通过对路径进行硬编码来启动 chrome,但我需要使用第一种方式,以便使其动态化。

以下是我尝试过的代码,使用 chrome 的 --user-data-dir 属性,但它没有打开带有扩展名的浏览器。

PS:我知道这可以使用.crx 文件来完成,但我只需要从 Chrome 商店添加扩展程序。

提前致谢。

ChromeOptions opt1 = new ChromeOptions();
System.setProperty("webdriver.chrome.driver", "./Win/Drivers/chromedriver.exe");
opt1.addArguments("--user-data-dir = C:\\Sanity\\Chrome");
driver = new ChromeDriver(opt1);
driver.get("https://www.google.com");

【问题讨论】:

  • 您是否手动尝试使用新创建的配置文件打开浏览器以查看扩展是否可用?
  • 是的,它是手动工作的。
  • 您是否尝试过我在下面的“硬编码”响应中添加的内容??

标签: selenium google-chrome-extension


【解决方案1】:

使用预配置的配置文件

opt.add_argument('user-data-dir=folder')

其中文件夹是您感兴趣的 chrome 配置文件的位置(在其前面的“=”符号之前/之后没有任何空格 - 并检查配置文件的位置,例如 C:\Sanity\Chrome\User Data\Profile1 )

使用“硬编码”

opt1.add_argument('--load-extension={folder path with manifest here}')

(同样,没有空格)

opt.add_extension('{crx path here}')

机械方式

让我感到困惑的是,您曾多次强调“来自网上商店”。我知道如何直接从网上商店下载(即在启动 chrome/webdriver 之后)的唯一方法是使用以下类型的代码(它广泛使用 Pyautogui,并且比你的普通方式更不“精明”)..

PS - 老实说,我认为如果你只是用你当前使用的代码修正了你的拼写/语法,你会没事的 - 顺便说一句,在这方面的一些反馈会很有用......

import os, time, pyautogui
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait


def activ(wd):
    global index_activ
    index_activ = False
    try:
        wd.activate()
        index_activ = True
        return index_activ
    except:
        try:
            wd.minimize()
            wd.restore()
            index_activ = True
            return index_activ
        except: pass
    index_activ = False
    return index_activ

def ext_update(section = ''):

    global w, text_temp, ys, ys2
    text_temp=  ['']
    pyautogui.click()
    def button_click(parms = ['',True]):
        #parms[0] = ID, parms[1] = click?
        ID,click = parms[0], parms[1]
        global text_temp, button
        text_temp = ''
        ID = ['omghfjlpggmjjaagoclmmobgdodcjboh'] if ID == '' else ID #default i= Browsec if no ID entered
        d.get(f'https://chrome.google.com/webstore/detail/{ID[0]}')
        w = WebDriverWait(d, 10)
        w.until(lambda x: x.execute_script("return document.readyState") == "complete")
        button = w.until(lambda x: x.find_element_by_class_name('g-c-R'))
        text_temp = button.text.lower()
        if click == True:  button.click()

    def add_remove():
        global ys, ys2, after2, handles,cl, gaw
        [cl, gaw] = [pyautogui.click,pyautogui.getActiveWindow]
        handles = d.window_handles
        activ(ys[0]), (ss, 0.5),  pr('tab'), ss(0.5), pr('space')
        while len(gwwt('')) <= len(after) : pass
        pr('escape')

    def close_extra():
        global w
        w_old = w
        w = WebDriverWait(d, 10)
        tabs_close_extra()
        activ(wd), pr('a'), activ(wd), pr('enter')
        w.until(lambda x: x.execute_script("return document.readyState") == "complete")
        w = w_old

    tabs_close_extra()
    before = gwwt('')
    button_click(['',False])
    if 'remove' in text_temp: return 'extension already added!'
    else: button_click()
    cc(2)
    after, ys = gwwt(''), []
    for x in after: ys = ys + [x,] if x not in before else ys
    print(add_remove())
    close_extra()
    button_click(['',False])
    print(text_temp)
    qs = 0
    qs = qs + 1 if sum(1 for x in [text_temp] if 'add' in x.lower()) > 0 else qs
    print(f'qs: {qs}')
    if section == 2: return #prevent never-ending loop (see next comment)
    if qs > 0: ext_update(section = 2) #loop back on self in case 'add extension' still present in web-stor
    return 'success'

def new_profile():
    global ev, parent, d, w, wd
    global path_core, path_exec
    global cc, ss, hk, pr, tw, gwwt

    wd = ''
    [cc, ss, hk, pr, tw, gwwt] = [pyautogui.countdown, time.sleep, pyautogui.hotkey,pyautogui.press, pyautogui.typewrite,pyautogui.getWindowsWithTitle]
    path_core= os.path.join(os.path.expanduser("~"), 'PyCharmProjects', 'Parallel')
    path_exec =  os.path.join(path_core, "chromedriver.exe")
    d = webdriver.Chrome(executable_path=path_exec) #executable_path=path_exec)
    parent = d.current_window_handle
    w = WebDriverWait(d,5)
    #d.implicitly_wait(0.5)
    try: d.get('https://x0')
    except: pass
    start = time.time()
    while (wd == '') and (time.time() - start <=10):
        try: wd = gwwt('x0')[0]
        except: pass
    d.implicitly_wait(5)
    print('new profile complete')

def tabs_close_extra(url_karg = ''):
    # alternative method (much slower): https://stackoverflow.com/questions/12729265/switch-tabs-using-selenium-webdriver-with-java
    try:
        parent = d.current_window_handle
        for h in d.window_handles:
            d.switch_to.window(h)
            if url_karg != '':
                if url_karg.lower() in d.current_url.lower(): parent = h
                else:
                    d.switch_to.window(parent)
            else: parent = h
            break
        tabs_original = len(d.window_handles)
        if tabs_original > 1:
            for h in d.window_handles:
                if h != parent:
                    d.switch_to.window(h)
                    d.close()
            d.switch_to.window(parent)
    except:
        print(f'error in tabs_close_extra ')


if __name__ == '__main__':
    new_profile()
    ext_update()

【讨论】:

  • (re:使用“硬编码”:忽略 {} 周围的文件夹路径/crx 位置 - 您只需在每种情况下放置相应的位置)
猜你喜欢
  • 2019-08-27
  • 2014-10-02
  • 2018-10-12
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多