【问题标题】:Why Can't found this element with WebDriver?为什么用 WebDriver 找不到这个元素?
【发布时间】:2015-05-18 21:36:44
【问题描述】:

我开始使用 WebDriver 和 Java 进行 UI 自动化。当我尝试选择组合框的元素时遇到问题。这是代码:

WebDriver driver = new FirefoxDriver();
driver.get("http://intersite.com/");
new Select(driver.findElement(By.xpath(".//*[@id='term']"))); //Exception happens in this line org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='term']"}

这是网站上的代码(我用Firepath知道Xpath):

<select name="term" onchange="getTipDoc('');" id="term" class="termination"><option value="">-- Select an Option --</option>
                            <option value="OPT1">Option 1</option>
<option value="OPT2">Option2</option>
</select>

我在标签选择中看到,ID 属性是正确的,但总是发生异常。我尝试使用其他方法来定位像“By.id”这样的元素,但也不起作用。我能做什么?

问候!

【问题讨论】:

    标签: java xpath selenium-webdriver


    【解决方案1】:

    在这种情况下可能会发生几个可能的原因

    • 您要查找的元素位于iframe 中。使用driver.switchTo().frame(driver.findElement(somethting));
    • 元素查找比加载时间快。在这种情况下,使用显式等待。 WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("term")));this
    • 存在重复的 ID。尝试使用 select[id='term'][class='termination'] 作为 cssSelector

    当然也可以使用By.id(),因为 id 可用。

    【讨论】:

    • 你好@Saifur,可能是第一点。 “某事”是什么意思?
    • 类似By.xpath/By.cssSelector()
    • 我正在写 [code]driver.switchTo().frame(driver.findElement(By.id("term")));[/code] 但是没有用。 :(
    • 好吧,那不是iframeiframe 是一个通常包含一堆其他标签的标签。见this
    • 是的!我在源代码中找到了一个“框架集”,我切换到它,现在它可以工作了!谢谢!
    【解决方案2】:

    在尝试获取其元素之前,您需要等待页面加载,此代码将帮助您做到这一点

    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='term']")));
    

    【讨论】:

    • 是的,我之前添加了一个 Thread.sleep(10000)。我尝试了你的答案,但问题仍然存在。
    猜你喜欢
    • 2021-12-21
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2018-09-19
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多