在使用selenium進行web自動化測試時,經常需要切換到新窗口來操作。切換到新窗口可以使用以下步驟:
獲取當前窗口的句柄:
makefile
Copy code
current_handle = driver.current_window_handle
獲取所有窗口的句柄:
makefile
Copy code
all_handles = driver.window_handles
遍歷所有窗口的句柄,找到新窗口并切換到該窗口:
yaml
Copy code
for handle in all_handles:
if handle != current_handle:
driver.switch_to.window(handle)
break
上述代碼中,current_handle是當前窗口的句柄,all_handles是所有窗口的句柄,handle是遍歷到的每個窗口的句柄。當找到新窗口的句柄時,使用switch_to.window()方法切換到該窗口。
需要注意的是,切換到新窗口后,需要使用switch_to.window()方法切換回原來的窗口。否則,在執行下一步操作時,會在新窗口中執行,導致測試用例執行失敗。
scss
Copy code
driver.switch_to.window(current_handle)
上述代碼可以切換回原來的窗口。