以前使用watir 1.6x 的時候處理頁面javascript彈出的alert和confrim窗口時必須借助autoit工具來輔助執行,就像中國男足職業聯賽中高價聘請外援一般。
在selenium webdriver中,confirm和alert的處理再也不需要借助任何第三方工具了。
下面的html頁面上有1個名為click的button,點擊該button后就會彈出1個alert窗口。
<html> <head> <title>Alert</title> </head> <body> <input id = "btn" value = "click" type = "button" onclick = "alert('hello');"/> </body> </html> |
selenium webdriver處理alert的代碼如下:
require 'rubygems' require 'selenium-webdriver' dr = Selenium::WebDriver.for :firefox frame_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'alert.html')) dr.navigate.to frame_file dr.find_element(:id =>'btn').click a = dr.switch_to.alert puts a.text #--> hello a.accept |
上面代碼的思路是先點擊id為btn的按鈕,然后a = dr.switch_to.alert返回了1個alert element(暫時如此理解好了)并賦值給變量a。這樣a就代表了alert,使用puts a.text語句可以輸出alert的內容,這里會打印出'hello'。 a.accept表示點擊確認,當彈出窗口為confrim時,a.accept也表示確認,如果需要取消的話,那么則可以使用a.dismiss方法。
相關文章
Selenium webdriver系列教程(6)—如何捕獲彈出窗口