Selenium-Webdriver(python)学习笔记(六)
----定位弹窗
1.定位弹窗
所谓"弹窗",并不是指前面的alert一类由js产生的对话框, 而是指打开一个新链接(target=”_blank”)时,产生的新的浏览器窗口.
这时需要用到的函数是switch_to_window
这个函数接受两种参数.一个就是窗口句柄(可以通过window_handles属性获得),另一个就是新打开窗口名称(即a标签中target属性的值,不能是_blank等关键字)
代码如下:
handle.py:
import os from time import sleep from distutils import log from selenium import webdriver dr = webdriver.Firefox() url = "file:///%s" % (os.path.abspath("main.html")) dr.get(url) # 点击链接,打开新窗口 l = dr.find_element_by_xpath("//body/a") l.click() old_handle = dr.current_window_handle for handle in dr.window_handles: if old_handle != handle: new_handle = handle break # 切换到新窗口中,点击新窗口中的按钮 dr.switch_to_window(new_handle) btn = dr.find_element_by_xpath('//input[@id="b1"]') btn.click() # 关闭alert alert = dr.switch_to_alert() alert.accept() sleep(3) dr.close() # 切回到原页面关闭 dr.switch_to_window(old_handle) dr.close()
name.py: (html中target属性为testName)
import os from time import sleep from distutils import log from selenium import webdriver dr = webdriver.Firefox() url = "file:///%s" % (os.path.abspath("main.html")) dr.get(url) # 点击链接,打开新窗口 l = dr.find_element_by_xpath("//body/a") l.click() old_handle = dr.current_window_handle for handle in dr.window_handles: if old_handle != handle: new_handle = handle break # 切换到新窗口中,点击新窗口中的按钮 dr.switch_to_window(new_handle) btn = dr.find_element_by_xpath('//input[@id="b1"]') btn.click() # 关闭alert alert = dr.switch_to_alert() alert.accept() sleep(3) dr.close() # 切回到原页面关闭 dr.switch_to_window(old_handle) dr.close()
需要注意的是,主动关闭窗口时,只会关闭当前句柄的窗口.