【问题标题】:Find element by xpath failing with certain values通过 xpath 查找元素失败并具有某些值
【发布时间】:2015-12-27 05:21:56
【问题描述】:

使用 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 均成功通过。

【问题讨论】:

  • 你的值是“01”、“02”的形式吗?
  • 您需要提供页面的相关 HTML 或指向它的链接,以便我们为您提供帮助。
  • 我在上面添加了 html 元素,其值的格式为“1”。我很难理解的是为什么它的工作原理是值是 15 而不是 2!
  • 什么是错误(消息)。 NoSuchElementException 之类的东西,或者更确切地说是“不可见”或“无法与之交互”之类的东西,甚至是 StaleElementReferenceException??
  • 错误是:OpenQA.Selenium.ElementNotVisibleException : element not visible

标签: selenium selenium-webdriver


【解决方案1】:

请参阅 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));

如果它不可见,请不要使用它。

【讨论】:

  • 感谢您的建议,我尝试了这两个建议,但行为没有改变,请参阅原始帖子中的编辑。
  • @Colin 正如我所说:如果它不可见(并且在一段时间后不可见)您不能使用该元素。您可以尝试执行一些 JavaScript 以使其可见。但这是一个完全不同的故事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2015-11-10
  • 2020-07-20
  • 2016-03-12
  • 2017-09-14
相关资源
最近更新 更多