selenium跳转新页面定位元素

今天写定位元素的时候遇到个问题,明明xpath写的是正确的,但是总是提示elenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element
没有找到元素,找了半天的原因,终于找到了。
在这里插入图片描述
跳转到新的页面,定位元素时,一定要加上这两行:
windows = driver.window_handles
driver.switch_to.window(windows[-1])
driver.window_handles是获取当前的所有窗口
driver.switch_to.window(windows[-1])是切换到最新打开的窗口
扩展:
driver.switch_to.window(windows[0])是切换原来的窗口
driver.current_window_handle是获取当前窗口
加上这两行再去定位元素就可以定位到了

你可能感兴趣的:(selenium)