在使用selenium進(jìn)行web自動化測試時,經(jīng)常需要切換到新窗口來操作。切換到新窗口可以使用以下步驟:
獲取當(dāng)前窗口的句柄:
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是當(dāng)前窗口的句柄,all_handles是所有窗口的句柄,handle是遍歷到的每個窗口的句柄。當(dāng)找到新窗口的句柄時,使用switch_to.window()方法切換到該窗口。
需要注意的是,切換到新窗口后,需要使用switch_to.window()方法切換回原來的窗口。否則,在執(zhí)行下一步操作時,會在新窗口中執(zhí)行,導(dǎo)致測試用例執(zhí)行失敗。
scss
Copy code
driver.switch_to.window(current_handle)
上述代碼可以切換回原來的窗口。