简体   繁体   中英

WebElement getText() Returns empty value

Following code is used to get a mobile phone's price from amazon using Selenium Webdriver.

  1. If I use /span 1 at end in xpath it is not printing anything

  2. If I don't use xpath it prints price

HTML source code for the elements 在此处输入图像描述

    WebDriverManager.chromedriver().setup();
    
    WebDriver driver = new ChromeDriver();
    
    driver.manage().window().maximize();
    
    driver.get("https://www.amazon.in");
    
    
    
    driver.findElement(By.xpath("//input[@id='twotabsearchtextbox']")).sendKeys("one");
    
    Thread.sleep(2000);
    
    List<WebElement> all_mobile= driver.findElements(By.xpath("//div[@id='suggestions']/div/span"));
    
    //Thread.sleep(2000);
    
    int total= all_mobile.size();
    
    //System.out.println(total);
    
    for(int i=0; i<total;i++)
    
    {
    
    String mobiles = all_mobile.get(i).getText();
    
    //System.out.println(mobiles);
    
    if(all_mobile.get(i).getText().equals("plus nord 5g"))
    
    {
    
    all_mobile.get(i).click();
    
    break;
    
    }
    
    }
    
    Thread.sleep(2000);
    
    String  text = driver.findElement(By.xpath("(//span[@aria-label='FREE Delivery by Amazon'])[1]/span")).getText();
    
    System.out.println(text); //it prints FREE Delivery by Amazon working fine if I use /span at end or not both ways but below iam getting issue in price
    
    String  price = driver.findElement(By.xpath("(//span[@class='a-price'])[1]/span[1]")).getText();
    
    System.out.println(price); //it prints nothing if iam using /span[1] at end   
    
    String  PRICE = driver.findElement(By.xpath("(//span[@class='a-price'])[1]")).getText();
    
    System.out.println(PRICE); //it prints ₹29,990 if iam not using /span[1] at end    

Can anyone please help? Why I am getting different outputs with getText()?

Price text is coming from the second span element. <span aria-hidden="true"> . First span is hidden by CSS

<span class="a-price" data-a-size="l" data-a-color="price">
  <span class="a-offscreen">₹29,990</span>
  <span aria-hidden="true">
    <span class="a-price-symbol">₹</span>
    <span class="a-price-whole">29,990</span>
  </span>
</span>

You can get the price from the second span element too

 System.out.println("Experiments ");
 price = driver.findElement(By.xpath("(//span[@class='a-price'])[1]/span[2]")).getText();
 System.out.println(price);

WebElement's getText() documentation shows that

Get the visible (ie not hidden by CSS ) text of this element, including sub-elements.

<span class="a-offscreen">8888</span> is hidden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM