以前在使用watir 1.6x的時候,frame也是頗為棘手的一個問題。不但要照本宣科的進行一系列的設定,而且在進行實際代碼編寫的過程中會遇到各種奇奇怪怪的問題。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" f1" src = "part1.htm"></iframe>
<iframe id = "f_2" src = "part2.htm"></iframe>
</body>
</html>
part1.htm
<head><title>part1</title></head>
<p id = "f_p">this is part 1</p>
<input id = "btn" type = "button" value = "click me" onclick = "alert('hello')" />
require 'rubygems'
require 'selenium-webdriver'
dr = selenium::webdriver.for :firefox
frame_file = 'file:///'+file.expand_path(file.join(file.dirname(__file__), 'frame.html'))
dr.navigate.to frame_file
# 定位default content上的p元素
p dr.find_element(:id => 'p')
# 将目前識别主體移動到id為f_1的frame上去
dr.switch_to.frame('f_1')
# 點選frame上的button
dr.find_element(:id =>'btn').click # --> a alert will popup
# 此時再去定位frame外的p元素将出現錯誤
p dr.find_element(:id => 'p') # --> error
# 将識别的主體切換出frame
dr.switch_to.default_content
p dr.find_element(:id => 'p') # --> ok
webdriver的frame處理方式讓人感覺那個不痛越來越輕松,這點進步值得肯定。
下一節我們将介紹如何定位彈出的新視窗