【问题标题】:Check that text is visible on a page across HTML elements检查文本在跨 HTML 元素的页面上是否可见
【发布时间】:2015-11-26 00:34:28
【问题描述】:

我想检查某些文本(比如“独角兽”)在使用 Selenium 的 HTML 页面上是否可见(如果重要,则使用 Python)。

但是,由于不相关的原因,该页面具有以下结构(简化):

<div>
  <span style="display: none">A</span> <span style="display: none">unicorn</span>
</div>

Lettuce WebdriverAloe Webdriver 中使用的检查是:

driver.find_elements_by_xpath(
    '//*[contains(normalize-space(.),"{content}")'.format(text))

然后检查返回的元素是否有is_displayed。但是,这将找到外部 div 元素,并且其文本将包含搜索到的字符串,即使该字符串对用户实际上不可见。

如何检查页面上的某些文本是否可见,即使它跨越多个元素?

相应的错误:Aloe Webdriver bugLettuce Webdriver bug

【问题讨论】:

  • 也许你可以用beautifulsoup...看到这个答案:stackoverflow.com/a/27115266/499581
  • 这需要我重新实现一个 CSS 解析器,因为实际的网页可能使用类而不是简单的 display: none

标签: selenium


【解决方案1】:

这是一个困难的场景。对于您给出的具体示例,以下代码应该可以工作。该代码基本上将“A unicorn”拆分为 2 个单词并找到各个元素。找到各个跨度标签后,会找到每个元素的父元素并进行相等性比较。如果父级相等,则每个单独的元素都用于显示属性。

public class ComplicatedSearch {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("url");

        // Look if "A unicorn" occurs within a single element
        WebElement element = getElement(driver, "A unicorn");
        if (element != null) {
            if (element.isDisplayed()) {
                System.out.println("Text is displayed");
            }
        }

        // Split "A unicorn" into 2 String and find the individual elements
        WebElement part1 = getElement(driver, "A");
        WebElement part2 = getElement(driver, "unicorn");

        if (part1 != null && part2 != null) {
            // find the parents of part1 and part2 and compare whether they are
            // equal
            if (findParent(driver, "A").equals(findParent(driver, "unicorn"))) {
                // if parents are equal, check if both elements are displayed
                if (part1.isDisplayed() && part2.isDisplayed()) {
                    System.out.println("Text is displayed");
                } else {
                    System.out.println("Text is not displyed");
                }
            }
        }
    }

    private static WebElement getElement(WebDriver driver, String keyword) {
        try {
            return driver.findElement(By.xpath("//*[.='" + keyword + "']"));
        } catch (NoSuchElementException e) {
            return null;
        }
    }

    private static WebElement findParent(WebDriver driver, String keyword) {
        try {
            return driver.findElement(By.xpath("//*[.='" + keyword + "']/.."));
        } catch (NoSuchElementException e) {
            return null;
        }
    }
}

为了使这个场景具有通用性,需要付出很多努力,并且必须结合许多条件。编码愉快!

【讨论】:

  • 感谢您的回答。像这样的事情是我为解决眼前的问题所做的,但我认为它不适用于一般情况。
猜你喜欢
  • 2014-04-22
  • 2015-03-29
  • 2019-09-26
  • 2013-11-09
  • 2022-01-07
  • 2011-07-18
  • 2022-08-15
  • 2017-01-01
  • 1970-01-01
相关资源
最近更新 更多