How to click on checkbox on webpage using selenium

2019-01-15 23:31发布

I have a query,how to click on checkbox on webpage using selenium vba.

Below is the screen shot where i want to click

enter image description here

Below is the html code.

<span name="locSpans[]" value="Nerul" style="display:block">
<input type="checkbox" name="locArr[]" value="8897" onclick="enableDisableLocality(); showSelectedLoc();">Nerul
<br>
<input type="hidden" name="locArrVal[]" disabled="disabled" value="Nerul">
</span>

3条回答
Root(大扎)
2楼-- · 2019-01-15 23:50

Try this if not go for CSS Selector Option

bot.Window.Maximize

bot.FindElementByName("locArrVal").Click

bot.Wait 1000
查看更多
We Are One
3楼-- · 2019-01-15 23:57

You can use xpath below to get checkbox, it means: find input with type="checkbox" and parent SPAN with text "Nerul".

driver.FindElementByXPath("//input[ancestor::span[normalize-space(.)='Nerul'] and @type='checkbox']").Click
查看更多
仙女界的扛把子
4楼-- · 2019-01-16 00:08

FindElementByCss is generally faster unless using IE, and then it depends which version of IE and what type of traversal is required.

Repeated tests have proven FindElementByCss to be more performant than FindElementByXPath (Note: that if there is a unique id present then selecting by id is always the first choice!)

In benchmarked tests Chrome and FireFox saw faster matching using CSS consistently across different traversal paths. They are optimized with CSS in mind and using CSS selectors is advocated as selenium best practice. IE was more variable with most instances of XPath being slightly more performant, but there being some clear paths that favoured CSS selection. Long XPath selectors will be costly and prone to breakage. Later versions of IE saw more variability. Opera12 browser came in with mixed results.


I would use a CSS selector:

So, for a simple selection based on likely unique attribute, I would go with an attribute CSS selector of [value='8897'] to target the value attribute. The [] means attribute selector. So value attribute with value of 8897.

driver.FindElementByCss("[value='8897']").Click

If you want to be more selective you can throw in an additional attribute selector, as follows, to target the type attribute.

driver.FindElementByCss("[type=checkbox][value='8897']").Click

When should I use XPath then?

Older IE versions for sure.

Any requirement for walking up the DOM would point to XPath usage.

XPath has some great additional locator strategies for hard to find elements, but that is not necessary AFAIK here. You can see some of the additional considerations here.

查看更多
登录 后发表回答