web-dev-qa-db-ja.com

Seleniumを使用して、ページにテキストが存在するかどうかを確認するにはどうすればよいですか?

Selenium WebDriverを使用していますが、ページにテキストが存在するかどうかを確認するにはどうすればよいですか?たぶん誰かが私がそれについて読むことができる役に立つリソースを私に勧めます。ありがとう

45
khris

XPath を使用すると、それほど難しくありません。指定されたテキストを含むすべての要素を検索するだけです:

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

公式ドキュメント は、このようなタスクにはあまり役立ちませんが、それでも基本的なツールです。

JavaDocs の方が優れていますが、有用で役に立たないものすべてを理解するには時間がかかります。

XPathを学習するには、 インターネットに従う だけです。仕様も驚くほど良い読み物です。


編集:

または、 Implicit Wait でテキストが表示されるまで上記のコードを待機させたくない場合は、次の方法で何かを行うことができます。

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

これは、必要なテキストがWebページにあるかどうかを確認するのに役立ちます。

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

次のようにしてページ全体の本文を取得できます。

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

次のようにアサートを使用して確認します。

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

もちろん、特定のDOM要素のテキストを特定して取得し、ページ全体を取得する代わりにそれを確認することもできます。

13
JCarter

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

ソース: 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");
}

ソース: Selenium 2 WebdriverでverifyTextPresentを使用


ビハット

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
kenorb

Pythonでは、次のように簡単に確認できます。

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

self.assertTrue('your text' in self.Selenium.page_source)
2
Adiyat Mubarak

C#では、このコードは、必要なテキストがWebページにあるかどうかを確認するのに役立ちます。

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

Python:

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

Htmlページをダウンロードし、find()を使用します

1
Dipankar Nalui

次のようにして、ページソースのテキストを確認できます。

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

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は、実際のテキストと予想した内容を通知します。

0
Dan
  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
fart