如何使用selenium webdriver处理复选框?

时间:2016-05-20 11:18:59

标签: selenium selenium-webdriver web-scraping web-crawler

我想抓一个没有 id 的复选框的页面,它们具有相同的名称,只是值是不同的。

<div class="mvNavLk">
    <form class="jsExpSCCategories" method="post" name="ExpressSCCategories" action="actionTest.html">
        <ul class="mvSrcLk">
            <li>
                <label class="mvNavSel mvNavLvl1">
                    First
                    <input type="checkbox" value="firstValue" name="selectedNavigationCategoryPath">
                </label>
            </li>
            <li>
                <label class="mvNavSel mvNavLvl1">
                    Second
                    <input type="checkbox" value="secondValue" name="selectedNavigationCategoryPath">
                </label>
            </li>
        </ul>
    </form>
</div>

6 个答案:

答案 0 :(得分:1)

嗨,请按以下方式执行注意此示例位于java

// take check boxes with same name inside the list 
List<WebElement> myCheckBox = driver.findElements(By.name("selectedNavigationCategoryPath"));

// now on the basis of index call click

myCheckBox.get(0).click();  // for the first check box
Thread.sleep(2000);
myCheckBox.get(1).click();  // for the second check box

或者如果你想根据价值选择

driver.findElement(By.xpath("//*[@value='firstValue']")).click();  // for the 1st one
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@value='secondValue']")).click();  // for the 2st one

<强>更新

WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@value='firstValue']")));
driver.findElement(By.xpath("//*[@value='firstValue']")).click();  // for the 1st one

希望这有助于你

答案 1 :(得分:1)

希望这有效 -

 driver.FindElement(By.XPath(".//label[contains(text(),'First')]/input")).SendKeys("test");

答案 2 :(得分:1)

使用以下代码:

driver.find_element_by_css_selector(".mvSrcLk>li:nth-child(1)>label.mvNavSel.mvNavLvl1").click();
希望这会奏效。

答案 3 :(得分:0)

driver.findElement(By.name("selectedNavigationCategoryPath")).click();

答案 4 :(得分:0)

Below Code is in C#, Collects all the Checkboxes with the name specified. Then Iterates through each ckeckbox, gets the value attribute, if the attribute is equal to your specified check box, then clicks it and comes out of the loop. Hope this should work.
IList<IWebElement> myCheckBoxs =    driver.FindElements(By.name("selectedNavigationCategoryPath"));

Foreach(IWebElement chkBx in myCheckBoxs)
{
   if(chkBx.GetAttribute("Value")=="Your Desired value")
   {
     chkBx.Click();
     break;
   }
}

`

答案 5 :(得分:0)

使用此CSS定位器。

[name='selectedNavigationCategoryPath'][value='firstValue']