0

I need to test interacting with two tabs in Chrome. I've written a test in Python using Webdriver where I open Chrome with one tab.

I need to open a second tab (similarly to using Ctrl+t) so I can interact with both tabs. My plan is to copy text from Tab 1 and paste it into one of the fields on Tab 2, and vice versa.

How do I use Python and WebDriver to open a new tab and switch between tabs?

  • I've edited your question to make it more obvious what you're asking. You're welcome to revert my edit if you don't think I understood what you meant. – Kate Paulk Feb 24 at 12:34
  • no it's okay thank you :D – Armin Mar 7 at 9:10
0

Opening a New Tab

You do it the same way you would with a keyboard. Control + t, or Command + t if using a Mac.

driver.get("https://www.google.com")

page = driver.find_element_by_tag_name('body')

page.send_keys(Keys.CONTROL + 't') 

#new tab is open
#navigate to second url

driver.get('http://stackoverflow.com/')

Switching Tabs

The answer to this question is what you're looking for.

1 - Switch between the tabs using the send_keys (CONTROL + TAB)

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

2 - Switch between the tabs using the using ActionsChains (CONTROL+TAB)

actions = ActionChains(self.driver)      
actions.key_down(Keys.CONTROL).key_down(Keys.TAB).key_up(Keys.TAB).key_up(Keys.CONTROL).perform()

3 - Another approach could make usage of the Selenium methods to check current window and move to another one:

You can use

driver.window_handles

to find a list of window handles and after try to switch using following methods.

- driver.switch_to.active_element      
- driver.switch_to.default_content
- driver.switch_to.window

driver.close() will close the specific tab that the web driver is on.

| improve this answer | |
0

you can use the below code, windows[1] will switch to the newly opened tab and windows[0] will switch back to the original tab.

    windows = driver.window_handles
    driver.switch_to.window(windows[1])
    driver.switch_to.window(windows[0])
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.