我有一个单选按钮,它是html表中许多行的第一列。每行的第二列是每个单选按钮的相应文本。如果给出与第2列对应的值,如何在第1列中选择特定的单选按钮?例如,我有“狗”这个词,我试图检查/点击以下html表中相应的单选按钮:
<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>
必须假设该表不可更改。我知道这是一种使用表格的糟糕方式,但这是我必须使用的。谢谢。
答案 0 :(得分:2)
遍历每一行,并获取第二列的值。如果您正在寻找此值,请选择单选按钮。所以,在伪代码中:
def select_radio_button(second_value):
for row = 0 to rows_in_table:
if (second_value == table_value(row)):
select_radio_button(row, 1)
这需要编写table_value
和select_radio_button
,这可以通过编写几个简单的XPath查询来实现。在不知道页面上还有其他内容的情况下这样做是很困难的,因为没有元素具有ID。所以,你要写下以下内容:
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))
虽然可读性值得怀疑,但可以完全使用一个XPath完成此操作:
check("//table[@class='myClass']//td[text()='Dog']/../td[1]/input[1]")
如果你做了很多这样的事情,可能值得花一些时间为此构建抽象,这样你的测试就不会只是读作XPath的行。
答案 1 :(得分:0)
<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>
答案 2 :(得分:0)
使用
//td[text()='Dog']/preceding-sibling::td/input -- Radio Button for Dog.
//td[text()='Cat']/preceding-sibling::td/input -- Radio Button for Cat.