简体   繁体   English

Selenium WebDriver-遍历表行

[英]Selenium WebDriver - iteration through table rows

I'm having an issue with Selenium in Java. 我在Java中遇到Selenium的问题。 I have a web page like this: 我有一个这样的网页:

<html>
<body>
<div id='content'>
<table class='matches'>
<tr id='today_01'>
<td class='team-a'>Real Madrid</td>
<td class='score'>0-0</td>
<td class='team-b'>Barcelona</td>
</tr>
<tr id='today_02'>
<td class='team-a'>PSG</td>
<td class='score'>1-1</td>
<td class='team-b'>Manchester City</td>
</tr>
<tr id='today_03'>
<td class='team-a'>Liverpool</td>
<td class='score'>2-2</td>
<td class='team-b'>Arsenal</td>
</tr>
</table>

<div id='content'>
<body>
<html>

I first get all the rows into a list: 我首先将所有行放入列表中:

List<WebElement> allRows = driver.findElements(By.xpath("//table[@class='matches']/tbody/tr[contains(@id, 'today')]"));

Next I iterate through all the elements displaying the WebElement (ie the row) and on the next line I display the td containing the home team, separated by a line: 接下来,我遍历显示WebElement的所有元素(即行),并在下一行显示包含主队的td,并用一行分隔:

for (WebElement row : allRows) {
    System.out.println("Outer HTML for row" + row.getAttribute("outerHTML"));
    System.out.println("Outer HTML for Home Team cell" + row.findElement(By.xpath("//td[contains(@class,'team-a')]")).getAttribute("outerHTML"));
System.out.println("------------------------------------------------------------");
}

The first println displays all rows, one by one. 第一个println一次显示所有行。 The second however displays ONLY 'Real Madrid' for each iteration. 但是,第二个每次迭代仅显示“皇家马德里”。 I'm losing my mind because I don't understand why. 我迷失了方向,因为我不明白为什么。 Can someone please help? 有人可以帮忙吗?

The output: 输出:

<tr id='today_01'>
<td class='team-a'>Real Madrid</td>
<td class='score'>0-0</td>
<td class='team-b'>Barcelona</td>
</tr>
<td class='team-a'>Real Madrid</td>
------------------------------------------------------------
<tr id='today_02'>
<td class='team-a'>PSG</td>
<td class='score'>1-1</td>
<td class='team-b'>Manchester City</td>
</tr>
<td class='team-a'>Real Madrid</td>
------------------------------------------------------------
<tr id='today_03'>
<td class='team-a'>Liverpool</td>
<td class='score'>2-2</td>
<td class='team-b'>Arsenal</td>
</tr>
<td class='team-a'>Real Madrid</td>
------------------------------------------------------------

You have to use like this 你必须这样使用

  System.out.println("Outer HTML for Home Team cell" + row.findElement(By.xpath("td[contains(@class,'team-a')]")).getAttribute("outerHTML"));

Then it will point to correct element what we want. 然后它将指向正确的元素我们想要什么。

Thank You, Murali 谢谢,穆拉利

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

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