我们有一个建立在大量表格之上的网站。行中的每个单元格都是可单击的。我正在研究一种通过提供我想要单击的表名称和值来动态构建 cssSelector 信息的方法。我已经很接近了(我想)。
使用ToolsQA处的练习表,假设我想为值“Taiwan”构建 cssSelector。
其 cssSelector 为:.tsc_table_s13 > tbody:nth-child(4) > tr:nth-child(3) > td:nth-child(2)
我正在迭代表格,并已成功能够使用我指定的值(“台湾”)输入单元格,但是,我不确定如何获取当前所在行和列的值.
这是我迄今为止使用的代码:
driver.get("http://toolsqa.com/automation-practice-table/");
String table = ".tsc_table_s13 > tbody:nth-child(4)";
String cellValue = "Taiwan";
getCell(table, cellValue);
// Get the cell of a particular value
public static void getCell(String table, String value) throws IOException{
// Grab the table
WebElement tableName = driver.findElement(By.cssSelector(table));
// Now get all the TR elements from the table
List<WebElement> allRows = tableName.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
// Print the contents of each cell
for (WebElement cell : cells) {
// System.out.println(cell.getText());
if (cell.getText().equals(value))
{
String cellValue = table + " > tr:nth-child(" + row. + ") > td:nth-child(" + cell + ")";
System.out.println(cellValue);
} // end if text equals
} // end for loop for cells
} // end for loop for all rows
} // end getCell function
最佳答案
这里有一个简单的示例,说明如何使用 XPath 在表中查找文本并获取对元素的引用。您提供要搜索的文本,它会插入到 XPath 中。下面的 XPath 搜索包含该文本的 TD
。这只是一个简单的案例。如果您的表格中有很多重复的文本,您必须发布一些示例,以便我可以更新代码以将其考虑在内。
String searchText = "China";
driver.get("http://toolsqa.com/automation-practice-table/");
WebElement e = driver.findElement(By.xpath("//td[text()='" + searchText + "']"));
System.out.println(e.getText()); // you can get the text in the cell
System.out.println(e.getAttribute("outerHTML")); // you can get the HTML of the TD
e.click(); // you can click the element also but in this case it won't do anything since it's just a TD with text
关于java - 从表值动态生成 CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127203/