1

I am using the Selenium Python Bindings for web browser automation in Chrome. As part of the automation script, I click on a link and the website opens the page in a new tab. However, the WebDriver object in my python script is still pointing to the first tab.

I have tried all of the options offered on this answer but none were successful.

The only code I have been able to get to work so far is this:

driver.switch_to.window(driver.window_handles[1])

The problem I have with this is that I'm afraid I can't guarantee that the new tab will be at index 1, nor do I think I can guarantee that the new tab is at the last index. I did try using keys like this:

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

But using some logging I saw that the driver was still pointing to the first tab. Is there a way to focus on the current tab that chrome is showing?

Community
  • 1
  • 1
AdamMc331
  • 16,492
  • 10
  • 71
  • 133

1 Answers1

2

Whenever I have cases like these I switch to the last window handle, so far it worked for me:

driver.switch_to.window(driver.window_handles[-1])
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I had no idea -1 would automatically switch to the last tab, thanks for that! I will try it out, but unfortunately the website I'm automating is down for maintenance (just my luck) but I will let you know how it works. – AdamMc331 Jul 16 '15 at 17:07