如何使用Selenium检查页面中是否存在某些文本?

问题描述 投票:44回答:10

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

validation selenium webdriver assert
10个回答
45
投票

有了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));

0
投票

蟒蛇:

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

下载html页面并使用find()


20
投票

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

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

13
投票

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

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

然后使用断言来检查它:

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

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


6
投票

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

对于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));
}

2
投票

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

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

self.assertTrue('your text' in self.selenium.page_source)

1
投票

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

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

1
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.