选择隐藏在按钮下的复选框

时间:2013-11-27 13:59:16

标签: jquery selenium selenium-webdriver

我需要选中复选框,但点击功能失败。

我的网页上有按钮:

<button type="button" class="ui-multiselect ui-widget ui-state-default ui-corner-all" aria-haspopup="true" style="">
spans...
</button>

我们有复选框:

<ul class="classa123 classb123" style="">
<li class=" ">
<label class="classoflabel" title="" for="checkbox-123">
<input type="checkbox" title="Select This" value="1" name="multiselect-box-type" id="checkbox123">
<span>Select This</span>
</label></li>
    ...

如何选中此复选框? 使用find_element_by_id("checkbox123").is_selected()我发现未选中复选框,但是当我尝试.click()时它失败了。我想也许我应该先点击按钮打开复选框,但按钮没有唯一的ID或类。 我正在使用pylen的selenium webdriver。如果您知道如何解决此问题,也可以使用其他语言编写代码。 感谢...

2 个答案:

答案 0 :(得分:1)

好的,我想我能得到你所需要的。首先,如果您使用的是jQuery,则可以使用任何CSS选择器作为选择器来获取元素。例如,要获得id checkbox123的输入,您只需:

$('#checkbox123')

但是,如果您想要在checkbox内收集输入ul,那么您可以选择:

$('ul input[type=checkbox]')

最后,确定检查是否非常简单。

var checked = $('#checkbox123').is(':checked');
//  see your result in developer console with 
console.log(checked); // will be `true` or `false`

如果您尝试获取跨度(使用文本Select This),则在点击按钮后,您可能会尝试以下内容:

$('button').click(function(e) {
    $('ul input[type=checkbox]:checked').each(function(i) {
        var span = $(this).next('span');
        alert(span.text())
    });
})

上次通话,如果您需要更改复选框的状态,请在checked上使用布尔值.prop。如:

$('#checkbox123').prop('checked', true); // will make it checked
$('#checkbox123').prop('checked', false); // will uncheck it

我相信自从我上次回答问题以来可能已经更新了,所以我会在这里更新答案,以显示明显缺少的内容。

最后,使用jQuery触发事件,例如click非常简单。还有几种方法可以做到这一点,其中一些基本相同。

最简单的方法是使用.click()。它很简单:

$('#checkbox123').click();

下次使用是.trigger()。基本上与.click相同。 Really this is just about personal use in readability

$('#checkbox123').trigger('click');

请记住,如果您使用此功能,则无效。选择器可能有问题。确切知道的一种方法是控制日志。如果你没有看到一个jQuery对象元素打印到包含你期望的元素的控制台,那么你知道你的选择器不工作。请记住,这将显示一个jQuery对象,但它不会包含HTML元素。

console.log($('#checkbox123').trigger('click'));

如果存在,将看起来像:

[input#checkbox123, context: document, selector: "#content", jquery: "1.9.......and so on for rest of object

如果不存在,将看起来像:

[context: document, selector: "#checkbox123", jquery: "1.9.......and so on for rest of object

答案 1 :(得分:0)


尝试触发点击事件,如下所示:

   var element = $('#checkbox123')[0];
   if (document.createEvent) { 
      var e = document.createEvent("MouseEvents");
      e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      element.dispatchEvent(e);
  }