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

问题描述 投票:0回答:1

我是c#的新手,我在查找元素方面遇到了问题。我不太明白如何找到相对的xpath。我正在尝试找到一个元素。我的代码如下:

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

这是我想要找到的:

<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>
c# selenium xpath css-selectors webdriverwait
1个回答
0
投票

所需的元素是Angular元素,所以要找到你必须用WebDriverWait作为ExpectedConditions诱导ElementToBeClickable Method (By)的元素,你可以使用以下任一解决方案:

  • CssSelectorIWebElement 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();
  • XPathIWebElement 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'找到相关的讨论

© www.soinside.com 2019 - 2024. All rights reserved.