【问题标题】:Selenium finding element硒发现元素
【发布时间】:2014-08-23 04:52:43
【问题描述】:

我正在尝试查找元素,但出现错误 这是我的代码:

    driver.get(baseURL);
    driver.manage().timeouts().implicitlyWait(10 ,TimeUnit.SECONDS);
    driver.manage().window().maximize();
    //String parentHandle=driver.getWindowHandle();
    driver.findElement(By.linkText("Create Account")).click();
    System.out.println(driver.getCurrentUrl());

    //String currentWindow=driver.getWindowHandle();
    //driver.switchTo().window(currentWindow);
    //String currentURL=;
    //(currentURL);

    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
    }

    driver.findElement(By.xpath("//html/body/div/div[1]/div[1]/div/div/form/div[1]/input")).sendKeys("9051902811");


    driver.close();
    //driver.switchTo().window(parentHandle);

    }
    catch(NoSuchElementException nsee){
        System.out.println(nsee.toString());
  }

    System.exit(0);
}

我得到了例外:

无法定位元素 "method":"xpath","selector":"//html/body/div/div[1]/div[1]/div/div/form/div[1]/input "} 命令持续时间或超时:89 毫秒

请帮忙...

【问题讨论】:

  • 您能否显示您尝试访问的字段的 HTML?在尝试查找元素之前也让它休眠 2 秒,selenium 有时可以快速进入
  • @Decypher 这是可怕的建议。Selenium 有implicit and explicit waits 是有原因的。 OP - 尽管显示您尝试与之交互的字段的 HTML
  • 隐式等待有时会很快,就像有时睡眠一样。这是 selenium 的一个已知问题,将计时器调高只是为了调试

标签: java selenium


【解决方案1】:

根据您所展示的内容,很难确切地说出问题所在。这可能是几件不同的事情。

1) 元素是否存在?如果您显示 html,这将很快得到答复。

Xpath 非常脆弱并且非常容易出错。 如果可能的话,尝试使用不同的选择器,id 和 class 更可靠。 这是By 类的链接。

driver.findElement(By.id("id")).sendKeys("keys");
driver.findElement(By.className("className")).sendKeys("keys");

更具体的东西,当添加改变结构的内容时,它不会破坏测试,xpaths 肯定会让你的测试变得脆弱。


2) 输入框加载了吗?

Selenium 有时会尝试查找尚未加载的元素。 Explicit Waits 将帮助解决这个问题,您可以使用这些等待以及 ExpectedConditions 来等待元素可见、可点击、不可见等。 不要使用 thread.sleep 除非没有其他选择(可能有)。

下面的代码可以用来等待元素可见。

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


WebDriverWait wait = new WebDriverWait(driver, seconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By
            .xpath(xpath)));

您可以使用它来确保元素对 xpath 可见,但如果可能,您应该考虑使用不同的选择器,该选择器不会使您的测试非常可见。如果元素没有 id/class,您也可以将 xpath 锚定到更可靠的选择器,以减少一些脆弱性。 如果您提供 html,我将很乐意提供更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    相关资源
    最近更新 更多