我正在使用Selenium WebDriver并且它工作正常,今天如果我使用下面的代码或者收到错误Unable to find element with id == //*[@id='ctl00_ContentPlaceHolder1_AddControl1_txtName']
我尝试使用它:
public IWebElement GetElementId(string id)
{
//return Driver.FindElement(By.Id(id));
Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(TimeOut));
return Driver.FindElement(By.Id(id));
}
并尝试了这个:
public IWebElement GetElementId(string id)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement category = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id(el_id));
});
}
我仍然无法想出如何避免超时或元素未找到错误
任何帮助?
答案 0 :(得分:5)
尝试使用FluentWait类:
public WebElement fluentWait( final By locator ) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
// use a "custom" ExpectedCondition
WebElement foo = wait.until( new Function<WebDriver, WebElement>() {
public WebElement apply( WebDriver driver ) {
return driver.findElement( locator );
}
});
// usually use one of the built-in ExpectedCondtions
// WebElement foo = wait.until(
// ExpectedConditions.visibilityOfElementLocated( locator );
return foo;
};
你可以阅读流利的等待here
如果没有正确找到定位器,如果没有彻底检查。
希望这可以帮助你)
答案 1 :(得分:1)
您正在使用xpath,但在您使用的findElement中,我将其更改为
By.xpath("//*[@id='ctl00_ContentPlaceHolder1_AddeCardControl1_txtName']")
OR
By.id("ctl00_ContentPlaceHolder1_AddeCardControl1_txtName")
如果它仍然显示超时错误,那么尝试在xpath中指定元素名称,如
//div[@id='element_id']
因为像这样指定
//*[@id='ctl00_ContentPlaceHolder1_AddeCardControl1_txtName']
可能需要花时间搜索所有元素id属性,因此如果指定特定元素,则搜索时间将最小化。
如果不起作用,请检查您的xpath是否正确。