【问题标题】:xpath is validated but getting "no such element: Unable to locate element"xpath 已验证但得到“没有这样的元素:无法找到元素”
【发布时间】:2018-06-26 14:17:22
【问题描述】:

我正在尝试打开日历并单击月份。我可以设法打开日历,但我的日历的 xpath 没有被识别。我验证了我的 xpath 在 chrome 控制台中工作,但它只能在打开日历后验证它。有人可以帮我吗?谢谢!

`

`import java.util.List;
 import java.util.concurrent.TimeUnit;

 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.chrome.ChromeDriver;
 import org.openqa.selenium.support.ui.ExpectedConditions;
 import org.openqa.selenium.support.ui.WebDriverWait;

 public class CalendarExample {

     public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub

    System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Java\\Selenium\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://www.path2usa.com/travel-companions");

    List<WebElement> dates = driver.findElements(By.className("day"));
    String text = "";


    //select August 22 from calendar
    //step 1: open the calendar
    driver.findElement(By.xpath("//input[@id='travel_date']")).click();

    //step 2: click the month 
    driver.findElement(By.xpath("//body/div[4]/div[@class='datepicker-days']/table//th[@class='datepicker-switch']")).click();
    }
}

【问题讨论】:

标签: java selenium selenium-webdriver


【解决方案1】:

在 selenium 中,仅当元素在浏览器中可见时才会返回元素对象。另一方面,如果元素不可见,则返回 Selenium.ElementNotVisibleException。因此,查看您共享的问题,日历元素可能仅在其打开时创建,因此在您尝试单击日历时,您必须确保日历已打开。只有这样,元素才会被返回。

PS:关于应该使用哪种 XPath 的建议,请参考:https://stackoverflow.com/a/49497529/1262248

【讨论】:

  • 我想通了,我只需要告诉它等到网页加载完毕。我只是放了一个“Thread.sleep(5000);”在 "driver.get("path2usa.com/travel-companions");" 之后
  • 对...最好将其添加为您问题的答案,以便以相同问题结尾的其他人知道如何解决它
  • Thread.sleep(5000) 不是一个好主意。使用 Selenium API seleniumhq.org/docs/… 提供的等待
【解决方案2】:

您遇到错误是因为您试图在 DOM 中可用之前访问一个元素。 因此,只需首先打开日历,然后使用“day”类访问元素。 无需更改您的xpath

//open calendar
driver.findElement(By.xpath("//input[@id='travel_date']")).click();

//access element with class "day"
List<WebElement> dates = driver.findElements(By.className("day"));

【讨论】:

    【解决方案3】:

    当您尝试单击该元素时,该元素不可见。

    在课程开始时声明:

    WebDriverWait wait = new WebDriverWait(driver, 20);
    

    然后,在单击元素之前插入:

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//body/div[4]/div[@class='datepicker-days']/table//th[@class='datepicker-switch']")));
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 1970-01-01
      • 2021-12-20
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多