【问题标题】:Selenium: How to find the element from the HTML provided through CssSelector or XPathSelenium:如何从通过 CssSelector 或 XPath 提供的 HTML 中查找元素
【发布时间】:2018-06-03 07:27:48
【问题描述】:

这是页面上的一个按钮:

<button data-purpose="add-section-btn" type="button" 
        class="ellipsis btn btn-default btn-block">
   <span class="a3 udi udi-plus-square"></span>
   <!-- react-text: 255 --> <!-- /react-text -->
   <!-- react-text: 256 -->Add Section<!-- /react-text -->
</button>

当我尝试使用以下代码找到它时:

var btns = _driver.FindElements(By.TagName("button"));
var sectionTitle = btns.Where(x => x.GetAttribute("data-purpose") == "add-section-btn");

它返回空值。

如果我尝试以下 XPath:

var btn = _driver.FindElement(By.XPath("//button[data-purpose=\"add-section-btn\"]"));

然后我得到一个异常。

如何找到这样的按钮?

【问题讨论】:

  • 你试过LinkText吗?
  • 你能粘贴你得到的异常吗?详细的堆栈跟踪。

标签: c# selenium selenium-webdriver xpath css-selectors


【解决方案1】:

试试看,

var btn = _driver.FindElement(By.XPath("//button[@data-purpose='add-section-btn']"));

【讨论】:

    【解决方案2】:

    根据您共享的 HTML,以查找文本为 Add Section 的元素,因为该元素是 React Element,您必须诱导 WebDriverwait 使 元素可见,您可以使用以下任一 Locator Strategies:

    • CssSelector

      var btn = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("button.ellipsis.btn.btn-default.btn-block[data-purpose='add-section-btn']")));
      
    • XPath

      var btn = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//button[@class='ellipsis btn btn-default btn-block' and @data-purpose='add-section-btn'][normalize-space()='Add Section']")));
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多