【问题标题】:How can I check if some text exist or not in the page using Selenium?如何使用 Selenium 检查页面中是否存在某些文本?
【发布时间】:2012-07-12 09:04:38
【问题描述】:

我正在使用 Selenium WebDriver,如何检查页面中是否存在某些文本?也许有人向我推荐了有用的资源,我可以在其中阅读它。谢谢

【问题讨论】:

标签: validation selenium webdriver assert


【解决方案1】:

使用XPath,没那么难。只需搜索包含给定文本的所有元素:

List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

official documentation 不太支持此类任务,但它仍然是基本工具。

JavaDocs 更大,但需要一些时间来处理所有有用和无用的内容。

要学习 XPath,只需 follow the internet。该规范也是一本令人惊讶的好读物。


编辑:

或者,如果你不希望你的Implicit Wait 让上面的代码等待文本出现,你可以这样做:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));

【讨论】:

  • 我收到通知 - WebElement 无法解析为类型,Assert 无法解析为类型,List 无法解析为类型 - 我需要添加一些导入来解决此问题?
  • 你还记得我昨天告诉你的快捷键吗?他们帮助 ;-)。如果您使用 Java,您应该知道List 所在的位置。如果您正在使用 Selenium 库,您应该知道 WebElement 所在的位置。如果您在问题中添加了assert 标签并使用Java,您应该知道Assert 的位置(需要JUnit)...
  • 抱歉,我是 selenium 和 java 新手)
  • 获取正文不是在页面上搜索文本的正确方法。获取正文将测试该字符串是否存在于源代码中,但并不能真正测试该字符串是否存在于页面上。例如,可能存在损坏的 PHP 脚本,其中缺少关闭 ?>,这意味着测试将通过,但页面将无法正确呈现。
【解决方案2】:

您可以像这样检索整个页面的正文:

bodyText = self.driver.find_element_by_tag_name('body').text

然后像这样使用断言来检查它:

self.assertTrue("the text you want to check for" in bodyText)

当然,您可以指定并检索特定 DOM 元素的文本,然后检查它而不是检索整个页面。

【讨论】:

  • 如果您要断言并检查某个元素是否在某物中,我建议您使用self.assertIn("the text you want to check for", bodyText)
【解决方案3】:

这将帮助您检查网页中是否存在所需的文字。

driver.getPageSource().contains("Text which you looking for");

【讨论】:

  • AttributeError: 'WebDriver' object has no attribute 'getPageSource'
  • @Cerin 看起来你在 Python 中?这篇文章很可能是用 Java 编写的,所以你可能想把它改成get_page_source。 (我没有专门检查过这个,但是大部分camelCase变成了snake_case。)
【解决方案4】:

您可以按如下方式检查页面源中的文本:

Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))

【讨论】:

    【解决方案5】:

    Selenium 2 webdriver 中没有 verifyTextPresent,因此您必须检查页面源中的文本。请参阅下面的一些实际示例。

    Python

    在Python驱动中你可以编写如下函数:

    def is_text_present(self, text):
        return str(text) in self.driver.page_source
    

    然后将其用作:

    try: self.is_text_present("Some text.")
    except AssertionError as e: self.verificationErrors.append(str(e))
    

    要使用正则表达式,请尝试:

    def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
        self.assertRegex(self.driver.page_source, text)
        return True
    

    完整示例请参见:FooTest.py file。

    或检查以下其他几个替代方案:

    self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
    assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text
    

    来源:Another way to check (assert) if text exists using Selenium Python

    Java

    在Java中如下函数:

    public void verifyTextPresent(String value)
    {
      driver.PageSource.Contains(value);
    }
    

    用法如下:

    try
    {
      Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
      Console.WriteLine("Selenium Wiki test is present on the home page");
    }
    catch (Exception)
    {
      Console.WriteLine("Selenium Wiki test is not present on the home page");
    }
    

    来源:Using verifyTextPresent in Selenium 2 Webdriver


    行为

    对于 Behat,您可以使用 Mink extension。它在MinkContext.php中定义了以下方法:

    /**
     * Checks, that page doesn't contain text matching specified pattern
     * Example: Then I should see text matching "Bruce Wayne, the vigilante"
     * Example: And I should not see "Bruce Wayne, the vigilante"
     *
     * @Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
     */
    public function assertPageNotMatchesText($pattern)
    {
        $this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
    }
    
    /**
     * Checks, that HTML response contains specified string
     * Example: Then the response should contain "Batman is the hero Gotham deserves."
     * Example: And the response should contain "Batman is the hero Gotham deserves."
     *
     * @Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
     */
    public function assertResponseContains($text)
    {
        $this->assertSession()->responseContains($this->fixStepArgument($text));
    }
    

    【讨论】:

      【解决方案6】:

      在python中,你可以简单地检查如下:

      # on your `setUp` definition.
      from selenium import webdriver
      self.selenium = webdriver.Firefox()
      
      self.assertTrue('your text' in self.selenium.page_source)
      

      【讨论】:

      • 不错!像魅力一样工作!
      【解决方案7】:
        boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
          if (Error == true)
          {
           System.out.print("Login unsuccessful");
          }
          else
          {
           System.out.print("Login successful");
          }
      

      【讨论】:

        【解决方案8】:

        在 c# 中,此代码将帮助您检查网页中是否存在所需的文本。

        Assert.IsTrue(driver.PageSource.Contains("Type your text here"));
        

        【讨论】:

          【解决方案9】:

          JUnit+Webdriver

          assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");
          

          如果您的预期文本与 xpath 文本不匹配,webdriver 会告诉您实际文本与您期望的文本。

          【讨论】:

            【解决方案10】:

            Python:

            driver.get(url)
            content=driver.page_source
            if content.find("text_to_search"): 
                print("text is present in the webpage")
            

            下载html页面并使用find()

            【讨论】:

              【解决方案11】:

              string_website.py

              网页中的搜索字符串

                  from selenium import webdriver
                  from selenium.webdriver.common.keys import Keys
                  browser = webdriver.Firefox()
                  browser.get("https://www.python.org/")
                  content=browser.page_source
              
                  result = content.find('integrate systems')
                  print ("Substring found at index:", result ) 
              
                  if (result != -1): 
                  print("Webpage OK")
                  else: print("Webpage NOT OK")
                  #print(content)
                  browser.close()
              

              运行

              python test_website.py
              在索引处找到子字符串:26722
              网页正常


              d:\tools>python test_website.py
              在索引处找到子字符串:-1 ; -1 表示没有找到
              网页不正常

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-12-26
                • 2016-02-03
                • 1970-01-01
                • 2019-08-22
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多