【问题标题】:NoSuchElementException while using Xpath with HtmlUnitDriver将 Xpath 与 HtmlUnitDriver 一起使用时出现 NoSuchElementException
【发布时间】:2015-06-12 11:41:00
【问题描述】:

我需要在 Linux 机器上运行 Selenium 并使用 HtmlUnitDriver 来实现。

Selenium 脚本包含大部分 Xpath 来查找元素。运行时,NoSuchElementException 会显示在使用 xpath 的位置。

org.openqa.selenium.NoSuchElementException: Unable to locate a node using //*[contains(text(),'Sample Text')]
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html

相同的代码在 Chrome、Firefox 或 IE 等其他驱动程序上运行良好。

我的代码如下所示,

 HtmlUnitDriverdriver = new HtmlUnitDriver();
    driver.setJavascriptEnabled(true);
    driver.get("http://example.com");
    driver.findElement(By.id("username")).sendKeys("xxx");
    driver.findElement(By.id("password")).sendKeys("yyy");
    driver.findElement(By.id("loginButton")).click();
    Thread.sleep(2000);
    driver.findElement(By.xpath("//*[contains(text(),'Sample Text')]")).click();

我发现了许多类似的问题,解决方案是提供睡眠时间或等待元素直到它被加载。我提供了一切,但在使用 xpath 时仍然面临这个问题。

在我的用例中也无法通过 ID 或名称查找元素,因为它每次都不同。

我只能使用 xpath 来查找 span 标签内的文本。

我需要一个解决方案来处理这个问题。提前致谢!

编辑:

我尝试了相同的gmail登录,但仍然遇到同样的问题,

driver.get("http://www.gmail.com");
        driver.findElement(By.id("Email")).sendKeys("xxx@gmail.com");
        driver.findElement(By.id("next")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("Passwd")).sendKeys("yyy");
        driver.findElement(By.id("signIn")).click();
        Thread.sleep(8000);
        driver.findElement(By.xpath("//*[contains(text(),'COMPOSE')]")).click();

【问题讨论】:

  • iframe在场吗?'
  • 没有。 iframe 不可用
  • 能否发一下网址
  • 抱歉,我正在处理我的应用程序,我无法公开网址
  • 另外,使用 Sleeper.sleepTight 代替 Thread.sleep...

标签: selenium xpath selenium-webdriver htmlunit-driver


【解决方案1】:

考虑同时删除text(),这可能会导致此类问题。改用这个:

contains(., 'Sample Text')

如果您在这里遇到问题,不确定这是不是原因,鉴于您提供给我们的信息很少,这更像是盲目的。

【讨论】:

    【解决方案2】:

    我首先建议提供更有效的显式等待,以便在满足条件之前暂停,如果您没有提供足够长的超时,也会给您 TimeoutException。

    //This will store your locator for later use
    By elementLocator = By.xpath("//*[contains(text(),'Sample Text')]");
    
    //This creates a reusable wait object
    WebDriverWait wait = new WebDriverWait(browser.driver, 15);
    
    //Waiting is stopped right after the condition is satisfied or timeout (set in the previous line, in secs) was reached
    wait.until(ExpectedConditions.elementToBeClickable(elementLocator));
    

    如果你遇到同样的错误,你可以试试这个

    try {
        wait.until(ExpectedConditions.elementToBeClickable(elementLocator));
    } catch (org.openqa.selenium.TimeoutException e) {
        System.out.println(driver.getPageSource());
    }
    

    查看该元素是否存在于您正在查找的页面上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多