Java中的Selenium:无法在Amazon上找到元素

时间:2017-05-28 10:20:17

标签: java selenium xpath automation nosuchelementexception

我正在尝试在亚马逊上获取任何产品的评级文本,但我无法编写正确的代码。我不明白我在这里做错了什么。在这里它甚至无法找到元素。 此外,我不认为xpath是错误的,因为我检查过Firepath。

以下是代码:

IWindowSession

请帮帮我。

2 个答案:

答案 0 :(得分:3)

您要获取的span元素包含"4.4 out of 5 stars"之类的文字,但实际上您只会看到带有星标的图标,因此使用visibilityOfElementLocated条件时不明智因为它无论如何都不会被看见。

尝试改为使用presenceOfElementLocated

WebElement elem2 = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@class='a-popover-trigger a-declarative']//span[@class='a-icon-alt']")));
elem2.getAttribute("textContent");

请注意,要获取不可见范围的文字内容,您应使用getAttribute("textContent")代替getText()

答案 1 :(得分:0)

  1. 使用动态xpath而不是绝对xpath:
  2. By.xpath("//*[contains(@class,'a-icon-star')]//*[contains(@class,'a-icon-alt')]")

    rightly pointed out by @Andersson一样,

    1. 使用presenceOfElementLocated代替visibilityOfElementLocated,因为工具提示设计为不可见。

    2. 对隐身元素(例如工具提示而非textContent)使用getText()属性。