Locate the unique identifier for the initial product with a special badge on an online retail platform through the use of Selenium

To complete the task of finding the top-selling women's socks on Amazon, I attempted to locate the item labeled as a "Best Seller" after searching for "Socks for women" on the website. However, I am struggling with the logic to identify and click on this specific element within the list of items. Any suggestions or alternative approaches would be greatly appreciated.

List<WebElement> elements = driver.findElements(By.cssSelector("div[class*='s-card-container']"));
for(WebElement e : elements) {          
   // iterate
}

Answer №1

Here is the solution to find and click on the first Amazon best seller:

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

import java.util.List;

public class FindAndClickFirstAmazonBestSeller {

    @Test
    public void test() throws Exception {
        WebDriverManager.chromedriver().setup(); // ensure chromedriver is downloaded

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.amazon.com/s?k=socks+for+women&crid=O6H6S2VU5M66&sprefix=socks+%2Caps%2C74&ref=nb_sb_ss_ts-doa-p_2_6");

        List<WebElement> allBestSellers = driver.findElements(By.xpath("//span[text()='Best Seller']//ancestor::div[contains(@class,'s-card-container')]/div"));

        if (allBestSellers.size() > 0) {
            System.out.println("Total amount of best sellers: " + allBestSellers.size());

            allBestSellers.get(0).click(); // click on the first best seller item
        } else {
            System.out.println("There are no best sellers found");
        }
        
        Thread.sleep(10 * 1000); // wait for 10 seconds before closing browser
        driver.quit();
    }
}

Console output:

Total amount of best sellers: 2

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

Retrieving elements from the following page using Selenium in Python

My current project involves creating a Python3.5 program using Selenium to automate the downloading process on zbigz.com using the Firefox webdriver. The code snippet I am using looks like this: import time from selenium import webdriver from selenium.com ...

Display the element only when the input is in a selected state using CSS

Looking for a way to display an element when an input field is selected without using JavaScript? Preferably, the solution should not involve placing the element within the input field. Unfortunately, targeting the element in CSS with the :active selector ...

What is the best way to create distance between my buttons?

Can anyone help me with an issue I'm facing where adding margin to my buttons is causing the last button to jump down a row? I have an idea of what might be happening but I'm unsure how to solve it. Below is the CSS code for the buttons, any sugg ...

Python Error: Selenium Cannot Locate Element

If the element is not found, it should print: "not found," however I encountered an error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":&qu ...

Encountered ImportError with Seleniumwire

I am struggling to identify the source of this error message in Python 3.9 and 3.10. Traceback (most recent call last): File "C:\Users\User\Desktop\S\SS\test.py", line 1, in <module> from seleniumwire imp ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

Implement a feature in JSP that allows users to dynamically add or remove fields before submitting the data to the database

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http- ...

Different ways to update a SimpleCursorAdapter in a Listfragment using .notifyDataSetChanged()

How can I properly insert a new view data row into a ListView (ListFragment) without encountering a NullPointerException error when using adapter.notifyDataSetChanged(); in a new method? I've attempted to declare a Cursor in a new method and also tri ...

Chrome Driver Protractor Angular 2 encountering issue with unclickable element

My issue is with clicking the second level menu options to expand to the third level. I have tried using browser.driver.manage().window().setSize(1280, 1024) in the before all section. Here is my code snippet: it('Should trigger the expansion of the ...

Slider with FadeIn effect remains unresponsive to the FadeOut command (JQuery / Javascript)

I'm currently working on a slider that is supposed to fade in and out. However, I am facing an issue where the slide fades in correctly but instantly disappears instead of fading out. Do you have any insights into why this might be happening and any s ...

Selenium WebDriver is experiencing difficulty clicking on a hyperlink as the click is being redirected to a different element

I'm having trouble with clicking on the Website hyperlink as it keeps redirecting to Recently used pages. Attempted using the CSS locator of the Website icon, which works in the lower environment where there are no Recently used pages present. Also ...

You can only import Next.js Global CSS from your Custom <App> and not from any other files

Initially, my React App functioned perfectly with global CSS included. However, after running npm i next-images, adding an image, modifying the next.config.js file, and executing npm run dev, I encountered the following notification: "Global CSS cannot ...

How can you add draggable functionality to a Bootstrap dropdown menu?

My custom bootstrap dropdown design <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span cla ...

Alert: An error message is displayed despite completing the required field

My apologies in advance as I am new to coding and there may be a glaring mistake in my current project. I am creating a survey that requires participants to enter their age. The demographic data questions are organized in a table format, with code borrowed ...

Step by step guide to showcasing images dynamically in user interface

My current project involves displaying a screen with an HTML table and an image. The HTML table is fully dynamic. The Code Working Process When the user loads a page (with a URL), I render an HTML table in different parts as the page loads. I retrieve al ...

Tips for reducing the size of the IE Browser window using Selenium WebDriver

Looking to reduce the size of the IE Browser window using selenium webDriver with c#. ...

Utilizing a pre-existing Google Chrome profile with the Selenium Chrome WebDriver in Python

I'm having trouble loading my complete existing Google Chrome profile with all extensions, where I am logged into both Google and other site accounts. The code seems to have a syntax error that I can't pinpoint. chrome_options = Options() chrome ...

How can I configure my React Project to direct users to example.com/login.html when they land on the root URL?

My goal is to verify a user's identity through a third-party authentication server. The redirect_uri indicates that after the user logs in, they will be redirected to example.com/login.html. Inside the login.html file, there will be specific html/scr ...

What's the best way to toggle the visibility of an input-group in Bootstrap?

Is there a way to properly hide and show a Bootstrap 5 input-group? You can see an example here: https://jsfiddle.net/o08r3p9u I'm facing an issue where once the input group is hidden, it doesn't show correctly when displayed again. How can I e ...

Combining integers from an array into a single integer in Java

Looking to combine the values of an array of integers into a single integer without using the join or number methods taught in class. For example, if the array is {1, 2, 3}, the result would be 123. My proposed steps are as follows: Convert the first e ...