简体   繁体   English

Selenium WebDriver-如何获取表元素并遍历行

[英]Selenium WebDriver - how to get elements of tables and iterate through rows

I want to iterate tables per row, In my test scenario i will look for a certain data for each rows. 我想对每行的表进行迭代,在我的测试场景中,我将为每行寻找某些数据。 I already done this by using Absolute Xpath. 我已经通过使用Absolute Xpath做到了。 Is there another better/alternative way other than using Absolute Xpath for iterating through these rows? 除了使用绝对Xpath遍历这些行之外,还有其他更好/替代的方法吗?

This is the logic of my code before: 这是我之前代码的逻辑:

private static int iRow;

WebElement sWorkUnitRows = null;

for (iRow = 1; iRow <= 10; iRow++) {

sWorkUnitQuery = driver.findElement(By.Xpath("html/body/div[2]/div[4]/div/div/div[3]/div[1]/table/tbody/tr["+ iRow + "]/td[5]/div"));

// Do some actions here, click and verify data for each rows until it finds the specific data

break;

}

Any ideas for this? 有什么想法吗? Will highly appreciate any inputs thanks! 将非常感谢任何输入,谢谢!

You can use findElements(...) instead of findElement(...) . 您可以使用findElements(...)代替findElement(...)

Here is an example: 这是一个例子:

List<WebElement> elements = driver.findElements(By.Xpath(".//*/tr/td[5]/div"));
for(WebElement element:elements){
     ...
}

This will return a list of all the div s located in the 5th column of each row. 这将返回位于每行第五列的所有div的列表。

First : If you can get IDs put on elements you are interested in, that is the best and fastest option. 首先 :如果您可以在感兴趣的元素上放置ID,那是最好,最快的选择。 Most importantly, interface changes can be made without breaking your tests as long as the ID's are maintained. 最重要的是,只要维护ID,就可以在不中断测试的情况下进行界面更改。

To your question: I would recommend driver.findElements(), but would generally recommend not using XPath any time there is another option. 对于您的问题:我建议使用driver.findElements(),但通常建议在有其他选择的任何时候不要使用XPath。

In this case, I'd use By.CssSelector to find the elements. 在这种情况下,我将使用By.CssSelector查找元素。 Something like: 就像是:

"tbody.listTbody tr"

Then extract the data from each item in the list of web elements that are returned. 然后从返回的Web元素列表中的每个项目中提取数据。 I'm guessing that if you are looking for data that you may not need to get all the way down to the div. 我猜想,如果您正在寻找数据,则可能不需要一直深入到div。 Just get the text for the row, then if you find a match for your data, work with the div. 只需获取该行的文本,然后找到与数据匹配的内容,则使用div。 You avoid checking for the div in the first place. 您避免首先检查div。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM