[英]Selenium WebDriver Java locating two different table cells
I'm using Selenium Webdriver in Java.我在 Java 中使用 Selenium Webdriver。 I have a table, and I like to get my hands on the last cell on the first row, and the last cell of last row.
我有一张桌子,我喜欢把手放在第一行的最后一个单元格和最后一行的最后一个单元格上。 I manage to get one of them
我设法得到其中之一
WebElement table =driver.findElement(By.className("dataTable"));
List <WebElement> rows = table.findElements(By.tagName("tr"));
WebElement firstrow= rows.get(0);
WebElement lastrow= rows.get(rivit.size()-1);
List <WebElement> firstcells = firstrow.findElements(By.tagName("td"));
List <WebElement> lastcells = lastcell.findElements(By.tagName("td"));
firstcell.get(6).getText());
This is because I'm locating td-tags twice.这是因为我两次定位 td-tags。 Any hints how to get both cells nicely?
任何提示如何很好地获得两个细胞? I have no identifiers in my rows or cells.
我的行或单元格中没有标识符。
You can use xpath to get the elements:您可以使用 xpath 来获取元素:
WebElement lastCellInFirstRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[1]//td[last()]"));
WebElement lastCellInLastRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[last()]//td[last()]"));
Here's the xpath specification .这是xpath 规范。 You can play with xpath here .
您可以在此处使用 xpath。
You can try to make it with cssSelectors:您可以尝试使用 cssSelectors 来实现:
String cssLast="table[class='dataTable']>tr:first-child>td:last-child"
String cssFirst="table[class='dataTable']>tr:last-child>td:last-child"
it will be smt like that;它会像那样 smt;
driver.findElement(By.cssSelector(cssLast)).getText();
driver.findElement(By.cssSelector(cssFirst)).getText();
another approach is using js:另一种方法是使用js:
String getText(cssSel){
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\""+cssSel+"\");");
stringBuilder.append("return x.text().toString();") ;
String res= (String) js.executeScript(stringBuilder.toString());
}
text1=getText(cssLast);
text2=getText(csscssFirst);
But always make sure that you located elements properly (eg using firepath, firebug addon in firefox)但始终确保正确定位元素(例如,在 firefox 中使用 firepath、firebug 插件)
The TableDriver extension ( https://github.com/jkindwall/TableDriver.Java ) offers a nice clean way to handle things like this. TableDriver 扩展 ( https://github.com/jkindwall/TableDriver.Java ) 提供了一种非常干净的方式来处理这样的事情。 If your table has headers, you can (and should) identify the cell column by its header text, but in case you don't have headers, you can still do something like this.
如果您的表格有标题,您可以(并且应该)通过标题文本识别单元格列,但如果您没有标题,您仍然可以执行类似的操作。
Table table = Table.createWithNoHeaders(driver.findElement(By.className("dataTable")), 0);
WebElement firstRowLastCell = table.findCell(0, table.getColumnCount() - 1);
WebElement lastRowFirstCell = table.findCell(table.getRowCount() - 1, table.getColumnCount() - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.