2

I have been searching for this for a while. I need to open Google Chrome with extension in selenium. The extension should be added from the Web Store and not using .crx file.

I have gone through many websites. Like this website that shows the two ways of doing it. By using the second way I'm able to launch the chrome by hard coding the path but I need to do it the first way so I can make it dynamic.

Below is the code which I have tried, using --user-data-dir property of chrome but it is not opening the browser with extension.

PS: I know that this can be done using .crx file but I need to add the extension from Chrome Store only.

Thanks in advance.

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");
Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
Abhishek
  • 34
  • 3

1 Answers1

0

Using pre-configured profile

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

where folder is the location of the chrome profile you're interested in (without any spaces before / after '=' sign preceding it - and check the location of the profile e.g. C:\Sanity\Chrome\User Data\Profile1)

Using 'hard coding'

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

(again, no spaces)

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

Mechanical way

What confues me is that you've emphasied 'from the webstore' a couple of times. The only way I know how to download directly from webstore (i.e. after launching chrome/webdriver) is with following type of code (which makes use of Pyautogui extensively, and is less 'savvy' then your ordinary way of doing it)..

PS - I honestly think that if you just fixed your spelling/syntax with the code you're currently using, you'll be fine - some feedback in this regard would be useful btw....

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()
JB-007
  • 2,156
  • 1
  • 6
  • 22
  • (re: Using 'hard coding': ignore the {} surrounding folder path/crx location - you'd just put the respective locations in each case) – JB-007 Feb 16 '21 at 01:41