HTML:https://imgur.com/a/6QtUK
每个“tr”是表格的一行。 每行通过单击展开一个隐藏的行。 每个隐藏行都包含链接。 需要通过 linkText 找到特定的链接,因为行每次都在变化(id 也在变化),并且链接可以在不同的时刻在不同的行上找到。无法使用 xpath。
我用脚本尝试了 JavascriptExecutor:
arguments[0].click()But it can't execute by linkText without using xpath or css-selector. And one more problem: I don't know how to restrict execution in the specific table (page could has one more link with the same name).
I tried to create a collection:
WebElement table = $("table locator");
List<WebElement> allRows = table.findElements(By.tagName("tr"));
for(int i=1;i<allRows.size();i++) {
WebElement table1 = $("table locator");
List<WebElement> allRows1 = table1.findElements(By.tagName("tr"));
allRows1.get(i).findElement(By.linkText("linkText"));
但不知道如何创建隐藏元素的集合。
任何想法,我怎么不能严格地通过 linkText 找到隐藏的链接? 是否可以在没有绝对路径的情况下通过 linkName 迭代 DOM? 或者唯一的方法是循环,单击每一行直到找到链接?
PS:抱歉英语不好。
最佳答案
有 3 种方法。
- 遍历可见的
tr
元素 - 遍历隐藏的
tr
元素 - 如果链接从一开始就存在于源代码中,您可以找到它并且它是相关的父元素(行)
解决方案 #1:
WebElement table = $("table locator");
List<WebElement> dataRows = table.findElements(By.cssSelector("tr[class*='data-row']"));
for (int i = 0; i < dataRows.size(); i++) {
WebElement singleDataRow = dataRows.get(i);
singleDataRow.click();
}
//all VISIBLE tr elements were clicked. Time to find our link
WebElement link = table.findElement(By.linkText("linkText"));
link.click();
解决方案#2:
WebElement table = $("table locator");
List<WebElement> dataRows = table.findElements(By.cssSelector("tr[class*='actions']"));
for (int i = 0; i < dataRows.size(); i++) {
WebElement singleDataRow = dataRows.get(i);
singleDataRow.click();
}
//all HIDDEN tr elements were clicked. Time to find our link
WebElement link = table.findElement(By.linkText("linkText"));
link.click();
解决方案 #3:
WebElement link = table.findElement(By.linkText("linkText"));
WebElement parentElementOfLink = link.findElement(By.xpath("./*"));
//this is probably our tr element
parentElementOfLink.click(); //clicks desired row
编辑:
扩展解决方案 #1:
WebElement table = $("table locator");
List<WebElement> dataRows = table.findElements(By.cssSelector("tr[class*='data-row']"));
for (int i = 0; i < dataRows.size(); i++) {
WebElement singleDataRow = dataRows.get(i);
singleDataRow.click();
//we need to find the link after clicking each `tr` element.
try {
WebElement link = table.findElement(By.linkText("linkText"));
link.click();
break;
} catch (NoSuchElementException e) {
//ignore the exception. It means our link does not exist in this row and we need to continue the iteration
}
}
关于javascript - 如何通过 linkText/linkName 严格地在表的隐藏行之一中找到特定链接(不使用 css-selectors 或 xpath)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47606811/