c#selenium如何点击复选框

时间:2018-04-17 09:28:02

标签: c# selenium selenium-webdriver xpath css-selectors

我想通过C#和Selenium点击一个chechbox。复选框HTML如下:

<div class="ad-post-rules" ng-class="{'ad-post-rules-error': submitted &amp;&amp; addClassifiedForm.postRulesCheck.$error.required}" an-form-error="" an-form-error-optional-text="İlan verme kurallarını onaylamadınız."><input id="postRulesCheck" class="checkBox sg-checkbox ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" type="checkbox" value="1" name="postRulesCheck" ng-model="postRulesCheck" required="" an-form-object-name="İlan Verme Kuralları"><label for="postRulesCheck"></label><span class="rulesOpen" ng-click="adPostRules=true">İlan verme kurallarını</span><label for="postRulesCheck">okudum, kabul ediyorum</label></div>

我的代码如下:

Dim cekbul As IWebElement
System.Threading.Thread.Sleep(1000)
cekbul = driver.FindElement(By.Id("#postRulesCheck"))
cekbul.Click()

3 个答案:

答案 0 :(得分:0)

要单击复选框,因为元素是 Angular 元素,您必须引导 WebDriverWait 以使elelemt可单击,并且您可以使用以下任一选项:

  • CssSelector

    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.checkBox.sg-checkbox.ng-pristine.ng-untouched.ng-empty.ng-invalid.ng-invalid-required#postRulesCheck"))).Click();
    
  • XPath

    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@class='checkBox sg-checkbox ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required' and @id='postRulesCheck']"))).Click();
    

答案 1 :(得分:0)

Selenium只能点击对人类可见的元素。即使元素不可见,您仍然可以执行javascript。如果在您尝试执行测试时该元素对于人类是可见的,并且您仍然获得该元素不可见的异常,请尝试使用Actions API,否则使用javascript。

 Actions action = new Actions(driver);
 IWebElement cekbul = driver.FindElement(By.Id("postRulesCheck"));
 action.Click(cekbul).Build().Perform();

这使您无论点的位置如何都可以点击一个点。

答案 2 :(得分:0)

我不知道c sharp的编码,但我认为它有效

IWebElement Ele_CheckBox = driver.FindElement(By.Id("postRulesCheck"));

Ele_CheckBox.Click();

使用名称

IWebElement Ele_CheckBox = driver.FindElement(By.Name("postRulesCheck"));

Ele_CheckBox.Click();

按xpath

IWebElement Ele_CheckBox = driver.FindElement(By.Xpath("//input[@id='postRulesCheck']"));

Ele_CheckBox.Click();