[Python] Python Selenium how to prevent a non-link web element from opening in a new tab

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Python Selenium to find an element, click it, and have the new page stay open in the same window instead of opening in a new tab. I'm trying to be careful with how I word this because I it's not an anchor or url, from what I can tell. The html is:

    <div class="prevent-select">
    <div></div>
    <span class="tyl-list-item__text menuTitleClass" tabindex="0" data-testid="hub__tylermenu__node__title" text="Employee Job/Salary" aria-describedby="tcw-tooltip-56">Employee Job/Salary</span>
    <tcw-tooltip id="tcw-tooltip-56" style="border: 0px; clip: rect(0px, 0px, 0px, 0px); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; width: 1px; outline: 0px; appearance: none;">Enterprise ERP&gt;Human Capital Management&gt;Payroll&gt;Employee Maintenance&gt;Employee Job/Salary</tcw-tooltip>
    </div>


    My initial code (which IS opening it in a new tab) looks like:

    url_jobSalary = WebDriverWait(browser, 15).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'Employee Job/Salary')]"))).click()


    Since researching I've tried these techniques below, none of which are working:

    Technique #1

    #this technique failed because get_jobSalary is returned as nothing, I guess it cannot find an href attribute
    url_jobSalary = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, "//*[contains(text(), 'Employee Job/Salary')]")))
    get_jobSalary = url_jobSalary.get_attribute('href')
    browser.get(get_jobSalary)


    Technique #2

    #this one opens in a new tab still
    url_jobSalary = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, "//*[contains(text(), 'Employee Job/Salary')]")))
    browser.execute_script("arguments[0].target='_self';", url_jobSalary)
    url_jobSalary.click()


    Technique #3

    # Set chrome options -- I found a post that suggested adding the --profile-directory=default argument would work,
    # but it still opens in a new tab
    options = Options()
    options.add_argument('--profile-directory=Default') #prevent element from opening in new tab or window
    options.add_experimental_option("prefs", {
    "download.default_directory" : download_path
    })
    options.headless = False
    browser = webdriver.Chrome(options=options)


    Finally I found this post which feels on the right track, because the page I'm scraping is using those ng- commands, but I don't know how to write the code snippet the answer shows.

    Below is a screenshot of what the web element when I added it to a watch, maybe this will help:

    [​IMG]

    As always, any help is greatly appreciated!!

    Continue reading...

Compartilhe esta Página