Click a Button in Selenium WebDriver and Carry out Other Validations

A button is usually used to submit a for or trigger a function on a click event of it.  In this article, I am going to show you how to click a button or submit a form in Selenium WebDriver.We will also see the way to get the background color of the button in Selenium and carry out different other validations like whether the button is Enabled and is Displayed on the page and many more.

We will consider the following DOM structure for the examples.click a button in Selenium WebDriver

Click a Button in Selenium WebDriver

Click a Button In Selenium WebDriver By ID

We can click a button by simply using the click() method in Selenium Webdriver using the following code snippet example.

Submit a Button In Selenium WebDriver

We can click a button by using the submit() method in Selenium Webdriver using the following code snippet if the button is used to submit the page.

Click a Button Using CSS Selector ID attribute

The following example shows how to click a button using the CSS Selector ID attribute. To more about CSS Selector locator please refer to my post How to Use CSS Selector in Selenium WebDriver | 13 Examples.

Click a Button Using XPath In Selenium WebDriver

The following Selenium code clicks the Submit button using the XPath by its ID property. To know more about XPath please refer to my post XPath in Selenium WebDriver with Examples.

How to check whether a Button is Visible and Enabled on the Page in Selenium?

Whenever you are going to perform any action on a web element it is standard practice to first check whether it is visible on the page. If it is visible the next thing we should check whether it is enabled or not. The following example illustrates how to do it. Here we will first check whether Submit Button is visible on the page using isDisplayed() method. If it is visible we will check whether it is in the enabled state using the isEnabled() method. If it is enabled we will click on it.

How to Get Background Color of Button in Selenium WebDriver?

The getCssValue method is quite helpful to get the background color of any web element. Consider the following HTML Tag. We can use the following Selenium Code to get the background color of the Submit Button. To know more about getting the color of the element itself please refer to my post 23 Most Useful Selenium WebDriver Commands That You Must know.

Conclusion

  • We can click on a button in Selenium Webdriver using click and Submit method
  • We can locate the button elements by id, name, CSS, and XPath selector.
  • We can perform validation operations like isDisplayed(), and isEnabled() before clicking on a button to get rid of runtime exceptions thrown by Selenium WebDriver.

Recommended Posts

Leave a Reply