selenium webdriver处理frame比较简单,这点比某些测试工具要先进一些,令人身心愉悦。
以下面的html代码为例,我们看一下如何定位frame上的元素。
frame.html
Frame Outside frame
part1.htm
Part1 This is part 1
switch_to方法会new1个TargetLocator对象,使用该对象的frame方法可以将当前识别的”主体”移动到需要定位的frame上去。
require 'selenium-webdriver'
dr = Selenium::WebDriver.for :chrome
frame_file = 'file:///'+File.expand_path(File.join(File.dirname(__FILE__),'frame.html'))
dr.navigate.to frame_file
#定位default content 上的p元素
dr.find_element(:id=>'p')
#将当前识别主体移动到id为f_1的frame上去
dr.switch_to.frame('f_1')
#点击frame上的button
button = dr.find_element(:id=>'btn')
button.click # -->a alert will popup
alert = dr.switch_to.alert
alert.accept
#此时再去定位frame外的p 元素将出现错误
dr.find_element(:id=>'p') #--> error
#将识别的主体切换出frame
dr.switch_to.default_content
dr.find_element(:id=>'p') #--> ok