我在Java中遇到Selenium的问题。 我有一个这样的网页:
<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>
我首先将所有行放入列表中:
List<WebElement> allRows = driver.findElements(By.xpath("//table[@class='matches']/tbody/tr[contains(@id, 'today')]"));
接下来,我遍历显示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("------------------------------------------------------------");
}
第一个println逐个显示所有行。 然而,第二个只显示皇家马德里&#39;对于每次迭代。我失去了理智,因为我不明白为什么。有人可以帮忙吗?
输出:
<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>
------------------------------------------------------------
答案 0 :(得分:1)
你必须像这样使用
System.out.println("Outer HTML for Home Team cell" + row.findElement(By.xpath("td[contains(@class,'team-a')]")).getAttribute("outerHTML"));
然后它会指出我们想要的正确元素。
谢谢你, 穆拉利