简体   繁体   English

如何使用selenium单击复选框

[英]How to click a checkbox using selenium

<div id="yui_3_16_0_1_1399697074576_1339" class="cbox " role="gridcell">
<input id="yui_3_16_0_1_1399697074576_1338" type="checkbox" tabindex="-1" 89513626107905="" aria-label="Message " title="Select this email">
<span id="yui_3_16_0_1_1399697074576_1340" class="icon"></span>
</div>`

The above HTML is from firebug. 上面的HTML来自firebug。

I want to click the checkbox, its ID is id="yui_3_16_0_1_1399697074576_1338" from above. 我想点击复选框,其ID是上面的id="yui_3_16_0_1_1399697074576_1338" I tried using by.id and by.path , however neither of them work. 我尝试使用by.idby.path ,但是它们都不起作用。 The following is what I tried: 以下是我尝试的内容:

By.id("yui_3_16_0_1_1399697074576_1338")
By.xpath("//input[@id='yui_3_16_0_1_1399697074576_1339'

Can someone help me on this? 有人可以帮我吗?

if the id is static : 如果id是静态的:

 string checkboxXPath = "//input[contains(@id, 'yui_3_16_0_1_1399697074576_1338')]"

for Dynamic Tags value: 对于动态标签值:

           string checkboxXPath = "//input[contains(@type,'checkbox') and                       
          contains(@title,'Select this email')]"

IWebElement elementToClick = driver.FindElement(By.XPath(checkboxXPath));
elementToClick.Click();

You NEVER want to match on an ID like that. 永远不想匹配这样的ID。 What I'd recommend, is matching on something a little more "unique". 我推荐的是匹配更“独特”的东西。

Try: 尝试:

By.cssSelector("input[type='checkbox'][title='Select this email']")

This selector above will match your <input/> perfectly. 上面的这个选择器将完美匹配您的<input/> And, it's not coupled with the Yahoo UI so if you or your developers ever change software, it will account for that. 并且,它没有与Yahoo UI结合,因此如果您或您的开发人员更换软件,它将解释这一点。

You have to get the element using the id and make a click. 您必须使用id获取元素并单击。 It is similar to button click 它类似于按钮点击

driver.findElement(By.id("yui_3_16_0_1_1399697074576_1338")).click();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM