Such a task should be on the site https://www.slivki.by/sushi-2 choose sushi with the biggest discount. Show me what I wrote wrong? Here is my bad code.

public class Firstcase { @Test public void test2() { FirefoxDriver driver = new FirefoxDriver(); driver.get("https://www.slivki.by/sushi-2"); List<WebElement> discont = driver.findElements(By.className("discount-label")); List<WebElement> sortedDiscont = driver.findElements(By.className("discount-label")); Collections.sort(sortedDiscont, comparator); System.out.println(sortedDiscont.get(0).getText() + " index= " + discont.indexOf(sortedDiscont.get(0)));discont.get(discont.indexOf(sortedDiscont.get(0))).click(); int k=discont.indexOf(sortedDiscont.get(0)); String sw=Integer.toString(k); String Str="//img[contains(@src,'http://store.akamai.steamstatic.com/public/images/blank.gif')])[30]"; String fin=Str.replace("30", sw); System.out.println(fin); // driver.findElementByXPath(fin); for (WebElement element : discont) { System.out.println(element.getText() + "\n"); } discont.get(discont.indexOf(sortedDiscont.get(0))).click(); driver.quit(); } Comparator<WebElement> comparator = new Comparator<WebElement>() { @Override public int compare(WebElement o1, WebElement o2) { int firstValue = 0; int secondValue = 0; try { firstValue = Integer.parseInt(o1.getText().replace("%", "").replace("-", "")); secondValue = Integer.parseInt(o2.getText().replace("%", "").replace("-", "")); } catch (Exception e) { e.printStackTrace(); } if (firstValue == 0 && secondValue == 0) { return 0; } return firstValue > secondValue ? -1 : 1; } };} 

    1 answer 1

    You can go the other way, after we have found the element with the biggest discount, we take its parent and we are already looking for an element with the img tag:

     WebElement result= discont.get(0).findElement(By.xpath("..//img")); result.click(); 

    I advise you to learn XPath, it is like a regular routine for parsing strings, it has a powerful search mechanism.