简体   繁体   中英

How to locate the element within the HTML through Selenium and C#

I'm new to c# and I'm having problems locating elements. I don't quite understand how to find relative xpaths. I'm trying to locate an element. My code is listed below:

IWebElement webElement = driver.FindElement(By.XPath("Nothing I put here works"));
Thread.Sleep(1000);
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

Here is what I'm trying to find:

<li _ngcontent-c2="" class="header-item person-search ng-tns-c2-1 ng-star-inserted" ngbdropdown="" ngbtooltip="Person Search" placement="left">
    <a _ngcontent-c2="" class="dropdown-toggle dropdown-toggle" aria-haspopup="true" href="javascript:void(0)" ngbdropdowntoggle="" aria-expanded="false">
        <span _ngcontent-c2="" class="fa fa-search-plus block"></span>
    </a>
</li>

The desired element is an Angular element so to locate the element you have to induce WebDriverWait with ExpectedConditions as ElementToBeClickable Method (By) and you can use either of the following solutions:

  • CssSelector :

     IWebElement webElement = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("li.header-item.person-search.ng-star-inserted[ngbtooltip='Person Search']>a.dropdown-toggle>span.fa.fa-search-plus.block"))).Click(); 
  • XPath :

     IWebElement webElement = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//li[@class='header-item person-search ng-tns-c2-1 ng-star-inserted' and @ngbtooltip='Person Search']//a[@class='dropdown-toggle dropdown-toggle']/span[@class='fa fa-search-plus block']"))); 

Update

If you are using nuget , search for DotNetSeleniumExtras.WaitHelpers and import that namespace into your class and you can do this:

new WebDriverWait(driver, new TimeSpan(0, 0, 30)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("elementID")));

You can find a relevant discussion in C# Selenium 'ExpectedConditions is obsolete'

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