Display various texts from various elements with identical class names

I am attempting to extract and print the names of all products from an e-commerce website using Selenium with Java. However, my current code is only fetching the name of the first product it finds within a specific class. How can I modify my code to retrieve the names of all products across multiple classes with the same class name?

Below is the snippet of my code:

package introduction;

import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Getproductnames {

    private static int i;

    public static void main(String[] args) throws InterruptedException {

        // Setting up Chrome WebDriver
        System.setProperty("webdriver.chrome.driver", "D:/Temp/chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        driver.get("https://www.fipola.in/chicken");
        driver.findElement(By.id("DelLocation")).sendKeys("600020");
        driver.findElement(By.className("top_pincode_select")).click();

        Thread.sleep(3000);

        List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));

        for(int i=0; i<products.size(); i++);
        {
            String[] names = new String[]{products.get(i).getText()};
            System.out.println(names[i] + "");
        }
    }
}

Answer №1

If you want to display the names of all products, you can utilize the following code snippet:

List<WebElement> productNames = driver.findElements(By.cssSelector("a.product-item-link"));

for(int i = 0; i < productNames.size(); i++) {
    String productName = productNames.get(i).getText();
    System.out.println(productName);
}

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

Querying subdocuments within an array using MongoDB's aggregation framework

Currently, I'm facing a challenge while developing a statistics dashboard for a meditation app. I'm struggling with creating a MongoDB query to fetch the most popular meditations based on user progress. The key collections involved are users and ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Revamping the current text for the circle feature in ProgressBar.js

I am working on a project where I use ProgressBar.js to generate a circle with a percentage displayed in the center. While the circle renders correctly initially, I'm facing an issue when trying to update the text (percentage) after running it again w ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...

Python Selenium does not output console.log messages

One issue I'm encountering is that when I run this Python script, I can't seem to see any of the console.log, console.error, console.warning messages in my logs: import time from selenium.webdriver.common.by import By from selenium.webdriver.supp ...

Assigning a value to a variable from a method in Vue: a step-by-step guide

I'm having trouble assigning values from a method to variables in HTML. Here's what I have in my code: <b-card-text>X position {{xpos}}</b-card-text> <b-card-text>Y position {{ypos}}</b-card-text> I would like to assign v ...

AngularJS: Hide Row in NG-Grid Based on Condition

I am a beginner in angularJS and I have a requirement to hide a row in my ng-grid table if the value of a column is '0'. The grid consists of 4 columns: User Today This Week This Month I need to hide an entire row if the value in the 'Th ...

Tips for Saving process.argv in a .js File for Future Reference

I am struggling with passing process.argv value to a config file for later use. I am trying to call it from npm scripts. I have the following config file: module.exports = { foo: proccess.argv[2] } So far, I have tried calling it via node config.js &apo ...

What is preventing me from being able to click on the next button and the forgot password link?

https://i.sstatic.net/zdM2G.pngI am encountering an issue with the code snippet below. When attempting to click on the forgot password link, it is not functioning as expected. Can someone assist me in resolving this issue? package testingPackage; impor ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Utilizing AngularJS Directive to trigger a designated function upon change in an input file

My current project involves creating a scavenger hunt editor with various types of questions stored in an array. Each question can be of a different type, all displayed using ng-repeat. To achieve this, I utilize a JavaScript object representing a Questio ...

Scraping Target with Python for Web Data

Looking to extract the names of Chips from this Target marketplacelink, aiming to automatically retrieve all 28 chips listed on the first page. Here is the code I have written: It opens the link, scrolls down (to fetch the names and pictures) and attempts ...

Upon initiating a second user session, NodeJS yields contrasting MySQL outcomes

As a novice in NodeJS and Express, I find myself stuck on what seems to be a trivial issue. Despite my best efforts, I have been unable to resolve the problem on my own. My aim is to create a basic web application that allows user authentication and displ ...

a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions. Does anyone have suggestions on how to adjust the regular expression? var urlPattern ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

The sendFile function fails to transmit any data

Currently working on integrating the mailChimp API into my project, but facing an issue with the resFile code that handles sending the success response. The current code snippet: async function run(){ try { const res = await mailch ...

Having trouble sending the information to Parse.com using the website

I am a beginner with the Parse database and I am currently working on implementing a code that allows users to sign up, with their information stored in the Parse database. However, I am encountering an issue where the values are not uploading as expected. ...

What are the steps for defining the maximum and minimum values in AngularJS?

I'm working with the following HTML markup: <div class="input-group-icon">Max <span class="error">*</span> <div class="input-group"> <input style="border-right:none;" name="available_funds_max" ng-model="attributes.avai ...

Utilizing the CSS :not() selector within a nested table

I am having an issue with my AjaxControlToolkit where the main-page CSS is affecting the inner "calendar" popup. To illustrate what I need, what I've tried, and the temporary workaround, I have simplified everything into a one-page example. I am in s ...

Error: Webdriver does not allow compound class names

I encountered an error message that says: "Compound class names not allowed" This error occurred when I attempted to access a web element with class names that contain spaces. Here is the page source for the element in question. driver.findElement(By ...