gpt4 book ai didi

java - Selenium 2 : something wrong with code “driver.findElement(By.name("username")). 发送 key ("");”

转载 作者:行者123 更新时间:2023-12-01 16:39:00 25 4
gpt4 key购买 nike

我使用代码

driver.findElement(By.name("username")).sendKeys("name");
driver.findElement(By.name("password")).sendKeys("12345");

登录网站。有时可以,有时不行,给出的错误是

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"username"}

问题是有时它会起作用。我应该使用 Byxpath() 吗?

最佳答案

您可以使用带有条件的 WebDriverWait 来等待元素:

public class MyTestClass{

private static final int MAX_WAIT_TIME_SEC = 60;
private WebDriverWait wait;
[...]

public void setField(String fieldname, String text){
wait = new WebDriverWait(driver, MAX_WAIT_TIME_SEC);
wait.until(new NameExpectedCondition(xpath));
WebElement element = driver.findElement(By.name(fieldname));
if(element != null){
element.sendKeys(text);
}
[...]
}

public void foo()
}

名称预期条件:

import org.openqa.selenium.By;

public class NameExpectedCondition implements ExpectedCondition<Boolean> {

private String fieldName;

public NameExpectedCondition(String fieldName)
{
this.fieldName= fieldName;
}

public Boolean apply(WebDriver d) {
d.findElement(By.Name(fieldName));
return Boolean.TRUE;
}

}

另请确保您正在正确的框架中搜索该元素。

关于java - Selenium 2 : something wrong with code “driver.findElement(By.name("username")). 发送 key ("");”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6104958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com