簡體   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

我想使用 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

您應該使用動態選擇器。 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 將它扔到其他日志條目中。 線程“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]

要提取文本Business,您需要為visibilityOfElementLocated()引入WebDriverWait ,您可以使用以下任一定位器策略

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM