Joshua Alayon
Joshua Alayon

Reputation: 25

Clicking opens a new link

selenium/chromedriver

When clicking a button, a new tab is opened when I do it through a GUI browser.

Python Selenium seems to have no problem clicking the button, as it gives me no errors. The errors come in the next step, when I need to find an element in the clicked page. I had selenium take a screenshot and it still shows the first page.

Presumably it clicked the button, created a new tab, and didn't switch over?

How do I switch to the new tab, or even verify the new tab exists in the first place?

Thank you!

Upvotes: 0

Views: 35

Answers (1)

Entest89
Entest89

Reputation: 87

When you open a browser with selenium, it stores a handle for each tab/window it is controlling in a list called window_handles, for example:

from selenium import webdriver
driver = webdriver.Firefox()

print(driver.window_handles)

...should give you something like ['6b7af9bb-f299-462e-a79a-2b8fda63f388']

When you open a new tab, a new handle for that window/tab should be added to that list. To then switch to the tab you want, use driver.switch_to.window(), for example (continuing above example):

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

Note: you could also use driver.switch_to_window, but this is deprecated in favor of the above example.

Also, just a tip for debugging, it can be helpful to use the python repl so you can follow what the browser is doing in real time.

Upvotes: 1

Related Questions