How to handle Button in Selenium Webdriver

asked 3 months ago

There are different operations we can perform on the button using a Selenium web driver.

The operations are:

   > To click
   > Get the color of the button
   > To check whether the button is clickable or not

Navigate to https://www.qafeast.com/demo,click the button tab.

Press F12 on the keyboard and inspect the button.

 

 

To click the button:

To click the button or any control on the webpage click() method is used. 

Syntax:

driver.findElement(By.("")).click();

 

Example:

driver.findElement(By.id("button-1")).click();

 

To get the color of the button:

To get the color of the button we can use getCssValue() function

Syntax

driver.findElement(By.("locator value ")).getCssValue("background-color");

 

Example

String buttonColor = driver.findElement(By.id("button-1")).getCssValue("background-color");
String buttonTextColor =driver.findElement(By.id("button-1")).getCssValue("color");
System.out.println(buttonColor);
System.out.println(buttonTextColor);

 

To verify whether the button is clickable or not

To check whether the button is clickable or not , isEnabled() function is used. The isEnabled() function returns a boolean value, based on the boolean value we can determine whether it is clickable or not.

Syntax:

driver.findElement(By. (" ")).isEnabled();

 

Example:

WebElement Button = driver.findElement(By.id("button-2"));
if(Button.isEnabled()){
  System.out.println("Button is enabled");
}
else {
  System.out.println("Button is not enabled");
}

 

In Selenium Csharp

 

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace ConsoleApp1
{
    internal class SeleniumTest
    {
        static IWebDriver driver;
        static void Main(string[] args)
        {
           
            driver = new ChromeDriver(@"\\Driver\\chromedriver.exe");
            driver.Navigate().GoToUrl("https://qafeast.com/demo");
            driver.FindElement(By.XPath("//label[text()='Button']")).Click();
           //To click the Button 
            driver.FindElement(By.Id("button-1")).Click();
           //To verify whether the button is clickable or not
            IWebElement ele = driver.FindElement(By.Id("button-1"));
            if (ele.Enabled)
            {
                Console.WriteLine("button is enabled");
            }
            else
            {
               Console.Write("buttont is not enabled");
            }
            //To get the color of the button:
            IWebElement typedText = driver.FindElement(By.Id("button-1"));
            Console.WriteLine(typedText.GetCssValue("background-color"));
            Console.WriteLine(typedText.GetCssValue("color"));
            driver.Quit();  
        }
    }
}