如何使用字段中的 linkText 提取 WebElements 并单击它

How to extract WebElements using linkText from fields and click on it

我想捕捉字段中的文本并能够单击该元素。当我使用以下内容时,它会将所有元素的文本提取到日志中:

 String text;
 text = HomePageFields.TableOneColumn(driver).getText();
System.out.println("Table One Column contains following:\n" + text);

TableOneColumn xpath 不同 class:

public static WebElement TableOneColumn(WebDriver driver) throws IOException {
element = driver.findElement(By.xpath("//div[contains(@eventproxy,'isc_QMetricsView_0')]/div[1]/div[1]/div[1]/div[1]/div[1]/div[contains(@style,'position')]/div"));
    return element;

我尝试使用:

HomePageFields.TableOneColumn(driver).findElement(By.linkText("RFI Overview")).click();

但是它报错说找不到元素。

这是该特定文本的 html link。但是其他文本包含在同一个标​​签中,但在该主标签中的不同位置。

实际上 By.linkText() 通过显示的确切文本定位 <a> 元素,而 所需文本不在任何 <a> 标签内 。这就是你遇到麻烦的原因。

您应该尝试将 By.xpath() 与以下文本一起使用 :-

WebElement el = driver.findElement(By.xpath(".//div[descendant::td[text() = 'RFI Overview']]"));
System.out.println("Table One Column contains following:\n" + el.getText());
el.click();

WebElement el = driver.findElement(By.xpath(".//div[normalize-space(.) = 'RFI Overview']"));
System.out.println("Table One Column contains following:\n" + el.getText());
el.click();

或者正如我在提供的屏幕截图中看到的那样,希望 <div> 具有 id 属性,该属性的值看起来很独特。如果此元素的此属性值是固定的,您还可以尝试使用 By.id() as :-

WebElement el = driver.findElement(By.id("isc_3BL"));
System.out.println("Table One Column contains following:\n" + el.getText());
el.click();
driver.findElement(By.xpath("//td[.='RFI Overview']")).click();

我建议也使用 ID 为 isc_3BL 的 div,但我不确定这是静态 ID。如果是,您绝对可以使用它与包含与文本 "RFI Overview"

完全相同的 td 的任何其他外部 table 隔离