【问题标题】:c# selenium How to click on a checkboxc# selenium 如何点击一个复选框
【发布时间】:2018-09-27 04:57:51
【问题描述】:

我想通过 C# 和 Selenium 单击一个复选框。复选框 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()

【问题讨论】:

  • 从 id 中删除“#”。所以说:driver.FindElement(By.Id("postRulesCheck"))
  • 元素不可见
  • 使用javascript执行器点击

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


【解决方案1】:

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

  • 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();
    

【讨论】:

  • @HasanSarıkaya 根据您更新的 HTML 检查我的更新答案,并让我知道状态。
  • 非常感谢dude xpath选择是过程。每个人都非常感谢
【解决方案2】:

我不知道用 c 语言编码,但我认为它可以工作

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();

【讨论】:

  • 使用 isdisplayed 方法检查可见性
【解决方案3】:

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

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

这使您可以单击某个点,而与点的位置无关。

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多