selenium webdriver處理frame比較簡單,這點比某些測試工具要先進一些,令人身心愉悅。
以下面的html代碼為例,我們看一下如何定位frame上的元素。
frame.html
<html>
<head>
<title>Frame</title>
<style>
#f_1 {width: 10em; height: 10em; border: 1px solid #ccc; }
#f_2 {display: none}
</style>
</head>
<body>
<p id = "p">Outside frame</p>
<iframe id = "f_1" src = "part1.htm"></iframe>
<iframe id = "f_2" src = "part2.htm"></iframe>
</body>
</html>
part1.htm
<html>
<head><title>Part1</title></head>
<body>
<p id = "f_p">This is part 1</p>
<input id = "btn" type = "button" value = "click me" onclick = "alert('hello')" />
</body>
</html>
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
PS:如果用的是Selenium::WebDriver.for :ie
會遇到

這樣的IE提示窗口,因此頁面上的元素不能被找到
可以這樣處理:
工具-Internet選項-高級-允許活動內容在我的計算機上的文件中運行 勾上 就OK了