It depends on whether or not the checkbox is using a known HTML
convention. If you look at
http://www.w3schools.com/tags/tag_label.asp
you can see an example. Essentially, the text associated with the
input has a for attribute. If you find the label, get the for
attribute you can find the input. For example,
<label for='agreement'>I agree</label>
<input type='checkbox' id='agreement'>
If I get the text into the variable label and it is "I agree" the code
might look like:
String label = "I agree";
String labelLocator = By.xpath("//input[text()='" + label + "']");
WebElement labelElement = driver.findElement(labelLocator);
String checkboxID = labelElement.getAttribute("for");
Sting checkboxLocator = By.cssSelector("input#" + checkboxID);
WebElement checkboxElement = driver.findElement(checkboxLocator);
If they are not following this convention you would have to find the
input by using the XPath from the text to the input. For example, if
the above example is actually,
<span>I agree</span>
<input type='checkbox' id='agreement'>
then I would have to use:
String label = "I agree";
String checkboxLocator = By.xpath("//span[text='" + label + "']/../
input[@type='checkbox']");
WebElement checkboxElement = driver.findElement(checkboxLocator);
Although this looks shorter it is not as secure as the first example.
It also assumes there is only one check box parallel to the span.