Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Alert in Selenium WebDriver (Selenium 2)

driver.findElement(By.xpath("//input[@value='添加']")).click(); 
//Pops out an Alert and program stops, does not continue 

how to click the alert?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

啊啊啊啊  怎么没有人呢? (TRANS: ahahahahaha why there is no one here to reply my post?)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我顶  (TRANS: Let me promote this post!)
like image 304
user640778 Avatar asked Mar 02 '11 08:03

user640778


People also ask

Which command is useful in handling Alert window in Selenium Webdriver?

Alert confirmBox = (Alert) driver. switchTo(). alert(); //Using dismiss() command to dismiss the confirm box.

What is Alert () in driver switchTo ()?

An alert can be of three types – a prompt which allows the user to input text, a normal alert and a confirmation alert. By default, the webdriver can only access the main page, once an alert comes up, the method switchTo(). alert() is used to shift the focus webdriver control to the alert.

How many types of alerts are there in Selenium?

Types of Alerts in Selenium There are mainly 3 types of Alerts, namely: Simple Alert. Prompt Alert. Confirmation Alert.

Which command is used to handle alerts?

The SwitchTo() command is used to 'get alert box in selenium'.


2 Answers

As of the latest selenium 2 release, this can be done (at least using the FirefoxDriver):

    driver.switchTo().alert().accept();
like image 51
Lucas Avatar answered Dec 08 '22 00:12

Lucas


In Selenium 2, currently alerts are only handled in the Firefox browser. You don't specify what language you're using for your tests, but here's how to handle an alert using ruby. (This is taken from the Ruby Bindings page on the selenium wiki).

Javascript Alert/Confirm

You can use webdriver to handle javascript alert and confirm dialogs. The implementation for both is the same.

Note: At this time the API is only available in Firefox (or in Firefox using the remote server), and only alert/confirms that are generated post load can be captured.

require "selenium-webdriver"

driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://mysite.com/page_with_alert.html"

driver.find_element(:name, 'element_with_alert_javascript').click
a = driver.switch_to.alert
if a.text == 'A value you are looking for'
  a.dismiss
else
  a.accept
end
like image 35
Andy Tinkham Avatar answered Dec 08 '22 01:12

Andy Tinkham