我无法让我的自动化测试用例在“第一”行之后运行。

huangapple go评论87阅读模式
英文:

I cant get my automation testcase to run past the "first" line

问题

我正在为我的工作创建一个自动化测试套件,但目前无法使其在第一行之后运行,即:

"driver.findElement(By.id("username")).sendKeys("example");

我决定尝试使用谷歌看看是否能有所进展,以下是我最初开始的代码:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class fgiLogin {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webDriver.chrome.driver",
                "C:\\Users\\examplefolder\\Documents\\examplefolder\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://google.com");

        driver.manage().window().maximize();

        Thread.sleep(5000);

        driver.findElement(By.className("gLFyf")).sendKeys("fruit");
        driver.findElement(By.name("ntnK")).click();

        driver.close();
    }
}

在将单词"fruit"输入到谷歌搜索栏后,测试就失败了。

这是我在IntelliJ中得到的错误信息:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Starting ChromeDriver 110.0.5481.77 (65ed616c6e8ee3fe0ad64fe83796c020644d42af-refs/branch-heads/5481@{#839}) on port 10097
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1677870261.213][WARNING]: virtual void DevToolsClientImpl::AddListener(DevToolsEventListener *) subscribing a listener to the already connected DevToolsClient. Connection notification will not arrive.
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"*[name='ntnK']"}
  (Session info: chrome=110.0.5481.178)
For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
Build info: version: '4.8.1', revision: '8ebccac989'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '19.0.2'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [2937306020c9aa7bccf03e80ec05305a, findElement {using=name, value=ntnK}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 110.0.5481.178, chrome: {chromedriverVersion: 110.0.5481.77 (65ed616c6e8e..., userDataDir: C:\Users\ne1723\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: localhost:50557}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://localhost:50557/devtoo..., se:cdpVersion: 110.0.5481.178, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: 2937306020c9aa7bccf03e80ec05305a
	at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:484)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)
	at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)
	at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167)
	at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142)
	at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
	at org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:162)
	at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:66)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
	at fgiLogin.main(fgiLogin.java:20)

Process finished with exit code 1

如何让代码能够在将键发送到搜索栏的初始行之后正常工作?

我尝试更改driver.getidclassnamename等,我想要点击谷歌搜索按钮并关闭驱动程序,与预期相符。搜索栏将输入"fruit",但自动化测试就会失败。

英文:

I'm creating an automated test suite for my job and currently I can't get it to run past the first line i.e

"driver.findElement(By.id("username")).sendKeys("example");

I decided to try google to see if i could make any headway and this is the code i started out with

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class fgiLogin {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webDriver.chrome.driver",
"C:\\Users\\examplefolder\\Documents\\examplefolder\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://google.com");

        driver.manage().window().maximize();

        Thread.sleep(5000);


        driver.findElement(By.className("gLFyf")).sendKeys("fruit");
        driver.findElement(By.name("ntnK")).click();

        driver.close();
    }

}

After the word fruit is placed into the google search bar thats where the test is failing.

this is the error set i get in intellij

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Starting ChromeDriver 110.0.5481.77 (65ed616c6e8ee3fe0ad64fe83796c020644d42af-refs/branch-heads/5481@{#839}) on port 10097
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1677870261.213][WARNING]: virtual void DevToolsClientImpl::AddListener(DevToolsEventListener *) subscribing a listener to the already connected DevToolsClient. Connection notification will not arrive.
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"*[name='ntnK']"}
  (Session info: chrome=110.0.5481.178)
For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
Build info: version: '4.8.1', revision: '8ebccac989'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '19.0.2'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [2937306020c9aa7bccf03e80ec05305a, findElement {using=name, value=ntnK}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 110.0.5481.178, chrome: {chromedriverVersion: 110.0.5481.77 (65ed616c6e8e..., userDataDir: C:\Users\ne1723\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: localhost:50557}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://localhost:50557/devtoo..., se:cdpVersion: 110.0.5481.178, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: 2937306020c9aa7bccf03e80ec05305a
	at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:484)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)
	at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)
	at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167)
	at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142)
	at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
	at org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:162)
	at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:66)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
	at fgiLogin.main(fgiLogin.java:20)

Process finished with exit code 1

How can i get the code to work past the initial line of sending the keys to the search bar?

Tried to change the driver.get to id, classname, name, and etc. I want the google search button to click and the driver to close as expected. The search bar will enter fruit and the automation breaks.

答案1

得分: 0

一旦通过`get()`方法调用URL,然后立即尝试在`username`字段中调用`sendKeys()`方法,`username`字段可能尚未完全[渲染](https://stackoverflow.com/a/47237075/7429447)。

解决方案
--------
理想情况下,在`Username`字段中发送字符序列,您需要使用[WebDriverWait](https://stackoverflow.com/a/48990165/7429447)来等待[_elementToBeClickable()_](https://stackoverflow.com/a/63301869/7429447),并且可以使用以下任一[_定位策略_](https://stackoverflow.com/a/48056120/7429447):

- 使用_id_:

  ```java
  new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id("username"))).sendKeys("jetswept");
  • 使用_cssSelector_:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("#username"))).sendKeys("jetswept");
    
  • 使用_xpath_:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='username']"))).sendKeys("jetswept");
    

<details>
<summary>英文:</summary>

Once you invoke an url through _`get()`_ and then immediately try to invoke _`sendKeys()`_ within the _username_ field, the _username_ field may not have completely [rendered](https://stackoverflow.com/a/47237075/7429447).


----------


Solution
--------
Ideally, to send a character sequence within an _Username_ field you need to induce [WebDriverWait](https://stackoverflow.com/a/48990165/7429447) for the [_elementToBeClickable()_](https://stackoverflow.com/a/63301869/7429447) and you can use either of the following [_locator strategies_](https://stackoverflow.com/a/48056120/7429447):

- Using _id_:

	  new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id(&quot;username&quot;))).sendKeys(&quot;jetswept&quot;);

- Using _cssSelector_:

	  new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector(&quot;#username&quot;))).sendKeys(&quot;jetswept&quot;);
	
- Using _xpath_:

	  new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath(&quot;//*[@id=&#39;username&#39;]&quot;))).sendKeys(&quot;jetswept&quot;);

</details>



huangapple
  • 本文由 发表于 2023年3月4日 03:15:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定