我是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>
所需的元素是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'找到相关的讨论