硒没有找到元素 [英] Selenium not finding element

查看:163
本文介绍了硒没有找到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是HTML:
https://www.dropbox .com / s / aiaw2u4j7dkmui2 / Untitled%20picture.png

我不明白为什么这段代码在页面上找不到该元素。该网站不使用iframe。

I don't understand why this code doesn't find the element on the page. The website doesn't use iframes.

@Test
public void Appointments() {
    driver.findElement(By.id("ctl00_Header1_liAppointmentDiary"));
}

这是我收到的错误消息:

this is the error message I get:

FAILED: Appointments
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"ctl00_Header1_liAppointmentDiary"}


推荐答案

这是时间问题吗? AJAX加载的元素(或整个页面)是?当你试图寻找它时,页面上可能没有它,WebDriver通常太快。

Is this a timing issue? Is the element (or the whole page) AJAX-loaded? It's possible that it's not present on the page when you're trying to look for it, WebDriver is often "too fast".

要解决它,要么隐式或显式等待

隐式等待方式。由于隐式等待集,这将尝试等待元素出现在页面上,如果它不立即出现(这是异步请求的情况),直到它超时并像往常一样抛出:

The Implicit Wait way. Because of the implicit wait set, this will try to wait for the element to appear on the page if it is not present right away (which is the case of asynchronous requests) until it times out and throws as usual:

// Sooner, usually right after your driver instance is created.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Your method, unchanged.
@Test
public void Appointments() {
    ...
    driver.findElement(By.id("ctl00_Header1_liAppointmentDiary")).doSomethingWithIt();
    ...
}

显式等待方式。这只会在查找时等待页面上出现这一个元素。使用 ExpectedConditions 类,您也可以等待不同的东西 - 元素可见,可点击等等:

The Explicit Wait way. This will only wait for this one element to be present on the page when looking for it. Using the ExpectedConditions class, you can wait for different things, too - the element to be visible, clickable etc.:

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

@Test
public void Appointments() {
    ...
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(presenceOfElementLocated(By.id("ctl00_Header1_liAppointmentDiary")))
        .doSomethingwithIt();
    ...
}

这篇关于硒没有找到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆