selenium
  1. selenium-handling-checkboxes

Handling Checkboxes

Description

Checkboxes are an important feature of web forms that allow users to make multiple selections from a list of options. In web testing automation, checkboxes should be checked or unchecked by using the Selenium WebDriver.

Syntax

webdriver.ActionChains(driver).click(element).perform()

Example

Suppose you want to check the checkbox of Yelp for Business Owners' "Create an Ad" option, which is on a web page containing a list of checkboxes and its code is:

<input type="checkbox" id="checkbox-business" name="checkbox-business" value="1" checked="">

To uncheck this checkbox, use the following Python code:

elem = driver.find_element_by_xpath("//input[@id='checkbox-business']")
webdriver.ActionChains(driver).click(elem).perform()

Output

The output of the above script will be that the checkbox of "Create an Ad" option will be unchecked.

Explanation

The 'find_element_by_xpath' function is used to find the element from the web page with the given XPath, which is the address of the element present on the page. Once the element is found, an instance of the ActionChains class is created to perform various mouse or keyboard interactions. After that, a click on the element is performed using the 'click' method of the ActionChains instance. Finally, the 'perform' method is called to execute all the actions at once.

Use

This method is useful when there is a need to test webpages containing multiple checkboxes.

Important points

  • The 'click' method from 'ActionChains' class enables to click on any web element, like a checkbox.
  • The 'find_element_by_xpath' method locates the web element using the Xpath address.
  • The 'perform' method executes all actions stored in the ActionChains container.

Summary

In this tutorial, we learned how to handle checkboxes of a webpage using the Selenium WebDriver. We covered the syntax, example, output, explanation, use, and important points of the code snippet used to handle checkboxes. The code snippet is essential for testing webpages that have multiple checkboxes with various options on a single webpage.

Published on: