What is the correct way to loop through a collection of web elements in Selenium WebDriver using Python?

My current project involves testing a webpage containing a list of product articles. Each article includes an item title, price, stock availability tag, and an add to cart button. To achieve my goal, I am attempting to gather all the product articles using the By library and CSS_SELECTOR locator. Then, I plan to iterate through this list to identify available items by locating the stock availability tag and appending these products to a separate list. Ultimately, I aim to randomly select a product from the list of available items and click on the add to cart button.

However, despite manual verification showing different counts for the complete list and the list of available items, my program consistently returns identical lengths for both lists.

        all_items_on_page = self.browser.find_elements(*CataloguePageLocators.PRODUCT_POD_ARTICLE)
        print(f"Total number of items on page is {len(all_items_on_page)}")
        available_items = []
        for item in all_items_on_page:
            if self.is_element_present(*CataloguePageLocators.AVAILABLE_ITEM_TAG) is True:
                available_items.append(item)
        print(f"Total number of available items is {len(available_items)}")
        return available_items

The is_element_present function has the following code:

    def is_element_present(self, how, what):
        try:
            self.browser.find_element(how, what)
        except NoSuchElementException:
            return False
        else:
            return True

I have included the print statements to compare the lengths of the lists, although they are temporary and will be removed once the issue is resolved. I suspect the problem lies within the if condition, and likely has a simple solution that currently eludes me.

Answer №1

Using <strong>self.browser.find_element(how, what)</strong>
in this context means that the same element
*CataloguePageLocators.AVAILABLE_ITEM_TAG
is being found each time within the for loop, leading to ineffectiveness.

To address this issue, refer to this helpful article which suggests utilizing element.is_displayed() as a potential solution instead of the current approach. It's important to note that is_displayed() provides a boolean value (True or False) and does not require catching an exception.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on using selenium with python to interact with buttons

Starting out with Python and Selenium, I'm eager to automate clicking the "Afficher plus" button on this specific webpage. I attempted the following code snippet: plus = driver.find_element_by_css_selector("button[class='b-btn b- ghost']" ...

Exploring Feature Extraction and Dimension Reduction with MLP

I am currently developing a model that utilizes MLP for both feature extraction and dimension reduction. This model has the ability to condense data from 204 dimensions down to just 80 dimensions through the following process: A dense layer with 512 dimen ...

The hash for the JSONObject could not be located

Currently, I am in the process of developing a Test Automation Script using JAVA and Selenium WebDriver. The test is being executed on a cloud environment provided by crossbrowsertesting.com. One of the features allows for taking snapshots of the browser w ...

Steps to Automatically Close Browser Upon Test Failure in Parallel Testing

Struggling to find a solution for closing the browser when a test fails in Selenium. I've tried implementing an AfterMethod but unfortunately, the browser still isn't closing on fail. Any assistance would be highly appreciated! Below is my Java ...

Move the primary window to the front in PySide

The situation: Here's the deal - I've got a total of 3 windows along with 1 window manager file. The window manager kicks off the main window and you can open other windows from there. Everything seems to be going smoothly so far. However, all t ...

Locate the XPath for a recurring AngularJS element

Is it possible to determine the xpath for an angularJs element? I noticed that all links on my page share the same xpath due to repeated items in angularJS. .//*[@id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a I have ...

Python 2.7's Timezone Adjustment

My current approach involves shifting a time forward or backward based on an integer value. I simply add or subtract the time shift from the hour, then use mod 24 when constructing the new time. time_structure = datetime.time((hour + time_zone_shift)%24, ...

Calculating the edit distance between two fields in a pandas dataframe

I am working with a pandas DataFrame that has two columns of strings. My goal is to add a third column which will calculate the Edit Distance between the values in the first two columns. from nltk.metrics import edit_distance df['edit'] = ed ...

Guidelines for extracting specific text data from a label element with Selenium and Python

I am working on iterating through a variety of checkboxes in order to verify their presence within a given list, and then click on them if they match the criteria. Here is an example of the HTML element that I have managed to extract: <label> < ...

Repeatedly clicking on a pagination 'load more' button in Selenium (Python) to load dynamically generated JavaScript data

I have been attempting to crawl the content of a website by dynamically clicking a 'load-more' button. Despite researching similar questions on Stack Overflow, I have not found a solution that addresses my specific issue when parsing the website ...

Analyzing the Hover functionality through Selenium Testing

Currently, I am working on testing the change in background color to #F67621 when hovering over an element. In this case, the background color code needs to be compared with a predefined expected value using XPath as the selector. String xPathStr="//input ...

How can we transform the input for the prediction function into categorical data to make it more user-friendly?

To verify my code, I can use the following line: print(regressor.predict([[1, 0, 0, 90, 100]])) This will generate an output. The first 3 elements in the array correspond to morning, afternoon, and evening. For example: 1, 0, 0 is considered as morning 0 ...

Cannot get MySQLClient to install using pip on MacBook Pro M1 running the latest version of Big Sur

I recently got my hands on a brand new Macbook Pro featuring the M1 chip and made sure that homebrew would run smoothly on it. While I've been able to pip install various libraries without any trouble, I'm encountering issues specifically with my ...

Obtaining the Id token bearer through selenium webdriver - a step-by-step guide

Is there a way to retrieve the id token bearer post-login using selenium webdriver or another framework? Any suggestions would be appreciated. Thank you! ...

I am unable to generate png maps using folium with the combination of selenium and firefox

I have been attempting to export a map that I created using folium in Python to a png file. I came across a post suggesting that this can be achieved by using selenium with the following code snippet: Export a folium map as a png import io from PIL import ...

Difficulty encountered while attempting to tally the amount of words within a loop

Struggling to calculate the total number of words in a for loop, encountering issues with the sum() method and unsuccessful attempts using list-append method: for line in open("jane_eyre.txt"): strip = line.rstrip() words = strip.split() for i in ...

What is the best way to store a collection of class instances in a serialized format

Is there a way to convert an object that contains a list of objects into JSON format? Error message received: TypeError: Object of type person is not JSON serializable Here's the code snippet in question: import json class person: def __init__( ...

Encountering a problem while creating a Page Object in webdriver.io - getting the error "setValue is not a function" or "cannot read property 'setValue' of undefined"

While working on a webdriver.io automation project, I encountered an issue with recognizing objects in my page object file (login.po.js) when calling them in the test spec file (test.spec.js). The error message displayed is LoginPage.username.setValue is n ...

What's causing Elif to display after certain list inputs?

Currently, I am working on a shopping basket program and I encountered an issue where the "elif" statement is being printed after certain items like "ham" have been entered. Why is this happening? I have already attempted to include the while loop in the ...

Encountering an error while trying to install PyDev in Eclipse

There was an issue when trying to access the repository at http://pydev.sf.net/updates/content.xml. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid c ...