What is the method for retrieving all elements, regardless of duplicative data?

I need assistance with a project in which I am attempting to extract brand names and prices from a website. Below is the code I am currently using:

List<WebElement> list_of_products = driver.findElements(By.xpath(loc.getProperty("brandName")));
    List<WebElement> list_of_products_price = driver.findElements(By.xpath(loc.getProperty("finalPrice")));


    //System.out.println("these are the products "+ list_of_products);
    // Implementing HashMap to store Products and Their prices(after conversion to
    // Integer)
    String product_name;
    String product_price;
    int int_product_price;
    HashMap<Integer, String> map_final_products = new HashMap<>();
    {

        for (int i = 0; i < list_of_products.size(); i++) {

            product_name = list_of_products.get(i).getText();// Iterating through and fetching product name
            product_price = list_of_products_price.get(i).getText();// Iterating through and fetching product price
            product_price = product_price.replaceAll("[^0-9]", "");// Removing anything that isn't a number
            int_product_price = Integer.parseInt(product_price);// Converting to Integer
            map_final_products.put(int_product_price, product_name);// Adding product and price to HashMap
        }

        // displaying all the products found
         Reporter.log("All the prices and products we found: " +
         map_final_products.toString()+ "\n", true);

        // Getting all keys from Hash Map
        Set<Integer> allkeys = map_final_products.keySet();
        ArrayList<Integer> array_list_values_product_prices = new ArrayList<Integer>(allkeys);

        // sorting in ascending order with lowest at the top and highest at the bottom
        Collections.sort(array_list_values_product_prices);

The output on the console shows: The brandnames being referred to as XYs.

All the prices and products we found: {20720=XY, 11490=XY, 13490=XY, 15490=XY, 19490=XY, 21990=XY, 16490=XY, 18490=XY 20490=XY, 18990=XY, 20990=XY}

I've noticed that my code does not capture or display duplicate prices for different brands(or the same brand too). For instance, there might be multiple products priced at 13490 and many more at 18490 on the website.

How can I adjust my code to include all pairs of brands and prices, even if they have matching prices?

Answer №1

Hey, @Peter! Have you considered using the product Name as your key instead of Price? This way, you can easily reverse the location. However, keep in mind that this might not display the same product with different prices. It should be fine though, as it's unlikely for the same product to have different prices on the same website.

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

What is the best way to successfully navigate a parsed document?

Hey there, I appreciate your time and assistance. I am currently working on parsing an XML file located in the "res/raw" folder and passing the parsed result to another class for further processing. However, I seem to be stuck and unable to find a solution ...

What is the best way to find the number of <div> elements within a parent <div> using selenium?

I'm looking for a way to count the number of <div> elements within a parent <div> using Selenium. Here's the code snippet I have: List<String> productNames = new ArrayList<String>(); List<WebElement> divElements = ...

Accessing a variable from another HTML using JavaScript

I'm currently attempting to access a variable from another HTML file using JS. Specifically, I have a file (file1.htm) that opens a dialog box, and I want to send the information of the selected file to another file (file2.htm) in order to modify a v ...

Error: Failed to find the location because geolocate has not been defined

I searched extensively online for a solution to my problem without success, so I am reaching out to seek your assistance. I am attempting to utilize the Google Address auto-complete API within an asp.net core framework. In my razor file, I have included: ...

Can the pointerover event be managed on a container within the am5 library?

While attempting to add an HTML label to a map and trigger a pointerover event, I encountered issues. The objective was to change the HTML content upon hover. Despite trying to incorporate a tooltip, the hover event failed to work properly, and the tooltip ...

Calculating the function using data in a Vue component

Here is a Vue component along with some data: Vue.component('receipt', { template: '#receipt-template', data: function() { return { tip: 8.50 }; }, computed: { subtotal: function( ...

Issues with calculating results have been identified in the Java survey program

For my project, I aim to develop a Java application that employs an array, a looping structure, and a function to carry out a survey involving 3 questions posed to 4 individuals. Each question will elicit a response of either yes or no. The final results o ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

Discover the best way to implement Wait.Until in Selenium when you already have the element using FindsBy

Currently, I am utilizing the Wait.Until method to ascertain whether my page has finished loading or if it is still in the process of loading. The implementation looks like this: protected IWebElement FindElement(By by, int timeoutInSeconds) { ...

Upon returning to the website homepage from another page, the JavaScript animation ceases

I implemented a unique typewriter animation on my homepage by utilizing code from this source and making minor HTML edits to customize the content. https://codepen.io/hi-im-si/pen/DHoup. <h5> <body>Hello! I am Jane.</body> < ...

Is there a way to retrieve a value from localStorage and use it to automatically set the selected option in a UL-based dropdown list upon page load

I have implemented a unique UL-based dropdown list that I discovered here (specifically the third model) as the foundation for a role-based selection box for my users. To enhance user experience, I am storing their role selection in localStorage so they do ...

Is there a way to simultaneously utilize multiple browser instances in Selenium with Python?

Is it possible to open three identical windows of a website and perform the same actions on all of them simultaneously? I'm new to Selenium and programming in general, so forgive me for this basic question. Any help is appreciated. Update: I attempte ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Ensuring proper alignment within anchor links and buttons

button, a { height: 30px; display: inline-block; border: 1px solid black; vertical-align: middle; } button > div, a > div { width: 30px; height: 10px; background-color: red; } <button> <div class="buttonDiv"></div> ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

HTML // jQuery - temporarily mute all audio for 10 seconds after page reload

Is there a way to automatically mute all audio sounds on my website for the first 10 seconds after it is reloaded, and then unmute again? <audio id="musWrited" autoplay> <source src="sound/soundl.mp3" type="audio/mp3" /> // < ...

Fetching server-side data for isomorphic React app: A guide to accessing cookies

Currently, I am in the process of developing an isomorphic/universal React + Redux + Express application. The method I use for server-side data fetching is quite standard: I identify the routes that match the URL, call the appropriate data-fetching functio ...

A basic problem involving appending content using jQuery

I have encountered a puzzling issue. Whenever I attempt to insert new content into the <div> element using my JS code, it briefly appears and then disappears abruptly. I am unsure of the reason behind this behavior. Is there a way to prevent this fr ...