0

Just like the title says, I am having trouble with getting my code to focus on a new window, using the "driver.switch_to_window".

My task is to: Click button on the parent page > new window appears > click an "accept" button on the new window and continue with the rest of the code

driver.get("https:testpage.com/")
driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[2]/ul/li[1]/button").click()

#here the window appears
time.sleep(2)

driver.switch_to_window("windowName")
driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[3]/button[2]").click() #here nothing happens 



4non
  • 35
  • 4
  • You need the window handle. Basically you want to get the current window handle first. (driver.getWindowHandle())... after the new window is opened, get all window handles (driver.getWindowHandles()) and iterate through them to find the one that is not the original handle. (Because index order is not guaranteed...) See this thread: https://stackoverflow.com/questions/45476200/in-selenium-how-to-handle-a-new-window Also remember that the new window may not have finished loading... best to use a webdriverwait when finding elements. (and more targetted xpaths) – pcalkins Nov 12 '21 at 22:01

1 Answers1

0

You can try to get the page source so that you are sure whether the driver has switched or not:

html_source = browser.page_source

It is possible that it has switched, but your element is not loaded or is in iframe. If your element is present, then you can try with different XPath that is relative, e.g. find the nearest id and find your element from it:

//div[@id='someid']//button[text()='someText'] 

I do not use absolute XPaths as I think they are too fragile.

Reference:
Python Selenium accessing HTML source

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

K. B.
  • 3,342
  • 3
  • 19
  • 32