【问题标题】:How to locate the element within the HTML through Selenium and C#如何通过 Selenium 和 C# 在 HTML 中定位元素
【发布时间】:2019-02-26 22:19:15
【问题描述】:

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

【问题讨论】:

  • 我强烈建议您将"Nothing I put here works" 替换为您所做的实际尝试(并且可能显示多次尝试以确保人们知道尝试了什么)。这样,更容易在方法调用中查明问题。
  • 我认为为您的页面上传整个 HTML 会很有帮助。

标签: c# selenium xpath css-selectors webdriverwait


【解决方案1】:

所需的元素是Angular 元素,因此要找到必须将WebDriverWaitExpectedConditions 诱导为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'找到相关讨论

【讨论】:

  • 这有帮助。如果我使用 CssCelector 方法,则必须将 Click() 移动到该行下方,例如“webElement.Click();”否则它会给出一个错误,不能将 void 转换为 Selenium.QA 等......只要 Click() 像上面所说的那样移动到下面,这两个语句都可以工作。我的一个问题是......它说明 ExpectedConditions 已经过时并且将被弃用。未来可以改成什么?
  • @christopherhe1 查看更新的答案并告诉我状态。
  • @christopherhe1 很高兴能为您提供帮助。 Upvote 答案如果这个/任何答案对您/对您有帮助,以造福未来的读者。
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多