如何使用 Selenium C# 单击按钮

How to click on the button with Selenium C#

我需要使用 selenium 来点击按钮,但我遇到了一些问题

我尝试了这段代码,但显示错误 "Selenium.InvalidSelectorException: 'invalid selector"

IList link = driver.FindElements(By.ClassName("button postfix"));

        foreach (IWebElement elem in link)
        {
            if (elem.GetAttribute("ng-click").Equals("quickSearch.search()"))
                elem.Click();
        }

html 页面代码

<a href="javascript: void(0);" class="button postfix" ng-click="quickSearch.search()" analytics-on="click" analytics-event="InventoryManagementSearchKeyword" sc-omniture-props="InventoryManagementAllSS"><i class="fi-magnifying-glass"></i></a>

我尝试使用 id,但是按钮没有 Id,所以我不知道如何使用它

您可以使用 Xpath。

 driver.FindElement(By.XPath("//a[@class='button postfix' and @ng-click='quickSearch.search()']")).Click();

因为元素是 Angular element so to invoke click() on the desired element you have to induce WebDriverWait for the ElementToBeClickable and you can use either of the following :

  • CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("a.button.postfix[ng-click^='quickSearch'][analytics-event='InventoryManagementSearchKeyword']"))).Click();
    
  • XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//a[@class='button postfix' and starts-with(@ng-click, 'quickSearch')][@analytics-event='InventoryManagementSearchKeyword']"))).Click();