按xpath查找元素失败并显示某些值

时间:2015-09-29 16:10:18

标签: selenium selenium-webdriver

使用selenium webdriver和C#,当我尝试使用下面的代码查找元素并且defaultLocationID1-9范围内(即单个数字)时,它会失败。

但是,如果defaultLocationID10或更高(即多位数),则成功。

_webDriver.FindElement(By.XPath("//input[@value='" + defaultLocationID + "']")).Click();

除了确保ID是10还是以上之外,有没有人经历过这种情况并想出一个解决方法?

我想找的元素是:

<li><input type="checkbox" value="2"> LocationName</li>

为了回应Würgspaß的回答,我尝试了以下内容:

WebDriverWait wait = new WebDriverWait(_webDriver, TimeSpan.FromSeconds(20));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//input[@value='2']")));
_webDriver.FindElement(By.XPath("//input[@value='2']")).Click();
commonFunctions.ClickButtonOrLink(_webDriver, "save-btn");

这失败了:

OpenQA.Selenium.WebDriverTimeoutException : Timed out after 20 seconds

还尝试了:

WebDriverWait wait = new WebDriverWait(_webDriver, TimeSpan.FromSeconds(20));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
        return d.FindElement(By.XPath("//input[@value='2']"));
});
_webDriver.FindElement(By.XPath("//input[@value='2']")).Click();
commonFunctions.ClickButtonOrLink(_webDriver, "save-btn");

此失败并出现与以前相同的错误。

用11替换值都成功通过。

1 个答案:

答案 0 :(得分:0)

请参阅Selenium文档,了解如何使用explicit waits

等待元素可点击的Java方式是这样的(在C#中它应该是类似的):

//30s timeout, use timeout not sleep
WebDriverWait wait = new WebDriverWait(driver, 30); 
By xpath = By.xpath("//input[@value='" + defaultLocationID + "']");
//wait for element to be clickable, then click
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(xpath));

或者等待可见性:

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(xpath));

如果看不到,请不要使用它。

相关问题