org.openqa.selenium.NoSuchElementException:在定位要使用Selenium和Java提取文本的元素时无法定位元素错误

问题描述 投票:1回答:3

我想用硒写一些文本,但是我看到很多错误,而不是输出。但是,该代码之前曾奏效,我对此感到满意。我没有覆盖任何代码部分。我不知道怎么了。我对输出了解不多。您了解错误的输出吗?

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
import java.time.Duration;

public class project_selenium {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        System.setProperty("webdriver.gecko.driver", "C:\\Users\\david\\Desktop\\dotazy\\geckodriver-v0.26.0 win64\\geckodriver.exe");

        driver.get("https://edition.cnn.com/");

        WebElement word1 = driver.findElement(By.xpath("/html[1]/body[1]/div[5]/div[1]/div[1]/header[1]/div[1]/div[1]/div[1]/div[2]/nav[1]/ul[1]/li[3]/a[1]")); 
        System.out.println(word1.getText());
        //should return word "Business"

        WebElement word2 = driver.findElement(By.className("politics"));
        System.out.println(word2.getText());
        //should return word "US Politics"

        String currentURL = driver.getCurrentUrl();
        System.out.println(currentURL);

    }
}

有我的有效输出:

1580136956525   mozrunner::runner   INFO    Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "-marionette" "-foreground" "-no-remote" "-profile" "C:\\Users\\david\\AppData\\Local\\Temp\\rust_mozprofileduNDR7"
1580136956833   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: networkStatus
1580136956926   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: mozillaAddons
1580136956927   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: telemetry
1580136956927   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: resource://pdf.js/
1580136956927   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: about:reader*
JavaScript error: resource://gre/modules/XULStore.jsm, line 66: Error: Can't find profile directory.
1580136959269   Marionette  INFO    Listening on port 61686
1580136959745   Marionette  WARN    TLS certificate errors will be ignored for this session
led 27, 2020 3:55:59 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
JavaScript warning: https://confiant-integrations.global.ssl.fastly.net/gpt/202001101133/wrap.js, line 8: unreachable code after return statement
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: /html[1]/body[1]/div[5]/div[1]/div[1]/header[1]/div[1]/div[1]/div[1]/div[2]/nav[1]/ul[1]/li[3]/a[1]
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'DESKTOP-7SSQHFU', ip: '192.168.31.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '13'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 72.0.2, javascriptEnabled: true, moz:accessibilityChecks: false, moz:buildID: 20200117190643, moz:geckodriverVersion: 0.26.0, moz:headless: false, moz:processID: 19352, moz:profile: C:\Users\david\AppData\Loca..., moz:shutdownTimeout: 60000, moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, platformVersion: 10.0, rotatable: false, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: c96eed46-c306-4563-9346-c7016b1ee855
*** Element info: {Using=xpath, value=/html[1]/body[1]/div[5]/div[1]/div[1]/header[1]/div[1]/div[1]/div[1]/div[2]/nav[1]/ul[1]/li[3]/a[1]}
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at project_selenium.main(project_selenium.java:20)
Process finished with exit code 1
java selenium xpath css-selectors webdriverwait
3个回答
2
投票

您应该使用动态选择器。 http://pragmatictestlabs.com/2018/05/16/mastering-xpath-for-selenium-test-automation/

如果您只是开始,这肯定是一个艰难的xpath,但是如果您想单击标题中的“业务”按钮,它将是:

driver.findElement(By.xpath("//header[@id='header-nav-container'] //div[contains(@class,'NavGrid')] [not(@style='false:unset')]//a[text()='Business']"));

关于所有错误消息,我不确定为什么会抛出错误消息。实际上缺少的是findElement方法失败时应引发的异常。我相信这应该是NoSuchElement异常。

您可以用try / catch块包围代码并抛出异常,如下所示:

try {
//code
} catch (Exception e) {
System.out.println(e) 
}

编辑:实际上,它抛出NoSuchElementException。我猜Geckodriver会将它扔在其他日志条目中。线程“主”中的异常org.openqa.selenium.NoSuchElementException:无法找到元素:/ html [1] / body [1] / div [5] / div [1] / div [1] / header [1] / div [1] / div [1] / div [1] / div [2] / nav [1] / ul [1] / li [3] / a [1]


0
投票

要提取文本 业务,您需要为visibilityOfElementLocated()引入WebDriverWait,并且可以使用以下任何一个Locator Strategies

  • cssSelector

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li[data-section='business']>a[name='business'][data-analytics='header_top-nav']"))).getText());
    
  • xpath

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[@data-section='business']/a[@name='business' and @data-analytics='header_top-nav']"))).getText());
    

0
投票

此具有相对xpath的代码正在运行。

public class project_selenium {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        System.setProperty("webdriver.gecko.driver", "C:\\Users\\david\\Desktop\\dotazy\\geckodriver-v0.26.0 win64\\geckodriver.exe");

        try {
            driver.get("https://edition.cnn.com/");
            System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("/System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li[data-section='business']>a[name='business'][data-analytics='header_top-nav']"))).getText());


        } 
        catch (Exception e) {
            System.out.println(e);
        }


    }
}

但是如果我更改相对的xpath:

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li[data-section='business']>a[name='business'][data-analytics='header_top-nav']"))).getText());

到绝对xpath:

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("/html[1]/body[1]/div[5]/div[1]/div[1]/header[1]/div[1]/div[1]/div[1]/div[2]/nav[1]/ul[1]/li[3]/a[1]"))).getText());

我看到输出:

1580224582098   mozrunner::runner   INFO    Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "-marionette" "-foreground" "-no-remote" "-profile" "C:\\Users\\david\\AppData\\Local\\Temp\\rust_mozprofileKslex2"
1580224582407   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: networkStatus
1580224582495   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: mozillaAddons
1580224582495   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: telemetry
1580224582495   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: resource://pdf.js/
1580224582495   [email protected] WARN    Loading extension '[email protected]': Reading manifest: Invalid extension permission: about:reader*
JavaScript error: resource://gre/modules/XULStore.jsm, line 66: Error: Can't find profile directory.
1580224584812   Marionette  INFO    Listening on port 58663
1580224584830   Marionette  WARN    TLS certificate errors will be ignored for this session
led 28, 2020 4:16:24 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.cssSelector: /html[1]/body[1]/div[5]/div[1]/div[1]/header[1]/div[1]/div[1]/div[1]/div[2]/nav[1]/ul[1]/li[3]/a[1] (tried for 20 second(s) with 500 milliseconds interval)

Abs_xpath是正确的:https://imgur.com/Wc5OQg0

我该如何选择abs_xpath?

*我对cnn页面没有特别的兴趣。这只是我一般想知道的一个例子

© www.soinside.com 2019 - 2024. All rights reserved.