Эквивалент isTextPresent для Selenium 1 (Selenium RC) в Selenium 2 (WebDriver)

Там нет isTextPresent в Selenium 2 (WebDriver)

Каков правильный способ утверждать существование какого-либо текста на странице с помощью WebDriver?

Ответы

Ответ 1

Я обычно делаю что-то вроде:

assertEquals(driver.getPageSource().contains("sometext"), true);

assertTrue(driver.getPageSource().contains("sometext"));

Ответ 2

Источник страницы содержит HTML-теги, которые могут разорвать ваш текст поиска и привести к ложным отрицаниям. Я нашел, что это решение работает так же, как Selenium RC isTextPresent API.

WebDriver driver = new FirefoxDriver(); //or some other driver
driver.findElement(By.tagName("body")).getText().contains("Some text to search")

делает getText, а затем содержит имеет компромисс производительности. Возможно, вы захотите сузить дерево поиска, используя более конкретный WebElement.

Ответ 3

Я знаю, что это немного устарело, но я нашел здесь хороший ответ: Selenium 2.0 Web Driver: реализация isTextPresent

В Python это выглядит так:

def is_text_present(self, text):
    try: el = self.driver.find_element_by_tag_name("body")
    except NoSuchElementException, e: return False
    return text in el.text

Ответ 4

Или, если вы хотите проверить текстовое содержимое WebElement, вы можете сделать что-то вроде:

assertEquals(getMyWebElement().getText(), "Expected text");

Ответ 5

Selenium2 Java-код для isTextPresent (Selenium IDE Code) в JUnit4

public boolean isTextPresent(String str)
{
    WebElement bodyElement = driver.findElement(By.tagName("body"));
    return bodyElement.getText().contains(str);
}

@Test
public void testText() throws Exception {
    assertTrue(isTextPresent("Some Text to search"));
}

Ответ 6

Следующий код с использованием Java в WebDriver должен работать:

assertTrue(driver.getPageSource().contains("Welcome Ripon Al Wasim"));
assertTrue(driver.findElement(By.id("widget_205_after_login")).getText().matches("^[\\s\\S]*Welcome ripon[\\s\\S]*$"));

Ответ 7

Я написал следующий метод:

public boolean isTextPresent(String text){
        try{
            boolean b = driver.getPageSource().contains(text);
            return b;
        }
        catch(Exception e){
            return false;
        }
    }

Вышеуказанный метод называется следующим:

assertTrue(isTextPresent("some text"));

Он прекрасно работает.

Ответ 8

Тестирование, если текст присутствует в Ruby (подход новичков), используя firefox в качестве целевого браузера.

1) Конечно, вам нужно скачать и запустить файл jar selenium server с чем-то вроде:

java - jar C:\Users\wmj\Downloads\selenium-server-standalone-2.25.0.jar

2) Вам нужно установить ruby, а в папке bin запустить команды для установки дополнительных камней:

gem install selenium-webdriver
gem install test-unit

3) создайте файл test-it.rb, содержащий:

require "selenium-webdriver"
require "test/unit"

class TestIt < Test::Unit::TestCase

    def setup
        @driver = Selenium::WebDriver.for :firefox
        @base_url = "http://www.yoursitehere.com"
        @driver.manage.timeouts.implicit_wait = 30
        @verification_errors = []
        @wait = Selenium::WebDriver::Wait.new :timeout => 10
    end


    def teardown
        @driver.quit
        assert_equal [], @verification_errors
    end

    def element_present?(how, what)
        @driver.find_element(how, what)
        true
        rescue Selenium::WebDriver::Error::NoSuchElementError
        false
    end

    def verify(&blk)
        yield
        rescue Test::Unit::AssertionFailedError => ex
        @verification_errors << ex
    end

    def test_simple

        @driver.get(@base_url + "/")
        # simulate a click on a span that is contained in a "a href" link 
        @driver.find_element(:css, "#linkLogin > span").click
        # we clear username textbox
        @driver.find_element(:id, "UserName").clear
        # we enter username
        @driver.find_element(:id, "UserName").send_keys "bozo"
        # we clear password
        @driver.find_element(:id, "Password").clear
        # we enter password
        @driver.find_element(:id, "Password").send_keys "123456"
        # we click on a button where its css is named as "btn"
        @driver.find_element(:css, "input.btn").click

        # you can wait for page to load, to check if text "My account" is present in body tag
        assert_nothing_raised do
            @wait.until { @driver.find_element(:tag_name=>"body").text.include? "My account" }
        end
        # or you can use direct assertion to check if text "My account" is present in body tag
        assert(@driver.find_element(:tag_name => "body").text.include?("My account"),"My account text check!")

        @driver.find_element(:css, "input.btn").click
    end
end

4) запустить ruby:

ruby test-it.rb