Selenium WebDriver java 简单实例

  1. 开发环境
    JDK
    下载地址:
    http://www.oracle.com/technetwork/java/javase/downloads/index.html

    Eclipse:
    下载地址:http://www.eclipse.org/downloads/

    Selenium jar包
    (这里用的是:selenium-java-2.45.0.zip ,selenium-server-standalone-2.45.0.jar)
    下载地址:http://code.google.com/p/selenium/downloads/list

  2. 开发工具
    打开Eclipse,新建一个java工程,在工程的下面新建一个lib文件夹
    把selenium-java-2.45.0.zip 解压过的文件 和selenium-server-standalone-2.45.0.jar,全部复制进去
    这里写图片描述

    ps: 其实这些jar,放在那里无所谓,引用的时候只要给个绝对路径都是可以的,还有Selenium 对应的浏览器的版本也有严格的 要求,对于不同的火狐浏览器,selenium的版本也是不同的,如果仅仅是java项目启动webdriver,那么必须要对应版本的selenium-server-standalone-2.45.0.jar

    接下来Build Path
    项目目录右键–>Build Path–> config build path–>Java Build Path–>Libraries–>Add JARs
    把lib下所有的jar全部添加上,包括selenium-server-standalone-2.45.0.jar,然后一路Ok,
    这里写图片描述

    最后会看到项目下多了一个映射的类库 Referenced Libraries
    这里写图片描述

  3. 代码示例
    准备工作做到这里,接下来要做的就是开始写代码了,在Src文件夹下,新建一个包,新建一个类

    这里写图片描述

代码如下:
(启动浏览器,百度搜索HelloWorld,运行结束后,关闭浏览器)

package com.selenium.test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class seleniumHello {

    public static void main(String[] args) {
        //如果火狐浏览器没有默认安装在C盘,需要制定其路径
        System.setProperty("webdriver.firefox.bin", "D:/Program Files (x86)/Mozilla Firefox/firefox.exe"); 

        //定义驱动对象为 FirefoxDriver 对象
        WebDriver driver = new FirefoxDriver();


        //驱动的网址
        driver.get("http://www.baidu.com/");


        //浏览器窗口变大
        driver.manage().window().maximize();

        //定位输入框元素
        WebElement txtbox = driver.findElement(By.name("wd"));

        //在输入框输入文本
        txtbox.sendKeys("HelloWorld");

        //定位按钮元素
        WebElement btn = driver.findElement(By.id("su"));

        //点击按钮
        btn.click();


        //关闭驱动
        driver.close();


    }

}
事在人为,功不唐捐
原文地址:https://www.cnblogs.com/xinleishare/p/4570140.html