简体   繁体   English

使用带有xpath的嵌套FindElement解析表(在JAVA中)

[英]Parsing table using nested FindElement with xpath (in JAVA)

I'm a bit new to selenium and xpath and am curious if I'm doing something right and how findElement will behave. 我对selenium和xpath有点陌生,很好奇我是否在做正确的事情以及findElement的行为。 I've looked and looked for an example but I can't find one. 我已经寻找了一个示例,但找不到。

Given this Table (simplified but relevant) 鉴于此表(简化但相关)

  <table> <thead></thead> <tbody> <tr> <td>R1C1</td> <td>R1C2</td> </tr> <tr> <td>R2C1</td> <td>R2C2</td> </tr> </tbody> </table> 

If I use the following, will I have the info I'm expecting? 如果使用以下内容,我会得到我所期望的信息吗?

WebElement r1 = driver.findElement(By.xpath("//table/tbody/tr[1]"));
String r1c1 = r1.findElement(By.xpath("//td[1]")).getText();
String r1c2 = r1.findElement(By.xpath("//td[2]")).getText();

WebElement r2 = driver.findElement(By.xpath("//table/tbody/tr[2]"));
String r2c1 = r1.findElement(By.xpath("//td[1]")).getText();
String r2c2 = r1.findElement(By.xpath("//td[2]")).getText();

Alt: 替代:

String r2c1 = driver.findElement(By.xpath("//table/tbody/tr[2]")).findElement(By.xpath("//td[1]")).getText();

Please keep in mind this is HIGHLY simplified in comparison to what I'm actually doing, but I'm confident the rest will work. 请记住,与我的实际操作相比,此操作已大大简化,但我相信其余的方法会起作用。 My question revolves specifically around finding an element off of another element. 我的问题专门围绕从另一个元素中找到一个元素。 And, no, there are no unique Class/ID tags I can utilize to specifically identify a given cell of the table. 而且,没有,我没有可以用来唯一标识表中给定单元格的唯一Class / ID标签。

Will this work as I expect it to? 我会按预期工作吗? (I realize I could just try it, but then the answer wouldn't be available online for the next person to search for) (我知道我可以尝试一下,但是下一个要搜索的人将无法在线找到答案)

I would rather suggest to Keep It Short and Simple for a better Execution Performance . 我宁愿建议Keep It Short and Simple以获得更好的Execution Performance

If you want to getText() from the following four WebElements keep it as simple as : 如果要从以下四个WebElements获取getText() ,则使其尽可能简单:

String r1c1 = driver.findElement(By.xpath("//table//tbody/tr/td")).getAttribute("innerHTML");
String r1c2 = driver.findElement(By.xpath("//table//tbody/tr//following::td[2]")).getAttribute("innerHTML");

String r2c1 = driver.findElement(By.xpath("//table//tbody//following::tr[2]/td")).getAttribute("innerHTML");
String r2c2 = driver.findElement(By.xpath("//table//tbody//following::tr[2]//following::td[2]")).getAttribute("innerHTML");

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

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