如何在 Selenium Java 中编写通用方法 findTableRowBy() ?
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
正如您从下面的简单表格中看到的,查找文本等于“January”的表格列很简单:“tr/td[text()='January']” 但 td 可能会变得复杂,因为它可能包含嵌套元素。所以我们最好再提供一个By参数。
我的问题是如何编写可以执行此搜索的通用方法。我下面有一个,但不好, findTableRowsBy( 1, By.xpath( "text()='January'" ) ) 会导致异常。有人可以帮我完善这个方法吗?非常感谢。
public List<WebElement> findTableRowsBy( int column, By theBy )
{
By by = By.xpath( "tbody[1]/tr/td[" + column + "]" );
List<WebElement> cols = table.findElements( by );
List<WebElement> rows = new ArrayList<WebElement>();
for( WebElement e : cols )
{
List<WebElement> eles = e.findElements( theBy );
if( eles.isEmpty() )
continue;
if( eles.size() == 1 )
rows.add( eles.get( 0 ) );
}
return rows;
}
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
As you can see from below simple table, find table column with text equals "January" is simple: "tr/td[text()='January']"
But the td may get complex as it may contains nested elements. So we'd better provide another By parameter.
My question is how to write a generic method that can perform this search. I have one below, but not good, findTableRowsBy( 1, By.xpath( "text()='January'" ) ) will lead to exception. Anybody could help me polish this method? Thanks very much.
public List<WebElement> findTableRowsBy( int column, By theBy )
{
By by = By.xpath( "tbody[1]/tr/td[" + column + "]" );
List<WebElement> cols = table.findElements( by );
List<WebElement> rows = new ArrayList<WebElement>();
for( WebElement e : cols )
{
List<WebElement> eles = e.findElements( theBy );
if( eles.isEmpty() )
continue;
if( eles.size() == 1 )
rows.add( eles.get( 0 ) );
}
return rows;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许,您还可以使用以下 xpath:
我想您应该能够找到正确的 td,即使它有嵌套元素。
Maybe, you could also use the following xpath:
I guess you should be able to find the proper td even if it has nested elements.