How to switch tabs using the expected conditions new_window_is_opened and verify the page title using Selenium and Python
new_window_is_opened(current_handles)
new_window_is_opened(current_handles)
is the expectation that a new window will be opened and have the number of windows handles increase.
Demonstration
The following example opens the url http://www.google.co.in first and then opens the url https://www.yahoo.com in the adjacent tab:
from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECoptions = webdriver.ChromeOptions() options.add_argument("start-maximized")driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')driver.get("http://www.google.co.in")windows_before = driver.window_handlesdriver.execute_script("window.open('https://www.yahoo.com')")WebDriverWait(driver, 20).until(EC.new_window_is_opened(windows_before))driver.switch_to.window([x for x in driver.window_handles if x not in windows_before][0])
Note: The argument passed to
new_window_is_opened(current_handles)
is a list. In order to create a list we need to usewindows_before = driver.window_handles
This usecase
In your code block, it is expected that when you:
current = self.driver.current_window_handle
There exists only one window handle. So moving forward, the line of code:
wait(self.driver, 10).until(EC.new_window_is_opened(self.driver.window_handles))
would wait for a new window to be opened and have the number of windows handles increases and that would happen only after an action is performed which opens a new window, which seems to be missing from your code block.
Solution
Insert the line of code which initiates opening of a new window-handles:
from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECwindows_before = driver.window_handleselement = driver.find_element_by_xpath("//input[@id='save' and @name='save'][@value='View Report']")driver.execute_script("arguments[0].click();", element)WebDriverWait(self.driver, 10).until(EC.new_window_is_opened(windows_before))driver.switch_to.window([x for x in driver.window_handles if x not in windows_before][0])assertTrue("Valuation" == driver.title)
Note: As per the lines of code you have updated within your comments you are not using Python class, so you shouldn't use the keyword
self
.