检索WebElements列表并识别它们

时间:2016-03-23 19:06:47

标签: java selenium-webdriver

有没有办法识别WebElement名称并将其分配给WebElement列表?例如,使用以下约定:W

@FindBy(xpath="")
WebElement listFirstObject;

@FindBy(xpath="")
WebElement listSecondObject;

请原谅我这是一个基本问题,但对于任何测试人员而言似乎都是一种非常常见的情况,因为许多应用程序都有具有通用名称的对象列表。在我的例子中,我有一个包含超过700个对象的控制列表,能够编写一些迭代方法来捕获并从列表中单独创建每个公共WebElement将会很棒。

**我已经对我的问题进行了更新以进一步澄清**整个网格信息对我来说是全新的,所以请特别注意答案,因为我正在努力理解它背后的逻辑。

所以我想要的元素是网格数据,我已经成功捕获了整个网格,例如

@FindBy(id="ctl00_SomeGridData_ucControlList_trgControlList_ctl00")
List<WebElement> someGridData;

如果我要单独捕获网格中的每个新添加内容,它将如此:

@FindBy(id="ctl00_SomeGridData_ucControlList_trgControlList_ctl00__0")
WebElement someGridObj1;

@FindBy(id="ctl00_SomeGridData_ucControlList_trgControlList_ctl00__1")
WebElement someGridObj2;

@FindBy(id="ctl00_SomeGridData_ucControlList_trgControlList_ctl00__2")
WebElement someGridObj3;

正如您所看到的,每个网格元素都以&#34; __#&#34;结尾。显然这是一个无限的列表,我不能单独捕获每个WebElement并分配一个WebElement值用于测试。我想问的是如何捕获整个列表然后如果我需要稍后调用单个WebElement来测试我该怎么做?我希望这能澄清并感谢阅读。

2 个答案:

答案 0 :(得分:3)

好的,现在已经编辑了你的问题,很清楚你想知道什么。假设您的网格数据位于td个元素中,您可以执行以下操作。

@FindBy(css = "td[id^=ctl00_SomeGridData_ucControlList_trgControlList_ctl00__]")
List<WebElement> allGridData;

使用^(表示开头),您将收集ID为td的所有ctl00_SomeGridData_ucControlList_trgControlList_ctl00__元素。

答案 1 :(得分:0)

是的,你可以这样做:

List<WebElement> mylist = driver.findElements(By.xpath("ur xpath"));
System.out.println("Size of the list is : " +mylist.size()); 

这将显示您的mylist中有多少个元素。

现在申请循环以在控制台上打印mylist的值 并且在for循环中你可以为它们分配一个像这样的值

for(int i = 0;i<mylist.size();i++){
   System.out.println("index of webelements in increasing order is : " + i + mylist.get(i).getText());  

    // this will assign an index of 0 to max for the weblements in the 
    list like index 0 = for 1 webelement ,index 1 = for 2nd webelement ,
    index 2 = for 3rd webelement and so on 
}