【问题标题】:org.openqa.selenium.NoSuchElementException: Unable to locate element error while locating an element to extract the text using Selenium and Javaorg.openqa.selenium.NoSuchElementException: Unable to locate element error while locating an element to extract the text using Selenium and Java
【发布时间】:2020-05-13 01:03:57
【问题描述】:

我想使用 selenium 编写一些文本,但我看到了很多错误而不是输出。但是,该代码以前有效,我有这种感觉。我没有覆盖代码的任何部分。 我不知道出了什么问题。 我对输出了解不多。你了解错误输出吗?

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   addons.webextension.doh-rollout@mozilla.org WARN    Loading extension 'doh-rollout@mozilla.org': Reading manifest: Invalid extension permission: networkStatus
1580136956926   addons.webextension.screenshots@mozilla.org WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: mozillaAddons
1580136956927   addons.webextension.screenshots@mozilla.org WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: telemetry
1580136956927   addons.webextension.screenshots@mozilla.org WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: resource://pdf.js/
1580136956927   addons.webextension.screenshots@mozilla.org WARN    Loading extension 'screenshots@mozilla.org': 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

【问题讨论】:

  • 错误消息的 TL;DR 是不存在您正在使用的 XPath 可以找到的元素。页面是否发生了变化?

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

要提取文本 Business,您需要为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());
    

【讨论】:

  • 好的,我也可以使用绝对 xpath 吗?
  • @david751 不推荐。您可以从 absolute xpath 开始,但每天都需要过渡到 relative xpath
  • 是的,我知道绝对 xpath 很长,但我找不到代码不应该运行的任何原因...如果我使用 try 和 Exception。
【解决方案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]

【讨论】:

  • 但是为什么元素无法定位?因为 chromepath 向我展示了这个绝对的 xpath。我的绝对 xpath 是正确的。
  • 虽然不应使用绝对 xpaths!它们的变化比季节更快。
  • 我对 cnn 页面并不特别感兴趣。这只是我想知道的一个例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-27
  • 2022-12-19
相关资源
最近更新 更多