Selenium Python Tutorial: Guide With Examples

Himanshu Sheth

Posted On: December 11, 2024

view count242069 Views

Read time29 Min Read

Python is a programming language that needs no introduction! It is one of the most preferred languages when it comes to projects involving Machine Learning (ML), Artificial Intelligence (AI), and more. On a different battleground, the combination of Selenium Python is the preferred choice for web automation.

Selenium with Python can be harnessed to automate browser testing of websites and web applications. It enables seamless automation of test scenarios that include interactions like button clicks, mouse interactions, filling forms, and comprehensive site navigation.

In this tutorial, we deep dive into the essential aspects of Selenium and Python, the learnings of which will be primarily instrumental in your web automation journey.

What Are Selenium Python Bindings?

Python Selenium bindings provide APIs using which you can write functional tests using the Selenium WebDriver. Like other Selenium language bindings, Selenium Python APIs can be leveraged to develop highly efficient tests that let you interact with the WebElements on the Application Under Test (AUT).

Selenium bindings for all Selenium-supported languages (e.g., Java, JavaScript, C#, etc.) provide similar functionality and follow the same core WebDriver API. The bindings support local browser drivers (e.g., Chrome, Firefox, Edge, etc.) and provide a remote WebDriver that lets you connect to a remote cloud Selenium Grid.

While syntax and library support may vary between languages, elements such as browser compatibility, WebElement locators in Selenium, and wait mechanisms remain consistent. The Selenium WebDriver architecture shows how the Selenium client libraries (or Selenium bindings) interact with the web browser through its corresponding browser driver.

Configuring Selenium and Python

It goes without saying that the prerequisite for Selenium installation is Python. So, before proceeding with the further steps, make sure to install Python on your machine. At the time of writing this tutorial, the latest stable version of Python is 3.13.0.

For demonstration, we are using Python 3.12.0 version.

Step 1: Install Python

In case you are using macOS, simply trigger the command python –version to check the version of Python installed on your machine. You can find all the stable releases of Python on the Python official website. The installation and upgradation steps might differ in case you are using Windows or Linux operating systems.

Step 2: Install pip

For installing Selenium (or any other Python library), you need to have the pip package-management system installed on the machine. First, download the script get-pip.py from the Python website.

Next up, invoke the command python get-pip.py (or python3 get-pip.py) for installing pip.

To check the installation status, run the command pip –version on the terminal. At the time of writing this tutorial, the latest version of pip is 24.3.1. In this tutorial, we will use the 24.1.2 version of pip.

Step 3: Install Selenium (optional for execution on cloud grid)

For installing Selenium, run the pip3 install selenium command on the terminal. Then, run the pip show selenium command on the terminal to check the version of Selenium installed in the machine.

In case you already have Selenium on your machine, you can trigger the command pip3 install –upgrade selenium for upgrading Selenium. At the time of writing this tutorial, the latest version of Selenium is 4.27.0. In this tutorial, we will use the 4.22.0 version of Selenium.

It is important to note that the Selenium installation step is optional if you are running tests on an online Selenium Grid like LambdaTest, as all the dependencies will be taken care of by the cloud provider! In our Selenium Python demonstration, we would be executing tests on the local grid and the LambdaTest cloud grid.

Looking to get started? Check out this documentation on Selenium testing with Python on LambdaTest.

Info Note

Run Selenium Python tests across 3000+ real browsers. Try LambdaTest Today!

Step 4: Install pytest Framework

In this tutorial, we will be using the pytest, a more popular framework. Invoke the command pip3 install pytest to install the latest version of pytest.

Now, run the command pip3 show pytest to check the pytest version installed on the machine.

At the time of writing this tutorial, the latest version of pytest is 8.3.4. In this tutorial, we will use the 8.2.2 version of pytest.

Step 5: Install Browser Drivers (optional step)

In case you are performing Selenium Python testing on the local machine, you need to have the respective browser driver before proceeding with the tests. The browser driver must be in line with the browser & browser version.

Shown below are the locations from where you can download the corresponding browser drivers:

Browser Browser Driver (Download Location)
Google Chrome http://chromedriver.chromium.org/downloads
Mozilla Firefox https://github.com/mozilla/geckodriver/releases
Microsoft Edge https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Opera https://github.com/operasoftware/operachromiumdriver/releases
Internet Explorer https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver

If you are using Selenium v4.6.0 & above, you can do away with the tedious task of browser driver installation! Selenium Manager, introduced in v4.6.0, handles the prime responsibility of management of browser drivers under the hood.

It automatically downloads and installs the browser driver (if not present on the machine) that matches the respective browser (and its version).

Now that the environment is all set up, let’s get our hands dirty by running Selenium Python tests on local and cloud Selenium grids.

gituhb

Running Automated Tests With Selenium Python

For demonstration, we have created a simple project where automated testing is performed using Selenium and pytest. For better maintainability, we have used pytest fixtures that handle setup and teardown actions (or functions).

Setting Up Project

It is recommended to use a virtual environment (venv) since it helps in better management of dependencies and environments.

Run the commands virtualenv venv and source venv/bin/activate on the terminal to create the virtual environment. All the dependencies (or Python packages), like pytest, selenium, etc., required for project execution are available in the requirements.txt file.

The dependencies can be installed by triggering pip3 install -r requirements.txt on the terminal. Selenium v4.6.0 (or above) is installed as a part of the installation procedure.

For improved maintenance and code reusability, the required Selenium locators are placed in the pageobject/locators.py file. The next step to making this more modular would be incorporating the best practices of the Page Object Model in Selenium in this project.

Helper (or wrapper) functions are available in the pageobject/helpers.py file. We are not deep-diving into those functions since the implementation is self-explanatory.

We could have done away with fixtures and made the project super simplified, but it will be usable in a real-project environment! The conftest.py file is a special configuration file that is usually used for defining fixtures, hooks, and other configuration options that would be shared across tests.

A fixture of function scope is defined for instantiating the browser on which automation tests will be performed using Selenium and Python. The environment variable EXEC_PLATFORM, when set to the cloud, instantiates a remote Chrome browser on the LambdaTest Selenium Grid.

The browser capabilities are set using the LambdaTest Automation Capabilities Generator. Since the tests are executed on a non-headless Chrome browser, the headless capability is set to False.

For execution on the LambdaTest cloud grid, an instance of Remote WebDriver is started using the Remote method of the webdriver class. The method takes two parameters:

  • LambdaTest grid URL appended with LambdaTest Username and Access Key.
  • Browser options (earlier referred to as Desired Capabilities).

LambdaTest credentials can be procured from your LambdaTest Account Settings page. The yield browser provides the browser instance to the test function (or method) that uses the said fixture.

The environment variable EXEC_PLATFORM is set to local for executing Python tests with Selenium on the local machine. As seen below, an instance of Chrome browser is instantiated for the tests.

The tests demonstrated in the further sections work seamlessly on the LambdaTest cloud grid as well as the Selenium setup locally. Since cloud testing offers numerous benefits in terms of scalability, reliability, and more, all the tests are executed on the LambdaTest grid.

Writing First Selenium Script in Selenium Python

The first step is to set up the infrastructure (i.e., local Selenium Grid setup or cloud grid on LambdaTest). All of this is already covered in the earlier section. Depending on the tests, appropriate web locators need to be identified and used with the best-suited methods of Selenium Python.

Test Scenario:

  1. Navigate to LambdaTest Selenium Playground.
  2. Locate the Input Form Submit Link on the page.
  3. Input the required information on the page.
  4. Submit details, assert if the information is not submitted successfully.

Implementation: The test script for the above mentioned test scenario is shown below:

Filename: 1_simple_selenium_test.py

Code Walkthrough:

Once all the libraries are imported, we first read the value of the environment variable EXEC_PLATFORM. As mentioned earlier, the variable is set to cloud for all the tests demonstrated in this tutorial.

The @pytest.mark.usefixtures decorator is used to specify that the driver fixture must be set up before the test execution and torn after the test execution (i.e., the tearDown process).

The driver.get() method is used for navigating to the URL under test.

An explicit wait in Selenium of 5 seconds is created by invoking the WebDriverWait() method. Though delving into waits in the first Selenium script is not recommended, it is still a good way to handle interactions with elements on dynamic pages. The method takes two parameters – WebDriver instance and timeout in seconds.

Next, we locate the Input Form Submit element using the XPath locator in Selenium. Instead of the Inspect Tools, we have used the POM Builder add-on since it provides the locator of any WebElement with ease!

Once the required element is located the click() method is invoked for clicking on the element. You can also automate mouse clicks in Selenium via ActionChains. We will cover the same in further sections of the tutorial.

Like the earlier step, the password element is located using XPath and the company element is located via the CSS Selector in Selenium.

Since there is only a single element with the specified locator, the findElement() method in Selenium is invoked for locating the specified element. As seen below, the send_keys() method of the WebElement class helps in sending text input in the located element.

Since dropdowns are widely used in websites, automating interactions with dropdowns using Selenium is something that might be frequently used in test scripts. The Select class which is a part of the selenium.webdriver.support.ui module provides methods for handling dropdowns with Selenium.

An object (i.e., country_dropdown) of the Select class is created with the input parameter set to the dropdown element that is located using the XPath property.

The select_by_visible_text() method of the Select class helps in selecting the item whose visible text matches the given string (i.e., United States). We will deep dive into handling dropdowns in further sections of this tutorial.

Once all the entries are populated in the form, the Submit button is located using the CSS Selector property. A button click is performed to simulate a mouse click on the located clickable element.

Once the entered information is submitted in the earlier step, we wait till the success message string (which was earlier hidden) is visible on the page. ExpectedConditions in Selenium help in waiting for a condition to be met. In this particular case, an explicit wait is performed till the success message is not present on the page.

An assert is raised if the resultant success string is not present on the page. The lambda-status variable is marked as failed in case of failure in the test execution.

Test Execution:

Run the below-given command in the terminal to trigger the execution of the first Selenium test.

Shown below is the execution status on the LambdaTest Web Automation dashboard. The status is marked as Passed, which means that the execution was successful.

make simple_selenium_test

Locating WebElements in Selenium Python

When it comes to front-end testing, one of the first things that needs to be done is locating the required WebElement using the appropriate web locators. We already used XPath and CSS Selector in the earlier section. ID, Name, Link Text, Partial Link Text, and Class Name are some of the other popular locators in Selenium.

You can also find elements by text in Selenium using the find_element() method in conjunction with the appropriate Selenium web locator. The find_elements() method in Selenium is used when multiple elements that match certain criteria need to be located on the page. It returns a list of WebElements matching the criteria.

Here is a short gist of the popular web locators that can be used in Selenium Python:

Locator Example
XPath driver.find_element(driver, By.XPATH, xpath-expression)
CSS Selector driver.find_element(driver, By.CSS_SELECTOR, css-selector expression)
ID driver.find_element(driver, By.ID, id-expression)
Name driver.find_element(driver, By.NAME, name)
Class Name driver.find_element(driver, By.CLASS_NAME, class-name)
Tag Name driver.find_element(driver, By.TAG_NAME, tag-name)
Link Text driver.find_element(driver, By.LINK_TEXT, link-text)
Partial Link Text driver.find_element(driver, By.PARTIAL_LINK_TEXT, partial-link)

Here is the syntax of find_element() and find_elements() methods when used with Selenium locators:

  • web_element = driver.find_element(by, locator)
  • web_element_list = driver.find_elements(by, locator)

It is a good practice to prioritize ID and Name locators over XPath since they are considered to be faster in comparison to the XPath selector.

Let’s get our hands dirty with web locators by locating elements with appropriate locators on LambdaTest Selenium Playground and LambdaTest eCommerce Playground.

Implementation: The test script for the above-mentioned test scenario is named as 4_locating_web_elements.py.

Locating WebElement Using XPath

The Input Form Submit is first located using the XPath locator. Like earlier, we have used POM Builder in cases where it eases the job of finding the best-suited locators on the page.

Once the required element is located, the click() method is invoked for clicking on the element.

Locating WebElement Using CSS Selector

The text box with the label Name is located using the CSS Selector. As POM Builder provides the CSS Selector, we used it instead of the Inspect Tools of the browser.

The send_keys() method sends the text to the located element. If an element has both XPath and CSS Selector, you should pick CSS Selector over XPath due to the speed benefits offered by the said selector.

Locating WebElement Using ID Selector

In case an element has the id (or ID) attribute, you can use the ID locator to locate the element. Alternatively, you can also execute the document.getElementById(“inputEmail4”) function for retrieving the HTML element with id attribute inputEmail4 from the Document Object Model (DOM) of the document.

Locating WebElement Using Name Selector

Like the ID selector, you can opt for the Name selector (or locator) if the WebElement has a name attribute.

You can also run the command document.getElementsByName(“company”) on the browser’s console to verify the presence of the element. The command returns a NodeList of the elements matching the specific name attribute.

Locating WebElement Using Class Name Selector

First, we navigate to the LambdaTest eCommerce Playground test website using the driver.get() method. The Class Name locator should be used if the element(s) has the class attribute.

The JS function document.getElementsByClassName(“module-mz_product_listing”), when executed on the console, returns a Node List of 5 elements.

The find_elements() method, when used with the CLASS_NAME locator and specified element, returns a list of elements matching that locator.

Finally, we print the size of the list returned in the earlier step.

Locating WebElement Using Tag Name Selector

The tagName attribute in HTML refers to the name of an HTML element. As you might be aware, the tag name is enclosed in angle brackets (i.e. < and >). <div>, <p>, <a>, <input>, <h1>, etc. are some of the popular tag names.

We locate the elements matching the h4 Tag Name. Close to 96 elements match the tag name. Since every element has a tagName attribute, the TAG_NAME selector should be used if the required element cannot be located using other selectors.

Once the elements are located using the find_elements() method, a for loop is executed to get the text of the element in Selenium.

Locating WebElement Using Link Text Selector

As the name suggests, the link text selector is used to find hyperlinks (<a> tags) based on the text content.

After navigating to the URL under test, the find_elements() method is invoked with By set LINK_TEXT. Once the element is located, a click() operation is performed to navigate to the link set under the href within the <a> tag.

Locating WebElement Using Partial Link Text Selector

Locating element(s) with PARTIAL_LINK_TEXT selector is somewhat similar to locating with LINK_TEXT locator. The only difference is that the hyperlinks (<a> tags) are located based on a substring of the visible text.

The PARTIAL_LINK_TEXT selector can be opted in place of LINK_TEXT in scenarios where part of the link text is known, and you need to find the hyperlink that contains that partial text.

In this example, the test URL is first set to ​​LambdaTest Selenium Playground. Next, the link (or element) with partial text Download is located with the find_elements() method and PARTIAL_LINK_TEXT selector.

Since there are 4 links with partial link text Download, a for loop is run on each link, and the link set under the href attribute is read using the get attribute method.

Since a list of WebElements is returned by the get_elements() method, the click operation is simulated on the second link by invoking the click() method on the said WebElement.

Test Execution:

Run the below-given command on the terminal to trigger the execution of the test:

Shown below is the execution status on the LambdaTest Web Automation dashboard. The status is marked as Passed, which means that the execution was successful.

make locating_elements_test

Handling Keyboard Events in Selenium Python

Automating interactions with elements like buttons, input boxes, etc., is essential since every website uses these controls to a large extent. For instance, the Input Form Demo page on the LambdaTest Selenium Playground website has a number of text boxes and buttons on the page.

The send_keys() method in Selenium Python helps simulate keyboard interactions. The Keys class from selenium.webdriver.common.keys provides constants for all the special keys, i.e., ENTER, DELETE, BACKSPACE, TAB, and more.

ActionChains in Selenium Python can be leveraged to automate complex interactions like mouse clicks, keyboard commands like Select All, context menu clicks, and more. In this section of the tutorial, we will be majorly focusing on handling keyboard actions in Selenium using the methods provided by the ActionChains class.

We would also recommend having a top-level look at the implementation of the action_chains.py file since it will be helpful when using those methods for automation tests!

Test Scenario 1 (Demonstration of SendKeys):

.

  • Navigate to the Account Login page of LambdaTest eCommerce Playground.
  • Enter the valid E-Mail Address and Password.
  • Assert if the login is not successful.

Test Scenario 2 (Demonstration of ActionChains):

  • Navigate to the LambdaTest eCommerce Playground.
  • Locate the Search Box.
  • Search for “IPod Nano”.
  • Assert if the search results do not show up on the page.

Implementation: Test scripts for the above-mentioned test scenario are named as 2_keyboard_interactions.py.

Code Walkthrough (Test Scenario 1):

After navigating to the Login page of LambdaTest eCommerce Playground, locate the E-Mail Address input box using the CSS Selector.

Once the element is located, the send_keys() method is invoked to enter the username in the located text box. Akin to the Thread.sleep() method, the time.sleep() method is invoked for realizing a blocking sleep of 4 seconds.

The clear() method is called only for demonstration purposes. It clears the text in the located element. The login email is entered again in the element located in the earlier step. On similar lines, the password is entered in the Password box that is located using the XPath locator.

The click() method is invoked for simulating click on the Login button that is located via CSS Selector. The page title of the newly opened page is obtained using the driver.title property.

Code Walkthrough (Test Scenario 2):

Since we need to perform complex user interactions, we first create an object (i.e., action) of the ActionChains class.

After the search box is located, the next step would be to enter the search term IPod Nano in the box. The first chain in the action is to type the term IPod in the box. For this, we simulate a series of keyboard events (e.g., pressing the Shift key and typing i – this types I). The same process is repeated for typing other letters in the word.

Since we also want to type the term Nano (after IPod), a leading space is added after the word by sending a SPACE key via the .send_keys(Keys.SPACE) action. Please note that we have created this complex action chain only for demonstration purposes, else we could have entered IPod Nano with just a few actions.

Unlike the earlier step, we have created a simple action that appends sending the text Nano to the earlier action. Keys.ENTER is added to the action for triggering the Search operation.

Now that we have all the chains in place, it’s time to execute all the actions that are queued up in the action object. The execution of the chain is performed by invoking the perform() method of the ActionChains class.

Like before, an assertion is raised if the page title does not match with the resultant page title.

Test Execution:

Run the below-given command on the terminal to trigger the execution of the test:

As seen in the LambdaTest execution snapshot, the IPod Nano search page opens up successfully.

make keyboard_interactions_test

Handling Mouse Actions in Selenium Python

Like keyboard interactions, Selenium also provides methods for simulating different mouse actions such as hover, context clicks, clicks, drag and drop, moving to element, and more. The methods are again a part of the ActionChains class.

One of the major Selenium 3 vs Selenium 4 differences is the implementation of new methods that ease mouse actions like drag and drop, back click, forward click, and more.

In this section of the tutorial, we will learn handling mouse actions in Selenium.

Test Scenario 1 (Drag and Drop Element):

  1. Navigate to the Drag and Drop Demo page.
  2. Locate the draggable elements.
  3. Drop the elements in the droppable frame.

Test Scenario 2 (Move to Element):

  1. Navigate to the LambdaTest eCommerce Playground.
  2. Locate the element with Partial Link Text AddOns.
  3. Locate the menu item with Partial Link Text Designs.
  4. Move to the element located in Step (3) and click on it.
  5. Assert if the title of the newly opened page does not match the expected one.

Implementation: The test script for the above-mentioned test scenario is named as 10_mouse_interactions.py.

Code Walkthrough (Test Scenario 1):

First up, we create an object of the ActionChains class. Since the Drag and Drop Demo page contains two draggable items and one droppable item, locate all of them using the find_element() method with the XPath locator.

Using drag and drop in Selenium Python, drag the first draggable item inside the droppable element. The drag_and_drop() method of the ActionChains class takes two input parameters – source WebElement and target WebElement. The perform() action is added to execute the actions.

The earlier step is also performed for the draggable 2 WebElement. Now that both the items are dragged and dropped, locate the items inside the Droppable frame. It is located using the ID locator and find_element() method in Selenium.

Items in the recently searched element are located using the TAG_NAME locator. We have used the tag in this example. An assert is raised if the text of the located elements inside Droppable does not match with Draggable 1 and Draggable 2.

Code Walkthrough (Test Scenario 2):

After navigating to LambdaTest eCommerce Playground, locate the element with Partial Link Text – AddOns.

Invoke the move_to_element() method of the ActionChains class for moving the cursor to the middle of the located element. Perform the required action with the perform() method.

With a focus on the element located in the previous step, locate the menu item within the element using the find_element() method and PARTIAL_LINK_TEXT locator (i.e., Designs).

Perform the action that combines moving to the element and clicking on it. An explicit wait is performed until the presence of the element located with CSS Selector ([data-id=’214968′] > .mb-4) is detected in the DOM. The test is marked as failed if the resultant string Accord is not present on the page.

Test Execution:

Run the below-given command on the terminal to trigger the execution of the tests. Since there are two tests in the suite, both tests are executed in parallel via the pytest-xdist plugin.

make mouse_interactions_test

Parallel execution in pytest is one of the ideal ways for reducing the test execution time and making the most out of the capabilities offered by cloud Selenium Grid like LambdaTest.

Handling Windows and Tabs in Selenium Python

When automating front-end tests, there could be cases where you need to open up multiple tabs or windows. Consider a scenario where you are running tests on multiple test URLs, and each URL can be opened in a new tab/window depending on the test requirement.

Handling multiple windows in Selenium is useful for tasks such as verifying content across multiple windows or tabs, tackling pop windows, and more.

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground.
  2. Open a new tab and navigate to the Login page of the LambdaTest eCommerce Playground.
  3. Close the respective windows.

Implementation: Test scripts for the above-mentioned test scenario are named as 3_switch_tabs_test.py

Code Walkthrough:

Navigate to the LambdaTest eCommerce Playground. Once the page is rendered, get the current window handle. The driver.window_handles list contains handles for the current window and any new tab/window. It can be used for switching between opened windows/tabs.

Hence, driver.window_handles[0] is the window handle of the parent window. Create a new tab by invoking the new_window() method that was newly introduced in Selenium 4. The new_window() method takes a single parameter of String format:

  • tab – Opens a new browser tab and switches the focus to it.
  • window – Opens a new browser window and switches focus to it.

Navigate to LambdaTest eCommerce Playground (Login page) in the newly opened tab. It is important to note that the focus automatically switches to the new tab. Since this is a second window, the driver.window_handles[1] provides its handle. Since the new tab is the active window, driver.close() closes only the said tab (and not the other windows).

For testing, we switch to the parent window by providing the parent window handle to the switch_to() method of WebDriver. The close() method of WebDriver closes the currently active window (i.e. only the parent window).

Test Execution:

Run the below-given command on the terminal to trigger the execution of the tests.

As shown below, the window handles are printed on the terminal and test execution is also successful.

make switch_tabs_test

Handling Dropdowns in Selenium Python

Like radio buttons and checkboxes, dropdown elements are also popularly used on a wide range of websites. Methods that are a part of the Select class from the selenium.webdriver.support.ui module in Selenium can be used for automating interactions with dropdown elements in the document.

Selenium also offers a wide range of methods for handling dropdowns in Selenium. Option in a dropdown can be chosen through different methods:

Method Description
select_by_visible_text Select an option in the dropdown by its visible text
select_by_index Select an option in the dropdown by its index that starts from 0
select_by_value Select an option in the dropdown by the value attribute

Test Scenario (Single-select and multi-select):

  1. Navigate to the Dropdown Demo page.
  2. Select an element(s) using the properties supported by the Select class.
  3. Assert if there is any error.

Implementation: Test scripts for the above-mentioned test scenario are named as 5_handling_dropdowns.py.

Code Walkthrough:

After navigating to the test URL, locate the single select dropdown using the find_element() method and CSS Selector.

Create an object of the Select class that provides the methods for automating interactions with the dropdown element. Use the select_by_visible_text method of the Select class with a parameter whose visible text is Monday.

Print the text property of the selected option on the console. Index in a dropdown starts from 0. Here, we select the 5th option in the dropdown element. A NoSuchElementException in Selenium is raised if a wrong (or non-existent) index is supplied to the select_by_index() method.

Next up, we select an option in the dropdown menu where the value attribute of the <option> tag is Friday. As a first step, we first locate the multi-select dropdown with the ID locator (i.e., multi-select).

After creating an object of the Select class, we use the select_by_visible_text() method for selecting the options – Florida, Ohio, and Texas from the dropdown. For multi-select dropdowns, the Select class in Selenium provides the all_selected_options() method that returns a list of all selected options belonging to the provided select tag.

We created a helper print_select_element() method that prints the selected items. As seen below, we print the text property of all the options that are selected in the dropdown. Next, we repeat the same process for selecting multiple options using the select_by_index() and select_by_value() methods of the Select class.

Test Execution:

Run the below-given command on the terminal to trigger the execution of the tests.

make handling_dropdown_test

Handling Radio Buttons in Selenium Python

Radio buttons are another commonly used element on a web page. They are used in profile creation forms or any other type of form where only one option can be selected from a group. Handling radio buttons in Selenium involves locating the respective button and simulating a click action on it.

Before selecting any option, it is necessary to check if the particular radio button is enabled or not. The is_selected() method is used for checking the currently selected option.

Test Scenario 1:

  1. Navigate to the Radio button Demo page.
  2. Locate the desired radio button.
  3. Click on it (if it is enabled).

Test Scenario 2:

  1. Navigate to the Radio Button by ID page.
  2. Toggle the visibility of the hidden option.
  3. Locate the (earlier hidden) radio button and click on it.

Implementation: Test scripts for the above-mentioned test scenario are named as 6_handling_radio_buttons.py

Code Walkthrough (Test Scenario 1):

Locate the radio button on the Radio Button Demo Page using the NAME selector and find_elements() method.

The earlier step returns a list of two radio buttons with the name optradio. Check if the second radio button (i.e., elem_radio[1]) is enabled or not. If enabled, select the radio button by invoking the click() method on the element.

Locate the Get Value button with the CSS_SELECTOR property. Once located, click on the button to read the radio button value. Get the text attribute of the located label element. Mark the test as passed if Female is present in the resultant string.

Code Walkthrough (Test Scenario 2):

Once you navigate the URL under test, create an object of WebDriverWait with an explicit wait duration of 10 seconds. Execute JavaScript in Selenium Python via the execute_script() method to wait till the document (or page under test) load is complete. In that case, the document.readyState property equates to complete.

Locate the Toggle Hidden Option with the ID property and simulate a click action. Now the hidden radio button is visible, locate the radio button with the ID property provided by the find_element() method. Finally, click on the radio button to select it!

Test Execution:

Run the command on the terminal to trigger the execution of the tests.

make handling_radio_buttons_test

Handling Checkboxes in Selenium Python

Handling checkboxes using Selenium on a web page can be done by locating it and then clicking on it. As usual, the click() method in Selenium is used for toggling the checkbox.

The is_selected() method of the WebElement class helps in checking the current state of the checkbox (i.e. checked or unchecked).

Test Scenario:

  1. Navigate to the Checkbox Demo page.
  2. Select the desired checkboxes only if they are enabled.
  3. Raise an assert in case of failure.

Implementation: Test scripts for the above-mentioned test scenario are named
as 7_handling_check_boxes.py

Code Walkthrough:

After navigating to the test URL, locate the checkbox with the CSS_SELECTOR property. After checking if the checkbox is enabled or not [with the is_enabled() method], select the checkbox using the click() method.

In the second test, we check if a particular checkbox is enabled or not. First, we locate all the required checkboxes using the XPath property. Since there are 4 checkboxes in total, a for loop is executed to check its status with the is_enabled() method.

Only if enabled, the respective checkbox is selected by invoking the click() method.

Test Execution:

Run the below-given command on the terminal to trigger the execution of the tests.

make locating_check_boxes_test

Handling Alerts in Selenium Python

Alerts are commonly used in varied scenarios like form submission, data validation, and session timeout warnings, amongst others. Since alerts are so common in the web world, handling alert windows in Selenium is something that you should consider when learning Selenium with Python.

Selenium with Python provides the switch_to.alert method for switching the context to the alert window.

Shown below are some operations that are possible on alert windows:

Operation Description
accept() Accept the alert
dismiss() Dismiss the alert
send_keys() Send content to the currently active alert

Test Scenario:

  1. Navigate to the Javascript Alert Box Demo page.
  2. Locate the appropriate alerts.
  3. Accept/dismiss/send content based on the type of alert.

Implementation: Test scripts for the above-mentioned test scenario are named as 8_handling_alerts.py

Code Walkthrough:

As a first step, we locate and click on the button to trigger the alert window. First, switch to the alert using the switch_to.alert method. Now accept the alert with the accept() method. Once the alert is accepted, the alert window closes, and the focus shifts back to the parent window.

An explicit wait is performed until the expected condition alert_is_present() is true. It is to ensure that the alert is available before any interactions are performed on it.

Like before, we switch to the alert. Since this alert supports both OK (i.e., accept) and cancel (i.e., dismiss) operations, we invoke the dismiss() method to cancel the alert.

Check if the label that displays the status is present or not by checking the expected condition presence_of_element_located. It is important to check if an element exists in Python Selenium, else it can result in an exception.

For the final test, we first trigger the alert and check for its presence. If present, the required text is entered in the alert with the send_keys() method.

Finally, we accept the alert and verify its execution by checking the status string.

Test Execution:

Run the command on the terminal to trigger the execution of the tests.

make handling_alerts_test

Handling iFrames in Selenium Python

When it comes to automating interactions with iFrames, the first step is switching to iFrames in Selenium. Like alerts, Selenium WebDriver also offers a switch_to.frame() method to switch to the required iFrame. The iFrame can be identified by Name, ID, index, or WebElement.

Once the actions on the iFrame are performed, you need to switch back to the main content (or parent window) by invoking the switch_to.default_content() method.

Test Scenario 1 (Nested Frames):

  1. Navigate to the Nested Frames page.
  2. Locate and switch to the frame ‘Top’.
  3. Assert in case of failure.

Test Scenario 2 (iFrames):

  1. Navigate to the Simple iframe page.
  2. Locate and switch to the iFrame – body.
  3. Enter “LambdaTest is an awesome platform!” in the text box.
  4. Make the entered content bold and underline.

Implementation: Test scripts for the above-mentioned test scenario are named as 9_handling_iframes.py

Code Walkthrough:

After navigating to the URL under test, locate the required iFrame with the XPath selector – //p[.=’Top’]. Switch to the iFrame by invoking the switch_to.frame() method with a parameter set to the iFrame located in the earlier step.

Switch back to the parent window by invoking the switch_to.default_content() method. Navigate to the Simple iframe page and locate the desired iFrame with the ID locator. Switch to the located iFrame so that we can perform further actions on the iFrame.

Since we intend to type content in the text area, we first locate the same with the find_element() method and CSS Selector – .rsw-ce

Since there is already default content in the text area, we first select the entire paragraph by performing a triple click within it. A chain of actions of triple-click is created, after which the required action is performed with the perform() method of the ActionChains class.

Now that the entire paragraph is selected, delete the selected content with the send_keys() method with the key combination set to BACKSPACE. The new content is entered in the text area.

Since the content needs to be bold and italic, we first wait for the element (for bold) to be clickable (i.e., element_to_be_clickable). The element to make the content italic is also located with the XPath locator.

Now that the bold and italic in the iFrame toolbar are identified, a click is performed on those elements to make the text area content bold and italicized.

Test Execution:

Run the below-given command on the terminal to trigger the execution of the tests.

make handling_iframes_test

It’s a Wrap!

Thanks for making it this far! Python is one of the widely used languages, and it is growing up the ranks with each passing year. Though PyUnit is the default test automation framework, pytest is more widely used in comparison to the PyUnit framework.

Also, it is relatively easy to run Selenium Python tests in parallel using the pytest-xdist plugin. In this Python tutorial, we deep-dived into the integral aspects of Selenium and Python for automating interactions with varied elements on a page.

The potential of Python and Selenium can be harnessed by performing Python automation testing on a cloud Selenium Grid (like LambdaTest). Also, do drop in your comments about the common challenges that you normally encounter when it comes to Selenium automation testing!

Happy Testing 🙂

Frequently Asked Questions (FAQs)

What is Selenium Python used for?

Selenium with Python is used to automate web browser interactions for testing web applications, web scraping, and repetitive browser tasks.

Is Selenium with Python easy to learn?

Yes, Selenium with Python is relatively easy to learn due to Python’s simple syntax and extensive libraries.

What is the Selenium tool used for?

Selenium is a tool used for automating web browsers to test websites and web applications across different browsers and operating systems.

Citations

Author Profile Author Profile Author Profile

Author’s Profile

Himanshu Sheth

Himanshu Sheth is a seasoned technologist and blogger with more than 15+ years of diverse working experience. He currently works as the 'Lead Developer Evangelist' and 'Senior Manager [Technical Content Marketing]' at LambdaTest. He is very active with the startup community in Bengaluru (and down South) and loves interacting with passionate founders on his personal blog (which he has been maintaining since last 15+ years).

Blogs: 128



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free