在这里,我要打印“ Delhi Capitals Innings”表中各个运动员的得分记录。我想先将范围限制为表,然后再使用方法findElemets
获得所需的输出。我正在使用以下代码。
如果替换
System.out.println(table.findElements(By.xpath("//div[@class='cb-col cb-col-8 text-right text-bold']")).get(i).getText());
与
System.out.println(table.findElements(By.xpath("//div[@id='innings_2']//div[@class='cb-col cb-col-100 cb-ltst-wgt-hdr'] //div[@class='cb-col cb-col-8 text-right text-bold']")).get(i).getText());
将获得正确的结果。但是我想通过限制驱动程序的范围来做到这一点。
public class Runs{
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","C:\\ChromeDriver\\1\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.cricbuzz.com/live-cricket-scorecard/22408/kxip-vs-dc-13th-match-indian-premier-league-2019");
driver.manage().window().maximize();
WebElement table = driver.findElement(By.xpath("//div[@id='innings_2']//div[@class='cb-col cb-col-100 cb-ltst-wgt-hdr']"));
int rowCount = table.findElements(By.xpath("//div[@class='cb-col cb-col-8 text-right text-bold']")).size();
for(int i=0;i<rowCount;i++) {
System.out.println(table.findElements(By.xpath("//div[@class='cb-col cb-col-8 text-right text-bold']")).get(i).getText());
}
}
}
我得到的输出如下:
R
15
20
6
39
43
29
1
3
1 < br /> 0
0
2
3
0
2
0
0
R
0
30
28
39
38
0
2
0
0
4
0
2
4
2
1
0
0
它将在整个网页中打印与提供的xpath匹配的所有元素。它应该只在“ Delhi Capitals Innings”表下打印一份礼物。 我在此缺少什么?
答案 0 :(得分:0)
在for循环中将方法value aggregateByKey
更改为findelements
。
findelement
答案 1 :(得分:0)
您正在使用2个带有选择器的表。如果您只想选择下面的xpath,请在末尾添加[1]
:
WebElement table = driver.findElement(By.xpath("//div[@id='innings_2']//div[@class='cb-col cb-col-100 cb-ltst-wgt-hdr'][1]"));
您可以按标签获取表格,xpath在下面可以获取“ Delhi Capitals Innings”表格的行:
//span[.='Delhi Capitals Innings']/ancestor::div[contains(@class,'cb-ltst-wgt-hdr')]/div[.//a[@class='cb-text-link']]
代码:
String tableName = "Delhi Capitals Innings";
List<WebElement> rows = driver.findElement(By.xpath("//span[.='"
+ tableName + "']/ancestor::div[contains(@class,'cb-ltst-wgt-hdr')]/div[.//a[@class='cb-text-link']]"));
答案 2 :(得分:-1)
您走在正确的道路上,但是有问题。通常,您尝试做的是可行的。您缺少的部分在第二个XPath中。一个简单的HTML TABLE
示例。
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
要使用XPath查找TABLE
,应使用//table
。要使用第二个定位器在表格中查找单元格,您需要在XPath的开头添加一个.
,例如./tr/td
。这告诉XPath从相对位置开始。有关更多信息,请参见this question。代码就像
WebElement table = driver.findElement(By.xpath("//table"));
WebElement cell = table.findElement(By.xpath("./tr/td"));
^ I'm starting with the table variable here, like you did
^ but I added the . to indicate relative
说了这么多,在这里就行不通了。没有一个HTML元素可以包含所有“ Delhi Capitals Innings”的内容。父DIV
内实际上有4个DIV,可以容纳所有内容。
<div id="innings_2" class="ng-scope">
<div class="cb-col cb-col-100 cb-ltst-wgt-hdr"></div>
<div class="cb-col cb-col-100 cb-scrd-sub-hdr cb-bg-gray text-bold">Fall of Wickets</div>
<div class="cb-col cb-col-100 cb-col-rt cb-font-13">...</div>
<div class="cb-col cb-col-100 cb-ltst-wgt-hdr"></div>
</div>
您将不得不分别刮擦每个。