無法使用Selenium WebDriver單擊複選框


0

我正在傳遞複選框ID,抓住元素,然後如果未選中該複選框,則要對其進行檢查。但是它不會選中該框,所以我正在調試,然後在我添加第二個它時起作用了,所以我添加了2個使其起作用,並清理了用註釋代碼等創建的雜亂無章的東西,然後我運行了再次單擊它,並且都沒有選中任何一個複選框。有趣的是,我開始關注複選框。

當代碼具有某些安全措施時,這可能會成為問題嗎?有解決方法嗎?

不確定是否重要,但是我正在將XUnit用於測試框架。

[Then(@"I check the '(.*)' checkbox")]
public void ThenICheckTheCheckbox(string checkBoxId)
{
    var checkBox = Ie.FindElementById(checkBoxId);
    var isChecked = checkBox.Selected;

    if (!isChecked)
    {
        checkBox.Click(); 
        checkBox.Click();
        isChecked = checkBox.Selected;

    }
    Assert.True(isChecked, $"the checkbox with id of: {checkBoxId}, is not checked");

}

此復選框的HTML是

<input class="check-box" data-val="true" data-val-required="The Is Active field is required." 
    id="IsActive" name="IsActive" type="checkbox" value="true">
2

Rather than accessing the element by Id try doing it with xpath. I can see the there is an tag attached to this element. So you could make use of that.So for example if your checkbox is setup like this:

<div id = "divContainer">
<input class="check-box" data-val="true" data-val-required="The Is Active 
 field is required." 
id="IsActive" name="IsActive" type="checkbox" value="true">
 </div>

Then you can use something like this:

 bool selected 
 =driver.findElemeny(By.xpath(.//[@id='divContainer']/input)).isSelected();

And then you can make use of the selected variable to click or unclick the checkbox. If you could provide me with the full page's code then I will be able to write the full xpath for you