I have a radio button that is the first column of many rows in an html table. The second column of each row is the corresponding text to each radio button. How can I select a specific radio button in column 1 if I am given a value that corresponds to column 2? For example, I have the word 'Dog' and I am trying to check/click the corresponding radio button from开发者_如何学JAVA the following html table:
<table class="myClass">
<tr>
<td><input type="radio" name="radioName"></td>
<td>Dog</td>
</tr>
<tr>
<td><input type="radio" name="radioName"></td>
<td>Cat</td>
</tr>
</table>
The table must be assumed to be unchangeable. I know it is a poor way to use a table, but this is what I've got to work with. Thank you.
Iterate through each row, and get the value of the second column. If this value is what you're looking for, then select the radio button. So, in pseudo-code:
def select_radio_button(second_value):
for row = 0 to rows_in_table:
if (second_value == table_value(row)):
select_radio_button(row, 1)
This requires table_value
and select_radio_button
to be written, which can be achieved by writing a couple of simple XPath queries. Doing so without knowing what else is on the page is difficult, since none of the elements have IDs. So, you'd write something along the lines of:
def table_value(row, column):
return get_text("//table[@class='myClass']//tr[%s]/td[%s]" % (row, column))
def select_radio_button(row, column):
check("//table[@class='myClass']//tr[%s]/td[%s]/input[@type='radio']" % (row, column))
It is possible to do this entirely with one XPath, although the readability is questionable:
check("//table[@class='myClass']//td[text()='Dog']/../td[1]/input[1]")
If you're doing this sort of thing a lot, it might be worth spending some time building abstractions for this, so that your tests don't just read as lines of XPaths.
<html>
<head>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function check_from_val(val) {
/*Find td containing matching text*/
var matching_val = $('td').filter( function() { return $(this).text() == val } );
/*Find the closest tr parent */
var parent_row = matching_val.parents("tr")[0];
/*Find the input descendent of tr and check it */
$(parent_row).find("td input").attr("checked",true);
}
</script>
</head>
<table>
<tr><td><input type="radio" name="rdoName" /></td><td>Dog</td></tr>
<tr><td><input type="radio" name="rdoName" /></td><td>Cat</td></tr>
</table>
<a href="javascript:check_from_val('Dog')">Dog</a>
<a href="javascript:check_from_val('Cat')">Cat</a>
</html>
Use
//td[text()='Dog']/preceding-sibling::td/input -- Radio Button for Dog.
//td[text()='Cat']/preceding-sibling::td/input -- Radio Button for Cat.
精彩评论