0

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...

  • 1
    Does this answer your question? [How do I switch to the active tab in Selenium?](https://stackoverflow.com/questions/28715942/how-do-i-switch-to-the-active-tab-in-selenium) – JaSON Oct 22 '20 at 10:59

1 Answers1

1

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
jackblk
  • 1,076
  • 8
  • 19