Unable to get the Search results in List using Xpath or CssLocator in Selenium Webdriver



  • Here is the requirement

    Go to https://www.amazon.in/
    Search for Apple Iphones
    Get all Search results in to list
    Iterate the list and print available iphone names and respective price.**
    Here i am able to do till step 2 and facing difficulty in in step 3. I.e i am unable to take the search results in the list. Any suggestions appreciated.

    This is the code i wrote

    @Test
    void test() {
    
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.amazon.in/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//div[@id='nav-xshop']/a[.='Mobiles']")).click();
        driver.findElement(By.xpath("//ul[5]//span[@class='a-size-small']")).click();
        driver.findElement(By.xpath("//span[.='Apple']")).click();
        driver.findElement(By.xpath("//input[@id='twotabsearchtextbox']"))
            .sendKeys("Apple iPhone");
        WebElement searchButton = driver.findElement(By.xpath("//input[@value='Go']"));
        searchButton.click();
        List<WebElement> searchResults = driver.findElements(By.xpath(".//li[starts-with(@id='atfResults, 'result_')]"));
        for (WebElement searchResult : searchResults) {
            //Loop the List and Print name and price
        }
    

    I have time constraint, Please help me to tackle this down. Thank you



  • First of all, your xpath is not correct ( the "." should not be there)

    Try this xpath is for name:

    //span[contains(@class, ' a-color-base a-text-normal')]
    

    This one for price:

    //span[@class='a-price-whole']
    

    This is how you can take the price text based on name locator (parent to child)

    //span[contains(@class, ' a-color-base a-text-normal')]//following::span[@class='a-price-whole']
    

    If you're trying to take all results in another way, store them as main div, if you iterate trough them and scrape the text for a specific child, you need to understand how locators are created



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2