简体   繁体   中英

Changing focus to a new window in Python/Selenium

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".

It just doesn't seem to focus on the new window, not sure why, it might be anything from something as little as me needing to "import" at the start of the code that I am missing, cause the Selenium documentation doesn't really explain the "import" or "from" part as much

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 



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, eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM