Guide To Find Index Of Element In List with Python Selenium

Jolivé Hodehou

Posted On: December 22, 2022

view count137267 Views

Read time3 Min Read

In an ideal world, you can test your web application in the same test environment and return the same results every time. The reality can be difficult sometimes when you have flaky tests, which may be due to the complexity of the web elements you are trying to perform an action on your test case.

However, web elements are essential when writing automated tests. To avoid this, it is important to use the right method to find the element you are trying to act on.

Finding an element using an index can help to avoid tests that produce inconsistent results. In this Selenium Python tutorial, we will discuss how to find index of element in list with Python using Selenium WebDriver.

So, let’s get started!

What is an index?

In Selenium, an index is a numerical position of an element within a list of elements. For example, if you have a list of elements representing links on a webpage and want to select the third link, you could use an index to specify that you want to select the element at the third position in the list.

An index is defined based on specific nodes in the node set for indexing using Selenium WebDriver. You can use the indexes to get a specific item in the list of identified locators. You can learn more about it from this blog on different locators in Selenium.

Let’s assume that if you write an XPath //input[@id=’lambda’], which gives you five matching nodes, then you would have to use the indexing concept.

For this, if the object is identified at index 1, then the XPath would be [//input[@id=’lambda’]][1].

Else, if it is identified at index 2, then it would be (//input[@id=’lambda’])[2].

Note: Indexes start from 0.

Let’s take an example to illustrate better.

Example 1: LambdaTest Sign up page.

On the LambdaTest registration page, we have a country selection field, which is a select. When we use the XPath //*[@id=”country_code”] to find the element, it returns 215 nodes.

LambdaTest Sign up page

So we will need to use the indexes to find the specific element we want to interact with. Note that in this blog on how to find index of element in list with Python, we use XPath to find our locators. You have the choice to use other methods like CSS Selector etc.

Now let’s prepare our test environment. We will need to install pytest and Selenium.

How to set up a test environment?

In the section of this blog on how to find index of element in list with Python, we will learn how to set up a test environment. However, before that, let’s understand the pytest framework.

What is the pytest framework?

Pytest is a very popular Python test automation framework (mainly used for unit testing). This highly configurable and scalable testing framework comes with a rich set of features to help you write better code for Python tests.

Pytest is often described as a flexible framework with less boilerplate code than other testing frameworks. pytest fixtures provide context for tests by passing parameter names in test cases; its parameterization eliminates duplicate code for testing multiple sets of input and output, and its rewritten assert statements provide detailed output for failure causes.

In this pytest tutorial, learn how to use parameterization in pytest to write concise and maintainable test cases by running the same test code with multiple data sets.

Installing the pytest framework

To install pytest on your machine, you first need to install Pipenv.

But make sure you have Homebrew on your machine because we will use a macOS operating system in this tutorial on how to find index of element in list with Python Selenium.

  1. Type the following command in your terminal.
  2. brew install pipenv

    The pipenv installation should look like this:

    pipenv installation

  3. Once you have installed it, make sure you have pipenv installed on your machine by typing in your terminal:
  4. pipenv

    The result should look like this:

    pipenv installed on your machine

    There are several other alternatives to Pipenv for package management, which can also be used like pyenv, poetry, virtualenv, autoenv, etc. However, adding them is beyond the scope of this blog on how to find index of element in list with Python Selenium.

  5. Creation of Pipfile in an empty directory. This file is essential for using Pipenv. It tracks your project’s dependencies if you need to reinstall them.
  6. The python_version parameter is the version of the base interpreter you specified when creating a new pipenv environment.

    The packages section is where you can list the packages required for your project. “*” is for installing the latest stable versions of the packages.

    At the time of writing this blog on how to find index of element in list with Python Selenium, the latest versions of pytest and Selenium are pytest 7.1.2 and 4.2.2, respectively.

  7. In your terminal, go to the directory and install the latest stable versions of the pytest and Selenium packages with the command:
  8. Pipenv Install

latest stable versions of the pytest

In this blog on how to find index of element in list with Python Selenium, we will use the LambdaTest Selenium Grid with pytest to run our tests. But you could have done this locally by installing the latest version of WebDriver for the browser you want to use. You can also use WebDriverManager.

Here are the download links for the most commonly used browsers.

Make sure you have the correct version for your browser; otherwise, it won’t work.

Now let’s add some code to the demo on how to find index of element in list with Python using Selenium WebDriver from our Selenium controlled browser.

How to find index of element in list with Python Selenium?

In this section of the Python automation testing blog on how to find index of element in list with Python, we will consider the following test scenario to download files using Selenium Python:

  1. Go to the Selenium Playground > Input Form.
  2. Click on the Country DropDown.
  3. Select a country (India).
  4. Save the selected country in a country.txt file.

This is what the structure of our project should look like.

index of element in list with Python Selenium

In the blog, we will create a tests folder.

In Python projects, it is conventional to create a “tests” directory under the project’s root directory to hold all the test cases.

We will create a file test_index.py in our “tests” folder, in which we will write our test case.

test index

Github Button

Code Walkthrough:

The pytest module provides a rich set of tools for constructing and running tests. In this blog on how to find index of element in list with Python Selenium, we have used unittest, but several other Selenium Python testing frameworks can be used, like Unittest, Robot, DocTest, etc.

Python sleep() is a method of the Python time module. So, first, we must import the time module, and then we can use this method:

This will import the Selenium packages that we will use for our project

The selenium.webdriver module provides all the WebDriver implementations. Currently, supported WebDriver implementations are Firefox, Chrome, Microsoft Edge, IE, and Remote.

The By class is used to locate elements within a document.

Automation uses locators to find elements on a page. Selenium locators are simple query strings for finding elements. They return all elements that match their query.

Selenium WebDriver supports many locators: ID, Name, Class Name, CSS Selectors, XPath, Link text, Partial link text, and Tag name.

Here we used Name to find the country field and clicked on the element.

element name to find the country field

You will notice that the different countries all have the same tagName. So we will have to use the index to choose a specific country.

Indexes can also be useful in cases where the same XPath returns multiple web elements.

The index is defined based on specific nodes in the node set for indexing using Selenium WebDriver. We can also reference the specific node to the index using many indexes enclosed in []. The tag name UI element contains several child elements whose tag name is option.

Element:

Now look at the Items tab; you will see that the XPath above returns 251 elements since there are 251 countries in the drop-down list.

XPath

Now let’s try to choose India from the list of countries:

 list of countries

Now that we know the index of the option, we save it in a variable country_index.

variable country_index

We then use this index to choose the country India.

choose the country India

We then saved the chosen country in a country.txt file.

How to find index of element in list with Python Selenium on the cloud Grid?

To use LambdaTest Selenium Grid with pytest to perform Python web automation, you will need a LambdaTest account.

LambdaTest is a continuous quality cloud that lets you perform Python automation testing on a reliable & scalable online Selenium Grid infrastructure across 3000+ real browsers and operating systems online. Furthermore, you can also cut down build times by multiple folds using parallel test execution.

You can also Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around automated browser testing, Selenium testing, Cypress E2E testing, CI/CD, and more.

Here are steps you can follow:

  1. Navigate to the LambdaTest website and log in if you already have an account, or create one if you don’t have an account yet.
  2. LambdaTest website

  3. Once you are logged in, navigate to the automation page by clicking Automation on the left sidebar of your screen.
  4. automation page

  5. To use pytest with LambdaTest Grid, you need LambdaTest credentials (i.e. username and access key). To get the credentials, click the “Access Key” button on the right side of your screen.
    1. LambdaTest Grid

      Implementation

      Now, let’s add a conftest.py file to the root of our project:

      Test execution in the cloud

      With the various configurations set up in the conftest.py file, we are ready to run the tests.
      Run pipenv run python -m pytest, and you should see the tests running in the terminal.

      pipenv run python

      Once the tests have run successfully, log in to LambdaTest Automation Dashboard to check the status of the test execution.

      test execution

      You can see that the value of the selected element is India.

      element

      country.txt content is below:

      Bonus Section

      Let’s try to do something much more fun. We’ll find all the countries starting with A and save them in a list_country.txt file. Let’s add a new function for this test case.

      The contents of your list_country file should look like this: list_country.txt (github.com)

      If you’re interested in becoming an automation testing expert and building your skills in Python, one way to get started is by earning a Selenium Python 101 certification. This will give you a strong foundation in using Selenium for testing and automation and can help you build a successful career in this field.

      selenium-python-101

      Conclusion

      This concludes the tutorial on how to find index of element in list with Python Selenium. When you automate your web tests using Selenium, you may encounter elements in the DOM that have the same attributes. Indexes can help you perform different actions on a specific element.

      I hope this has given you a good overview of how to find index of element in list with Python Selenium. If you have any questions or comments, please leave them in the section below.

      Frequently Asked Questions (FAQs)

      What is the fastest way to find an element in a list Python?

      The fastest way to find an element in a list in Python depends on the size of the list and the type of elements it contains.

      If the list is small and contains simple elements (e.g., integers or strings), then a keyword or the index() method will be fast enough. These methods have a time complexity of O(n), which means that the time they take to run increases linearly with the size of the list.

      If the list is large and contains complex elements (e.g., objects with many attributes), it may be faster to use a different data structure, such as a dictionary or a set. These data structures allow you to look up elements by key in constant time (O(1)), which is much faster than searching through a list.

      Is there a find method for lists in Python?

      There is no built-in find() method for lists in Python. However, you can use the index() method of a list to find the index of the first occurrence of a specific element in the list.

Author Profile Author Profile Author Profile

Author’s Profile

Jolivé Hodehou

Jolivé Hodehou is a QA Engineer and Technical Writer. He enjoys contributing to the delivery of valuable products by building a strategic vision of quality and by being involved in the different aspects of the tester's role.

Blogs: 7



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free