繁体   English   中英

Selenium:如何从通过CssSelector或XPath提供的HTML中查找元素

[英]Selenium: How to find the element from the HTML provided through CssSelector or XPath

这是页面上的一个按钮:

<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\"]"));

然后我得到一个例外。

如何找到这样的按钮?

试试看,

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

按照您共享的HTML来查找带有添加部分的文本的元素,因为该元素是React元素,您必须诱使WebDriverwait使该元素可见,并且可以使用以下两种定位策略之一

  • 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']"))); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM