Wednesday, September 21, 2011

Selenium 2.0 (Webdriver) How To with Java + Eclipse



Так как Selenium сейчас очень активно развивается, перед началом работы, необходимо скачать последнию версию с официального сайта. Для работы с Selenium 2.0 (WebDriver) нет необходимости в его отельном запуске как это было ранее. Создавая новый проект, в Eclipse в свойствах проекта нужно добавить путь к jar-файлу.



Для проверки присутствия элементов на веб-странице в Selenium RC (1.0) есть метод selenium.isElementPresent(). Для WebDriver аналогично можно использовать метод findElement(), который генерирует исключение NoSuchElementException, если элемент отсутсвтует на странице:

public static boolean isElementPresent(WebDriver driver, By by) { 
  try { 
    driver.findElement(by); 
    return true;  // Success! 
  } catch (NoSuchElementException ignored) { 
    return false; 
  } 

}


//Example 1:
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example  {
    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
    }
}


//Example 2:

package org.openqa.selenium.example;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript 
        WebDriver driver = new FirefoxDriver();
        
        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");
        
        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

        // Sleep until the div we want is visible or 5 seconds is over
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            WebElement resultsDiv = driver.findElement(By.className("gac_m"));

            // If results have been returned, the results are displayed in a drop down.
            if (resultsDiv.isDisplayed()) {
              break;
            }
        }

        // And now list the suggestions
        List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[@class='gac_c']"));
        
        for (WebElement suggestion : allSuggestions) {
            System.out.println(suggestion.getText());
        }
     }
}

Source: http://code.google.com

No comments:

Post a Comment