简体   繁体   中英

Selenium WebDriver - iteration through table rows

I'm having an issue with Selenium in Java. 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:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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