如何解决WebElement getText() 返回空值
以下代码用于使用 Selenium Webdriver 从亚马逊获取手机价格。
-
如果我在 xpath 的末尾使用 /span1 它不会打印任何内容
-
如果我不使用 xpath,它会打印价格
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() 得到不同的输出?
解决方法
价格文本来自第二 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 表明
获取此元素的可见(即不被 CSS 隐藏)文本,包括子元素。
<span class="a-offscreen">8888</span>
已隐藏。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。