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