天天看點

Selenium webdriver系列教程(7)—如何處理alert和confirm

 以前使用watir 1.6x 的時候處理頁面javascript彈出的alert和confrim視窗時必須借助autoit工具來輔助執行,就像中國男足職業聯賽中高價聘請外援一般。

  下面的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方法。   

最新内容請見作者的github頁:http://qaseven.github.io/

繼續閱讀