1

I am using selenium webdriver with python. I am not able to find a way in python by which I can switch the webdriver to a new browser.

My web application have multiple links and buttons

Clicking on any of them leads to a new browser window being opened.

for clicking on buttons and link I have used below code

driver.find_element_by_css_selector("input[type=\"submit\"]").click()
driver.find_element_by_id("btn1").click()
driver.find_element_by_css_selector("#linksPlace > #OIT> a").click()

For selecting subsequent browser windows, I have used below code

for handle in driver.window_handles:
    print handle
    driver.switch_to_window(handle)
    driver.get_window_position(handle)
    driver.save_screenshot('E:\Selenium scripts\demo.png')

However I am not able to navigate to that new browser window. I have used below command as well, but things didn't work

     driver.switch_to_window(driver.window_handles[-1])

Is there any way by which I can navigate to new browser window? I have seen that there are functions which exist in java and c# to do the same, but struggled so far in python.

0

1 Answer 1

3

The problem could be that the page in the new window is still loading while you are trying to interact with it, so you might need to add in a wait condition.

When I've done this, I've added in waits to make sure that the new window has actually been opened, and then to make sure the page in the new window is loaded.

from selenium.webdriver.support.wait import WebDriverWait

# wait to make sure there are two windows open
WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == 2)

# switch windows
driver.switch_to_window(driver.window_handles[1])

# wait to make sure the new window is loaded
WebDriverWait(driver, 10).until(lambda d: d.title != "")

Note that window_handles[1] is usually the new window - if you need to, you can double check that it isn't actually the window you are in (by comparing to driver.current_window_handle.

Also, there is probably a better way in your case to test for page load other than the presence of the title - you could check for a specific element depending on the source of your page.

0

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