首页 > 解决方案 > 如何使用xpath Java Selenium获取所有包含指定文本的td标签?

问题描述

实际的问题是:无法找到所有td包含指定文本的标签,只能找到其中的一些。

我正在尝试td使用 xpath 检查所有标签是否包含指定的文本,例如:

 WebElement tableId = driver.findElement(By.id("tablepress-6"));
 if (!driver.findElements(By.xpath("//td[contains(text(),'" + textInput + "')]")).isEmpty()) {

 List<WebElement> tdElements = tableId.findElements(By.xpath("//td[contains(text(),'"+ textInput + "')]"));
          //...
 }

我也尝试过使用 xpath 的方法,例如:

List<WebElement> tdElements = tableId.findElements(By.xpath("//*[contains(text(),'" + textInput + "')]"));

就像:

List<WebElement> tdElements = tableId.findElements(By.xpath("//tr[*[text() = '"+ textInput + "']]/td[2]"));

但是,如果我检查我的网站,我并没有得到td元素的所有匹配项,可能是因为br某些match 中的元素td

在此处输入图像描述

我没有得到所有17匹配项(如上面的屏幕),而是得到更少的匹配项(在我的特定情况下 - 12): 在此处输入图像描述

有人可以建议我如何获取td包含指定文本的所有标签吗?提前致谢。

标签: javaselenium-webdriver

解决方案


问题是区分大小写的Physics and astronomy。在某些行中,您可以找到Physics 和 Astronomy。要解决它,您可以使用 xpath translate功能。

在下面的示例中,我得到的第二列仅包含物理和天文学文本,因为它也存在于第二列中。

//tr[@role='row']/td[2][contains(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'physics and astronomy')]

作为替代方案,您可以使用 Java 按文本过滤:

List<WebElement> rows = new WebDriverWait(driver, 10)
        .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(".tablepress tbody tr[role=row]")));

// By whole phrase
List<WebElement> physicsAndAstronomy1 = rows.stream().filter(e ->
        e.findElement(By.cssSelector("td:nth-child(2)")).getText().toLowerCase()
                .contains("physics and astronomy"))
        .collect(Collectors.toList());

// By separately words
List<WebElement> physicsAndAstronomy2 = rows.stream().filter(e -> {
    String text = e.findElement(By.cssSelector("td:nth-child(2)")).getText().toLowerCase();
    return text.contains("physics") && text.contains("astronomy");
}).collect(Collectors.toList());

推荐阅读