簡體   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