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?