selenium

在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口上进行操作。WebDriver提供了switch_to.window()方法,可以实现在不同的窗口之间切换。

以百度首页为例:

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")

#获得百度搜索窗口的句柄
search_windows = driver.current_window_handle

driver.find_element_by_link_text('登录').click()
driver.find_element_by_link_text('立即注册').click()

#获得当前所有打开窗口的句柄
all_handles = driver.window_handles

#进入注册窗口
for handle in all_handles:
    if handle != search_windows:
        driver.switch_to_window(handle)
        print('now register window!')
        driver.find_element_by_name('userName').send_keys('ZeiTe9834')
        driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_3__password']").send_keys('ZeiTe9834')
        time.sleep(5)
        
driver.quit()
  • current_window_handle:获得当前窗口句柄。
  • window_handles:返回所有窗口的句柄到当前会话。
  • switch_to.window():用于切换到相应的窗口,与上一节的switch_to.frame()类似,前者用于不同窗口的切换,后者用于不同表单之间的切换

参考资料:http://www.testclass.net/selenium_python/more-windows/

原文地址:https://www.cnblogs.com/studyddup0212/p/9030455.html