如何通过 Java 中的 Selenium/Webdriver 从复选框列表中单击一个复选框? [英] How do you click on a checkbox from a list of checkboxes via Selenium/Webdriver in Java?
问题描述
我正在使用 Selenium 2 (Webdriver) 对网页进行自动化测试.但是我想知道是否有办法使用 webdriver 框架从复选框列表中检查复选框?
I'm using Selenium 2 (Webdriver) for automating tests on a webpage. However I wonder if there is way to check checkbox from the list of checkboxes using webdriver framework?
我试过这段代码但没有用:
I tried this code but no avail:
IWebElement box = ffDriver.FindElement(By.XPath("//*[@id='ctl00_ContentPlaceHolder1_Adde_div']"));
List<IWebElement> chkbox = box.FindElements(By.TagName("input"));
ffDriver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Add_lstCategory_0"));
//chkbox.g(2).click();
推荐答案
如果你已经知道checkbox的id,可以用这个方法点击选中:
If you already know the id of the checkbox, you can use this method to click select it:
string checkboxXPath = "//input[contains(@id, 'lstCategory_0')]"
IWebElement elementToClick = driver.FindElement(By.XPath(checkboxXPath));
elementToClick.Click();
假设您在页面上有多个具有相似 ID 的复选框,您可能需要将lstCategory_0"更改为更具体的内容.
Assuming that you have several checkboxes on the page with similar ids, you may need to change 'lstCategory_0' to something more specific.
这是用 C# 编写的,但适应其他语言应该不难.此外,如果您使用更多信息编辑您的帖子,我可以更好地微调这个示例.
This is written in C#, but it shouldn't be difficult to adapt to other languages. Also, if you edit your post with some more information, I can fine-tune this example better.
让我知道这是否有效!
我已经访问了该站点并使用以下代码成功地与下拉小部件中的复选框进行了交互:
I've visited the site and successfully interacted with the checkboxes in the dropdown widget using this code:
/** Set XPath Variables **/
string dropdownWidgetXPath = "//span[contains(@id, 'selInd')]";
string checkboxXPath = "//input[contains(@id, 'selInd')]";
/** Navigate to the page **/
driver.Navigate().GoToUrl("http://www.jobserve.com/us/en/Job-Search/");
/** Click the dropdown widget **/
IWebElement dropdownWidgetElement = driver.FindElement(By.XPath(dropdownWidgetXPath));
dropdownWidgetElement.Click();
/** Identify all checkboxes present **/
var allCheckboxes = driver.FindElements(By.XPath(checkboxXPath));
/** Click each checkbox and wait so that results are visible **/
foreach(IWebElement checkbox in allCheckboxes)
{
checkbox.Click();
System.Threading.Thread.Sleep(500);
}
这篇关于如何通过 Java 中的 Selenium/Webdriver 从复选框列表中单击一个复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!