I use the code
driver.findElement(By.name("username")).sendKeys("name");
drive开发者_如何转开发r.findElement(By.name("password")).sendKeys("12345");
to login to a website. Sometimes it will work, sometimes it won't, the error given is
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"username"}
The problem is that sometimes it will work. Should I perhaps use Byxpath()
?
You can use WebDriverWait with conditions to wait for Elements:
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()
}
With NameExpectedCondition:
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;
}
}
Please make also sure you're searching for the element in the correct frame.
You might not be waiting till the element loads in the page. Its a good practice to use selenium.isElementPresent(locator)
or selenium.isVisible(locator)
before the sendKeys
or similar commands command execution.
There is the most simple way to solve this problem:
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 10));
It will handle all NoSuchElementExceptions just trying to refind an element.
Please add this command before you send FindElement
:
String strTemp = driver.PageSource;
You'll see the source doesn't load the whole page.
精彩评论