Selenium入门指南,我做了什么错?

时间:2016-01-08 01:33:55

标签: java selenium nosuchelementexception

我尽可能地密切关注Selenium的“Getting Started Guide”,但是当我尝试运行时,我在控制台中收到很多警告和错误 码。 我还从here导入了selenium-java-2.48.2中的所有罐子。
非常感谢任何愿意透视这个并试着帮助我的人!
这是我的课程,我从指南中复制并粘贴。

Example.java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Example {
    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the
        // element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        driver.quit();
    }
}

GoogleSuggest.java

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript 
        WebDriver driver = new FirefoxDriver();

        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");

        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

        // Sleep until the div we want is visible or 5 seconds is over
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            WebElement resultsDiv = driver.findElement(By.className("gssb_e"));

            // If results have been returned, the results are displayed in a drop down.
            if (resultsDiv.isDisplayed()) {
              break;
            }
        }

        // And now list the suggestions
        List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[@class='gssb_a gbqfsf']"));

        for (WebElement suggestion : allSuggestions) {
            System.out.println(suggestion.getText());
        }

        driver.quit();
    }
}

运行'Example.java'时控制台中出现的内容

Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement addBehavior
WARNING: Unimplemented behavior: #default#userdata
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1419] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1467] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1478] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1488] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1499] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1510] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1601] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1613] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1626] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1639] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1653] Error in expression. (Invalid token "}". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2203] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2543] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2616] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3194] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3701] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3761] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:4196] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:4960] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6103] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6338] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6781] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6938] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:7010] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:7352] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:199] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:1691] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:2949] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:3481] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:3969] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:4480] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [3:117] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:685] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1235] Error in expression; ':' found after identifier "progid".
Page title is: Cheese! - Google Search

这个类做了它应该做的事情,即使它显示了一堆警告......

当我运行GoogleSuggest.java时控制台中出现的内容

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"gssb_e"}
Command duration or timeout: 9 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.0', revision: 'b7b081a', time: '2015-10-07 15:45:39'
System info: host: 'Zeus', ip: '192.168.7.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=40.0.3, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: f90cec4e-f47c-4306-9491-3248e836dd7c
*** Element info: {Using=class name, value=gssb_e}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:467)
    at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
    at GoogleSuggest.main(GoogleSuggest.java:23)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"gssb_e"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.0', revision: 'b7b081a', time: '2015-10-07 15:45:39'
System info: host: 'Zeus', ip: '192.168.7.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20'
Driver info: driver.version: unknown
    at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10659)
    at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10668)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12534)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12539)
    at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12481)

除了控制台中的所有功能外,该类还会打开FireFox,等待Google加载,键入奶酪,搜索,然后停止并显示所有错误。

2 个答案:

答案 0 :(得分:2)

运行Example.java时观察到的警告可以忽略,代码工作正常。如果您希望删除警告,可以添加以下代码行。

public class Example {
    static Logger log = Logger.getLogger("com.gargoylesoftware");

    public static void main(String[] args) {
        log.setLevel(Level.OFF)
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();
        ...................................
        ...................................
        ...................................
    }
}

我在GoogleSuggest.java中发现了一些问题。

  1. Sleep until the div we want is visible or 5 seconds is over编写的代码是错误的。根据您的代码,Selenium会查找元素,直到System.currentTimeMillis()小于end。但每次selenium寻找div时,会抛出一个异常,说找不到元素。这应该在try catch中处理。

  2. 在您的代码中使用类名resultsDiv标识gssb_e。当我检查时,我的班级名称为sbsb_a。请检查一下。

  3. list是由代码中的xpath //td[@class='gssb_a gbqfsf']获得的。当我检查时,没有td标签是相关的。请尝试以下xpath //div[@class='sbqs_c']

  4. 所需的代码更改摘要:

    while (System.currentTimeMillis() < end) {
        try {
            WebElement resultsDiv = driver.findElement(By.className("sbsb_a"));
    
            // If results have been returned, the results are displayed in a
            // drop down.
            if (resultsDiv.isDisplayed()) {
                break;
            }
        } catch (Exception e) {
            // do nothing 
        }
    }
    
    // And now list the suggestions
    List<WebElement> allSuggestions = driver.findElements(By.xpath("//div[@class='sbqs_c']"));
    

答案 1 :(得分:1)

只是警告,你可以忽略它们。

使用其他WEB驱动程序而不是默认驱动程序。例如,它可能是CHROME(您可以选择不同的浏览器,如CHROME,FIREFOX_31,FIREFOX_31,INTERNET_EXPLORER_8,INTERNET_EXPLORER_11)。

HtmlUnitDriver unitDriver = new HtmlUnitDriver(BrowserVersion.CHROME); 我想它应该解决你的问题。

相关问题