Monday, 17 March 2014

How to handle alerts in selenium webdriver in C#.Net?

We can handle the alerts very easily in selenium webdriver in C# using SwitchTo() method.

we can click on Ok button using below syntax.
alert.Accept();

we can click on Cancel button using below syntax.
alert.Dismiss();

To get the text displayed in the alert, you can use Text property

String text = alert.Text;


//Sample C#  program to handle alert in selenium webdriver

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;

namespace Abc
{
    class Program
    {
        static void Main(string[] args)
        {

           
IWebDriver driver=null;
try
{

   driver = new ChromeDriver(@"F:\selenium\csharp");
   driver.Url = "http://www.google.co.in";

   driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));

   driver.Navigate();

   driver.FindElement(By.Id("link")).Click();
   //click on ok button of alert
    driver.SwitchTo().Alert().Accept();
} catch(Exception e){ Console.WriteLine("Exception ******"+e.ToString()); } finally{ Thread.Sleep(2000); driver.Quit(); Console.ReadLine(); } } } }




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors