50

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

4

11 回答 11

49

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

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

官方文档不太支持此类任务,但它仍然是基本工具。

JavaDocs更强大,但需要一些时间才能了解所有有用和无用的内容。

要学习 XPath,只需关注互联网。该规范也是一个令人惊讶的好读物。


编辑:

或者,如果您不希望您的隐式等待使上述代码等待文本出现,您可以这样做:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));
于 2012-07-12T15:49:38.397 回答
21

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

driver.getPageSource().contains("Text which you looking for");
于 2012-07-13T05:43:24.693 回答
13

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

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

然后使用断言来检查它,如下所示:

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

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

于 2012-07-12T20:17:03.747 回答
7

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文件以获取完整示例。

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

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

资料来源:另一种使用 Selenium Python 检查(断言)文本是否存在的方法

爪哇

在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");
}

来源:在 Selenium 2 Webdriver 中使用 verifyTextPresent


贝哈特

对于 Behat,您可以使用Mink 扩展。它在 中定义了以下方法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));
}
于 2015-05-11T23:05:26.320 回答
3

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

Assert.IsTrue(driver.PageSource.Contains("Type your text here"));
于 2017-09-17T21:17:36.053 回答
2

您可以检查页面源中的文本,如下所示:

Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))
于 2014-09-24T11:22:47.103 回答
2

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

# on your `setUp` definition.
from selenium import webdriver
self.selenium = webdriver.Firefox()

self.assertTrue('your text' in self.selenium.page_source)
于 2016-04-22T15:32:18.387 回答
2

Python:

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

下载 html 页面并使用 find()

于 2019-03-12T19:15:42.093 回答
0
  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");
    }
于 2016-12-06T02:58:03.693 回答
0

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 将告诉您实际文本与您期望的文本。

于 2018-10-02T18:42:23.543 回答
0

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
在 index: -1 处找到子字符串;-1 表示没有找到
网页不正常

于 2020-03-24T10:38:44.943 回答