【问题标题】:How to check if some of the text data appears on the page如何检查某些文本数据是否出现在页面上
【发布时间】:2017-12-26 13:56:27
【问题描述】:

我想检查页面是否有特定的文本。最好能马上查出几条短信。

例如,如果有“客户”、“客户”、“订单”

这里是 HTML 代码。

<div class="findText"><span>Example text. Football.</span></div>

检查后,我会使用这里的 if 条件。这是我的尝试,但这不是最好的选择。此外,我无法检查更多的单词,我尝试使用 ||仅限。

 if(driver.getPageSource().contains("google"))  {

                driver.close();
                driver.switchTo().window(winHandleBefore);
                }

此外,是否可以大量抛出一个完整的单词列表来检查它们是否存在?

【问题讨论】:

    标签: java selenium selenium-webdriver automation


    【解决方案1】:
    if(stringContainsItemFromList(driver.getPageSource(), new String[] {"google", "otherword"))
    {
        driver.close();
        driver.switchTo().window(winHandleBefore);
    }
    
     public static boolean stringContainsItemFromList(String inputStr, String[] items)
        {
            for(int i =0; i < items.length; i++)
            {
                if(inputStr.contains(items[i]))
                {
                    return true;
                }
            }
            return false;
        }
    

    来自Test if a string contains any of the strings from an array的stringContainsItemFromList()方法

    如果您只想获取该元素的文本,您可以使用类似这样的东西而不是 driver.getPageSource()...

    driver.findElement(By.cssSelector("div.findText > span")).getText();
    

    【讨论】:

    • 感谢您的回复。我目前正在测试这种方法。看起来它的工作。但是,可以在不使用 .getPageSource 的情况下做同样的事情吗?就像使用我发布的这个 HTML 代码一样。
    • 是的,例如,您可以这样做(请参阅更新后的帖子以获得更好的格式) driver.findElement(By.cssSelector("div.findText > span")).getText()
    【解决方案2】:

    看看Java 8 Streaming API

    import java.util.Arrays;
    
    public class Test {
    
        private static final String[] positiveWords = {"love", "kiss", "happy"};
    
        public static boolean containsPositiveWords(String enteredText, String[] positiveWords) {
            return Arrays.stream(positiveWords).parallel().anyMatch(enteredText::contains);
        }
    
        public static void main(String[] args) {
            String enteredText1 = " Yo I love the world!";
            String enteredText2 = "I like to code.";
            System.out.println(containsPositiveWords(enteredText1, positiveWords));
            System.out.println(containsPositiveWords(enteredText2, positiveWords));
        }
    }
    

    输出:

    true
    false
    

    您也可以通过使用 .parallelStream() 来使用 ArrayList。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2013-05-20
      相关资源
      最近更新 更多