如何通过Selenium和C#在HTML中定位元素

时间:2019-02-26 22:19:15

标签: c# selenium xpath css-selectors webdriverwait

我是C#的新手,在查找元素时遇到问题。我不太了解如何找到相对的xpath。我正在尝试查找元素。我的代码如下:

<SampleEditor text={text} context={'overview'}/>

这就是我要查找的内容:

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

1 个答案:

答案 0 :(得分:0)

期望的元素是Angular元素,因此要定位必须用WebDriverWait作为ExpectedConditions来归纳ElementToBeClickable Method (By)的元素,则可以使用以下任一解决方案:

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

更新

如果您使用的是nuget,请搜索DotNetSeleniumExtras.WaitHelpers并将该名称空间导入您的类中,您可以这样做:

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

您可以在C# Selenium 'ExpectedConditions is obsolete'

中找到相关的讨论