webelement gettext()返回空值

wwtsj6pe  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(369)

下面的代码用于使用seleniumwebdriver从amazon获取移动电话的价格。
如果我在xpath的末尾使用/span1,它不会打印任何内容
如果我不使用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()得到不同的输出?

cbjzeqam

cbjzeqam1#

price文本来自第二个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()文档显示
获取此元素的可见(即不被css隐藏)文本,包括子元素。 <span class="a-offscreen">8888</span> 是隐藏的。

相关问题