简体   繁体   English

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

[英]org.openqa.selenium.NoSuchElementException: Unable to locate element error while locating an element to extract the text using Selenium and Java

I would like to write some text using selenium but instead of output I see a lot of errors.我想使用 selenium 写一些文本,但我看到很多错误而不是输出。 However, the code worked before and I feel that.但是,该代码以前有效,我感觉如此。 I did not overwrite any part of code.我没有覆盖代码的任何部分。 I do not know what is wrong.我不知道出了什么问题。 I don't know much about the output.我对输出知之甚少。 Do you understand the faulty output?你了解错误输出吗?

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);

    }
}

There is my valid output:有我的有效输出:

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

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

This is certainly a tough xpath if you're just starting but if you want to click the "Business" button in the header it would be:如果您刚刚开始,这肯定是一个艰难的 xpath,但如果您想单击标题中的“业务”按钮,它将是:

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

As for all the error messages, I'm not sure why it's throwing them.至于所有的错误消息,我不确定为什么要抛出它们。 What's missing actually is the Exception that should be thrown when the findElement method failed.实际上缺少的是当 findElement 方法失败时应该抛出的异常。 I believe it should be a NoSuchElement Exception.我相信它应该是一个 NoSuchElement 异常。

Can you surround your code with a try/catch block and throw an Exception like so:你能不能用 try/catch 块包围你的代码并像这样抛出异常:

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

EDIT: Actually, it is throwing the NoSuchElementException.编辑:实际上,它正在抛出 NoSuchElementException。 I guess Geckodriver throws it in the midst of other log entries.我猜 Geckodriver 将它扔到其他日志条目中。 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]线程“main” 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]

To extract the text Business you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies :要提取文本Business,您需要为visibilityOfElementLocated()引入WebDriverWait ,您可以使用以下任一定位器策略

  • cssSelector : 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 : 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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element error using Selenium through Java - org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element error using Selenium through Java org.openqa.selenium.NoSuchElementException:无法找到元素错误 - org.openqa.selenium.NoSuchElementException: Unable to locate element error org.openqa.selenium.NoSuchElementException:没有这样的元素:尝试使用Java通过Selenium登录时无法找到元素 - org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element while trying to login through Selenium with Java org.openqa.selenium.NoSuchElementException:无法找到元素: - org.openqa.selenium.NoSuchElementException: Unable to locate element: org.openqa.selenium.NoSuchElementException:无法找到元素:-搜索字段 - org.openqa.selenium.NoSuchElementException: Unable to locate element:- Search field 无法找到元素:org.openqa.selenium.NoSuchElementException - Unable to locate element: org.openqa.selenium.NoSuchElementException webdriver org.openqa.selenium.NoSuchElementException:无法找到元素: - webdriver org.openqa.selenium.NoSuchElementException: Unable to locate element: org.openqa.selenium.NoSuchElementException:无法找到元素: - org.openqa.selenium.NoSuchElementException: Unable to locate element: org.openqa.selenium.NoSuchElementException无法找到element:method“:” link text“,” selector“:” http:// - org.openqa.selenium.NoSuchElementException Unable to locate element:method“:”link text“,”selector“:”http:// org.openqa.selenium.NoSuchElementException:无法使用XPATH定位Label元素 - org.openqa.selenium.NoSuchElementException: Unable to locate Label element using XPATH
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM