Home > front end >  navigate to active chrome tab using selenium and python code
navigate to active chrome tab using selenium and python code

Time:01-13

I am trying to navigate to the active chrome tab using Selenium and Python code. However, when I run my code, it opens a new window with a new profile, not the profile that I have specified. I have tried many things to solve this issue, but I do not know what the problem is.

Here is my code:

`

    import time
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    options = webdriver.ChromeOptions()
    options.add_argument(f"--user-data-dir=C:/Users/loai/AppData/Local/Google/Chrome/User Data/Profile 1")
    browser = webdriver.Chrome(chrome_options=options,executable_path=r"C://Users//loai//Downloads//chromedriver_win32//chromedriver.exe")
    
    # navigate to the webpage
    browser.get('https://nft.bueno.art/NS1PNAih8UHV6y1XviWJU/art/kZK_iEBrl-kK8NY_UznyI/preview')
    
    # find all elements with the class name "virtuoso-grid-item"
    grid_items = browser.find_elements(By.CLASS_NAME, 'virtuoso-grid-item')
    
    # iterate through the grid items and click on each one
    for item in grid_items:
        item.click()
        # switch to the newly opened tab
        browser.switch_to.window(browser.window_handles[-1])
        # navigate to the desired URL
        browser.get('https://nft.bueno.art/NS1PNAih8UHV6y1XviWJU/art/kZK_iEBrl-kK8NY_UznyI/preview')
        # you may want to add here a sleep time to avoid clicking too fast.
        time.sleep(2)
    
    # delay before closing the browser
    time.sleep(5)
    
    # close the browser
    browser.close()

`

I have specified the profile path 'C:/Users/loai/AppData/Local/Google/Chrome/User Data/Profile 1', but it still creates a new profile and continues with it. I want to run my code with the already active tab that has the specified URL that I have mentioned in the browser.get line.

Does anyone have a suggestion on how to fix this issue or has had a similar issue in the past?

My chrome browser version is Version 109.0.5414.75 (Official Build) (64-bit).

I am trying to navigate to the active chrome tab using Selenium and Python code. However, when I run my code, it opens a new window with a new profile, not the profile that I have specified.

CodePudding user response:

To open specific profile, you should set 2 chrome options:

chrome_options.add_argument('--user-data-dir=C:\\Users\\{user}\\AppData\\Local\\Google\\Chrome\\User Data')
chrome_options.add_argument('--profile-directory=Profile 1')
  • Related