WebElement getText() Returns 空值

WebElement getText() Returns empty value

以下代码用于使用 Selenium Webdriver 从亚马逊获取手机 phone 的价格。

  1. 如果我在 xpath 的最后使用 /span1 它不会打印任何东西

  2. 如果我不使用 xpath,它会打印价格

HTML 元素的源代码

    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    

有人可以帮忙吗?为什么我使用 getText() 得到不同的输出?

价格文本来自 second span 元素。 <span aria-hidden="true">。第一个跨度被 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>

您也可以从第二个 span 元素中获取价格

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

WebElement 的 getText() documentation 表明

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

<span class="a-offscreen">8888</span> 已隐藏。