简体   繁体   中英

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

Here is a button on the page:

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

When I try to find it using the following code:

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

It returns null.

If I try the following XPath:

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

then I get an exception.

How to find such a button?

试试看,

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

As per the HTML you have shared to find the element with text as Add Section as the element is a React Element you have to induce WebDriverwait for the element to be visible and you can use either of the following 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']"))); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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