接收selenium.common.exceptions.NoSuchElementException:消息:无法找到元素消息

时间:2016-10-10 18:24:27

标签: java python-3.x

我是该网站的新手。我正在尝试选择/点击http://autotask.net上的元素。我试图使用以下方法找到元素:

driver.find_element_by_css_selector('#HREF_btnPrint> img:nth-​​child(1)') driver.find_element_by_xpath( 'browser.find_element_by_xpath('/ HTML /体/形式[1] / DIV [2] / DIV [1] / UL /锂[2] / A / IMG')

...但它在标题中给了我例外。

我可以在登录页面上找到正常的元素(即'用户名''密码'字段),但是一旦我登录,selenium就无法在页面上找到任何元素。

我现在只学习/编写python几周了,我对Java一无所知。如果您需要更多信息,请告诉我 - 谢谢。

1 个答案:

答案 0 :(得分:0)

我不确定python语法,所以我将使用Java代替。我认为有两种可能的情况,首先你的驱动程序在页面加载时调查DOM结构。另一个是Web驱动程序没有指向DOM的根目录。我通常使用wait方法等待页面加载完毕,并在查找某些元素之前切换到默认内容。

首先,我通过构造函数传递WebDriver,Element id和Element name。然后我有waitUntilReady()实现逻辑来检查特定超时内元素的存在。

    public void waitUntilReady() {
            WebDriverWait waiter = new WebDriverWait(getWebDriver(), 30);
            waiter.withMessage("\"" + getElementName() + "\" is not ready in 30 seconds")
                    .until(new Predicate<WebDriver>() {
                        @Override
                        public boolean apply(WebDriver input) {
                            /* isReady() returns true if all elements 
                             * that you need to test are available. 
                             * Note that if you have javascript, you 
                             * should have some hidden field to tell 
                             * you that the whole page has loaded. */
                            return isReady();
                        }
                    });
        }

以及在找到元素

之前切换到默认内容
WebElement getWebElement() {
    WebElement webElement;
    try {
        getWebDriver().switchTo().defaultContent();
        webElement = getWebDriver().findElement(By.id(elementId));
    } catch (NoSuchElementException ex) {
        getLogger().log(Level.SEVERE, "Element id '" + elementId + "' does not exist");
        throw ex;
    }
    return webElement;
}

如果它不起作用,你可以使用<body id="container">,然后使用driver.findElementById(“container”)。findElementById(“你的目标元素”)

相关问题