Fatih Tüz
Fatih Tüz

Reputation: 1

How to access an element that open in new tab via clicking a link button using python selenium?

There is a button in the website. When I click by click() method, it opens in the new tab.

I tried this method to access the element which is located in the second tab.

for _ in range(3):
    time.sleep(5)
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

    try:
        content = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "/html/body/div/p[1]"))).text
        print(content)
    except:
        print("...")

and the result was,

...
...
...

I guess, it accepts the first tab as an active tab. How to access an element in the other tab, by using python selenium. I searched some solution, and they were saying almost same thing which is to use CTRL+TAB method same as mine...

Upvotes: 0

Views: 1505

Answers (1)

jackblk
jackblk

Reputation: 1165

You need to switch your driver to the new tab, then switch it back when it's done.

Assuming you have 2 tabs:

# you already opened new tab
tab1 = driver.window_handles[0]
tab2 = driver.window_handles[1]

driver.switch_to.window(tab2) # switch to new tab

# do your stuff here

driver.close() # close new tab

driver.switch_to.window(tab1) # switch to original tab

Upvotes: 0

Related Questions