本文主要记录下在使用selenium2/webdriver时启动各种浏览器的方法、以及如何加载插件、定制浏览器信息(设置profile)等

 

Selenium Driver下载地址

selenium 下载地址:https://docs.seleniumhq.org/download/

selenium 源码github:https://github.com/SeleniumHQ/selenium

chromedriver 下载地址:http://chromedriver.storage.googleapis.com/index.html

 

1、 对浏览器操作

1.1 用webdriver打开一个浏览器

WebDriver driver = new FirefoxDriver();           	// 打开firefox浏览器:
WebDriver driver = new InternetExplorerDriver();	// 打开IE浏览器
WebDriverdriver = new HtmlUnitDriver();          	// 打开HtmlUnit浏览器
WebDriverdriver = new ChromeDriver();    			// 打开chrome浏览器

 

1.2 最大化浏览器&关闭浏览器

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.close();
driver.quit();

 

1.3 设置浏览器窗口大小

private static void SetWindowTest(WebDriver driver) throws InterruptedException {
    // 设置窗口的 宽度为:800,高度为600
    Dimension d = new Dimension(800, 600);
    driver.manage().window().setSize(d);
    Thread.sleep(2000);

    // 设置窗口最大化
    driver.manage().window().maximize();
    Thread.sleep(2000);

    // 设置窗口出现在屏幕上的坐标
    Point p = new Point(500, 300);
    
    // 执行设置
    driver.manage().window().setPosition(p);
    Thread.sleep(2000);
}

 

1.4 打开测试页面

打开测试页面
driver.get("https://mimvp.com");
driver.navigate().to("https://mimvp.com"); 
//navigate方法会产生1个Navigator对象,其封装了与导航相关的一些方法,比如前进后退等

 

1.5 处理浏览器弹出的新窗口

private static void MutiWindowTest(WebDriver driver) throws InterruptedException {
    WebDriver newWindow = null ;
    driver.get("https://mimvp.com");
    
    // 浏览器最大化
    driver.manage().window().maximize();
    
    // 获取当前页面句柄
    String current_handles = driver.getWindowHandle();
    
    // 点击 百度链接
    driver.findElement(By.xpath("//*[@data-title='百度']")).click();
    
    // 接下来会有新的窗口打开,获取所有窗口句柄
    Set<String> all_handles = driver.getWindowHandles();
    
    // 循环判断,把当前句柄从所有句柄中移除,剩下的就是你想要的新窗口
    Iterator<String> it = all_handles.iterator();
    while(it.hasNext()){
    if(current_handles == it.next()) continue;
    	// 跳入新窗口,并获得新窗口的driver - newWindow
     	newWindow = driver.switchTo().window(it.next());
    }
    
    // 接下来在新页面进行操作,也就是百度首页,我们输入一个java关键字进行搜索
    Thread.sleep(5000);
    WebElement baidu_keyowrd = newWindow.findElement(By.id("kw"));
    baidu_keyowrd.sendKeys("java");
    Thread.sleep(1000);
    
    // 关闭当前窗口,主要使用close而不是quite,
    newWindow.close();
    driver.switchTo().window(current_handles);
    System.out.println(driver.getCurrentUrl());
}

 

2、 页面元素定位

Webdriver提供下面两种方法来定位页面元素,参数是By对像,最常用是By.id和By.name查找。

  • findElement   定位某个元素,如果没有找到元素会抛出异常:NoSuchElementException
  • findElements     定位一组元素

例如需要定位如下元素: 

<input class="input_class" type="text" name="passwd" id="passwd-id" /> 

源码:

// By.id
WebElement element = driver.findElement(By.id("passwd-id"));

// By.name
WebElement element = driver.findElement(By.name("passwd"));

// By.xpath
WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']")); 

// By.className
WebElement element = driver.findElement(By.className("input_class"));

// By.cssSelector
WebElement element = driver.findElement(By.cssSelector(".input_class"));

// By.linkText
// 通俗点就是精确查询
WebDriver driver = new FirefoxDriver();
driver.get("https://mimvp.com"); 
WebElement element = driver.findElement(By.linkText("百科"));

// By.partialLinkText:
// 这个方法就是模糊查询
WebDriver driver = new FirefoxDriver();
driver.get("https://mimvp.com"); 
WebElement element = driver.findElement(By.partialLinkText("hao"));

// By.tagName
WebDriver driver = new FirefoxDriver();
driver.get("https://mimvp.com"); 
String test= driver.findElement(By.tagName("form")).getAttribute("name");
System.out.println(test);

 

3、 如何对页面元素进行操作

3.1 WebElement相关方法

Method Summary
void clear() If   this element is a text entry element, this will clear the value.
void click() Click   this element.
WebElement findElement(By by) Find   the first WebElement  using the given method.
 java.util.List<WebElement> findElement(By   by) Find   all elements within the current context using the given mechanism.
 java.lang.String getAttribute(java.lang.String   name) Get   the value of a the given attribute of the element.
 java.lang.String getCssValue(java.lang.String.propertyName) Get   the value of a given CSS property.
Point GetLocation() Where   on the page is the top left-hand corner of the rendered element?
 Dimension getSize() What   is the width and height of the rendered element?
 java.lang.String getTagName()  Get   the tag name of this element.
 java.lang.String getText()  Get   the visible (i.e. not hidden by CSS) innerText of this element, including
sub-elements, without any leading or trailing whitespace.
 boolean isDisplayed() Is   this element displayed or not? This method avoids the problem of having to   parse an element's "style" attribute.
 boolean isEnabled() Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
 boolean isSelected() Determine   whether or not this element is selected or not.
 void sendKeys(java.lang.CharSequence...   keysToSend) Use   this method to simulate typing into an element, which may set its value.
 void submit() If   this current element is a form, or an element within a form, then this will   be submitted to the remote server.

 

3.2 iFrame的处理

driver.switchTo().frame(“city_set_ifr”);    // 传入的是iframe的ID
dr.switchTo().defaultContent();               // 如果要返回到以前的默认content

 

3.3 输入框(text field or textarea)

WebElement element = driver.findElement(By.id("passwd-id"));
element.sendKeys(“test”);	// 在输入框中输入内容:
element.clear();       	// 将输入框清空
element.getText();     	// 获取输入框的文本内容:

 

3.4 下拉选择框(Select)

Select select = new Select(driver.findElement(By.id("select")));  
select.selectByVisibleText(“A”);
select.selectByValue(“1”); 
select.deselectAll();
select.deselectByValue(“1”);
select.deselectByVisibleText(“A”);
select.getAllSelectedOptions();
select.getFirstSelectedOption();

示例:

package seleniumAPIDemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectDemo {

    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        iframeAndSelectTest(driver);
        driver.quit();
    }

    private static void iframeAndSelectTest(WebDriver driver)
            throws InterruptedException {
        driver.get("https://mimvp.com");
        
        //浏览器最大化
        driver.manage().window().maximize();
        //点击切换按钮
        driver.findElement(By.id("J_city_switch")).click();
        //进入天气城市选择iframe
        driver.switchTo().frame("city_set_ifr");        
        Thread.sleep(2000);
        
        //然后在进行选择城市
        //定位 省下拉框                                                                          
        Select province = new Select(driver.findElement(By.id("province")));
        province.selectByValue("20");
        Thread.sleep(2000);
    
        //定位 城市下拉框
        Select city = new Select(driver.findElement(By.id("chengs")));
        city.selectByIndex(0);
        Thread.sleep(2000);
        
        //定位区
        Select region = new Select(driver.findElement(By.id("cityqx")));
        region.selectByVisibleText("X 新密");
        Thread.sleep(2000);
        
        //点击定制按钮
        driver.findElement(By.id("buttonsdm")).click();
        Thread.sleep(2000);
        //返回默认的content
        driver.switchTo().defaultContent();
    }
}

 

3.5 单选项(Radio Button)

WebElement radio=driver.findElement(By.id("BookMode"));
radio.click();       // 选择某个单选项
radio.clear();      // 清空某个单选项
radio.isSelected();  // 判断某个单选项是否已经被选择

 

3.6 多选项(checkbox)

WebElement checkbox = driver.findElement(By.id("myCheckbox."));
checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();

 

3.7 按钮(button)

WebElement btn= driver.findElement(By.id("save"));
btn.click();      // 点击按钮
btn.isEnabled ();    // 判断按钮是否enable

 

3.8 处理Alert

弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();
alert.accept();  // 确定
alert.dismiss();   // 取消
alert.getText();   // 获取文本

示例:

private static void alertTest(WebDriver driver) throws InterruptedException {   
    driver.get("http://www.w3school.com.cn/tiy/t.asp?f=hdom_alert");
    
    //浏览器最大化
    driver.manage().window().maximize();
    
    //进入frame
    driver.switchTo().frame("i");
    
    //找到按钮并点击按钮
    driver.findElement(By.xpath("//*[@value='显示消息框']")).click();
    Thread.sleep(2000);
    
    //获取Alert
    Alert a = driver.switchTo().alert();
    
    //打印出文本内容
    System.out.println(a.getText());
    
    //点击确定
    Thread.sleep(2000);
    
    a.accept();
	// 如果alert上有取消按钮,可以使用a.dismiss()代码
}

 

3.9 上传文件

3.9.1 元素标签是Input时上传方式

Upload.html文件内容如下:

<body>
<input type="file" id="fileControl" value="选择文件"/>
</body>

代码如下:

private static void uploadTest1(WebDriver driver) throws InterruptedException {
    //打开上传的网页 - get中输入upload的地址
    driver.get("D:\\DownLoad\\UploadTest\\upload.html");
    WebElement e1 = driver.findElement(By.id("fileControl"));
    Thread.sleep(2000);
    
    //输入要上传文件的地址
    e1.sendKeys("D:\\DownLoad\\UploadTest\\被上传的文件.txt");
    Thread.sleep(2000);
}

 

3.9.2 通过操作桌面浏览窗口上传

示例 上传文件

当上传控件不是input元素,而是桌面窗口,这个时候利用Selenium的sendkeys方法是行不通的。可以用autoIt来操作。

被测网页代码'upload.html':

<body>
<input type="file" id="fileControl" value="选择文件"/>
</body>

自动化操作代码'uploadFile.au3':

;first make sure the number of arguments passed into the scripts is more than 1
If $CmdLine[0]<2 Then Exit EndIf ;if parmas num <2 ,then break
;$CmdLine[0] ;参数的数量
;$CmdLine[1] ;第一个参数 (脚本名称后面)
;$CmdLine[2] ;第二个参数
;都是从cmd传入参数
 handleUpload($CmdLine[1],$CmdLine[2])

;定义上传函数,有两个参数,第一个是浏览器名字,第二参数是文件路径
 Func handleUpload($browser, $uploadfile)
     Dim $title                          ;定义一个title变量
            ;根据弹窗的title来判断是什么浏览器
            If $browser="ie" Then                          ; 代表IE浏览器
                  $title="选择要加载的文件"
            ElseIf $browser="chrome" Then               ; 代表谷歌浏览器
                 $title="打开"
            ElseIf    $browser="firefox" Then             ; 代表火狐浏览器
                  $title="文件上传"
            EndIf

            if WinWait($title,"",4) Then ;等待弹出出现,最大等待时间是4秒
                   WinActivate($title)                  ;找到弹出窗口之后,激活当前窗口
                   ControlSetText($title,"","Edit1",$uploadfile)   ;把文件路径放入输入框
                   ControlClick($title,"","Button1")                ;点击保存或者打开或者上传按钮
            Else
            Return False
            EndIf
 EndFunc

操作步骤:

1)把'uploadFile.au3'转化成'uploadFile.exe''

2)用ie打开被测网页代码'upload.html',并点击'浏览'元素,系统自动打开桌面浏览窗口,如下图3所示

3)打开cmd.exe窗口,输入以下命令,按回车执行,结果如下图所示

"D:\TestUploadFileWithAutoit\uploadFile.exe" "ie" "D:\TestUploadFileWithAutoit\1.png"

Java调用Upload.exe代码:

public void handleUpload(String browser, File file) {
    String filePath= file.getAbsolutePath();
    String executeFile= "D:\\TestUploadFileWithAutoit\\UploadFile.exe"; 
    String cmd= "\""+ executeFile+ "\""+ " "+ "\""+ browser+ "\""+ " "+ "\""+ filePath+ "\"";
    try{
        Process p= Runtime.getRuntime().exec(cmd);
        p.waitFor();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

 

3.10 Selenium处理HTML5

3.10.1 处理Vedio

这就需要了解html5中vedio的相关方法了,可以参考:http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp

private static void html5VedioTest(WebDriver driver) throws InterruptedException {
    driver.get("https://mimvp.com");
    Thread.sleep(2000);
    
    // 找到vedio元素
    WebElement vedio = driver.findElement(By.id("preview-player_html5_api"));
    
    // 声明js执行器
    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // 对vedio这个元素执行播放操作 
    js.executeScript("arguments[0].play()", vedio);
    
    // 为了观察效果暂停5秒
    Thread.sleep(5000);
    
    // 对vedio这个元素执行暂停操作
    js.executeScript("arguments[0].pause()", vedio);
    
    // 为了观察效果暂停2秒
    Thread.sleep(2000);
    
    // 对vedio这个元素执行播放操作 
    js.executeScript("arguments[0].play()", vedio);
    
    // 为了观察效果暂停2秒
    Thread.sleep(2000);
    
    // 对vedio这个元素执行重新加载视频的操作
    js.executeScript("arguments[0].load()", vedio);
    
    // 为了观察效果暂停2秒
    Thread.sleep(2000);
}

 

3.10.2 处理Canvas 

private static void Html5CanvasTest(WebDriver driver) throws InterruptedException {
    driver.get("https://mimvp.com");
    Thread.sleep(2000);
    
    //找到canvas元素
    WebElement canvas = driver.findElement(By.xpath("//*[@id='literally-canvas']//canvas[1]"));
    
    //声明一个操作类
    Actions drawPen = new Actions(driver);
    
    //点击并保持不放鼠标 ,按照给定的坐标点移动
    drawPen.clickAndHold(canvas).moveByOffset(20, 100).moveByOffset(100, 20).moveByOffset(-20, -100).moveByOffset(-100, -20).release().perform();
    Thread.sleep(2000);
}

 

3.11 表单(Form)

// Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:
WebElement approve = driver.findElement(By.id("approve"));
approve.click();
// 或
approve.submit();//只适合于表单的提交

 

4 其他

4.1 等待元素加载

超时设置

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);		// 识别元素时的超时时间
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);		// 页面加载时的超时时间
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);		// 异步脚本的超时时间

说明:

  • 硬性等待  Thread.sleep(int sleeptime);
  • 智能等待
  • 设置等待页面加载完毕

代码:

private static void waitElementTest(WebDriver driver) {
    // 设置等待页面完全加载的时间是10秒,如果在10秒内加载完毕,剩余时间不在等待
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.get("https://mimvp.com");
    By inputBox = By.id("kw");
    By searchButton = By.id("su");
    
    // 智能等待元素加载出来
    intelligentWait(driver, 10, inputBox);
    
    // 智能等待元素加载出来
    intelligentWait(driver, 10, searchButton);
    
    // 输入内容
    driver.findElement(inputBox).sendKeys("JAVA");
    
    // 点击查询
    driver.findElement(searchButton).click();
}


public static void intelligentWait(WebDriver driver,int timeOut, final By by){        
    try {
        (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                WebElement element = driver.findElement(by);
                return element.isDisplayed();
            }
        });
    } catch (TimeoutException e) {
        Assert.fail("超时!! " + timeOut + " 秒之后还没找到元素 [" + by + "]",e);
    }
}

 

4.2 执行JS脚本

selenium常用的js总结

有时候我们需要JS脚本来辅助我们进行测试,比如我们用JS赋值或者用js执行点击操作等。

执行JS脚本比较适用某些元素不易点击的情况下使用,比如网页内容太长,当前窗口太长,想要点击那些不在当前窗口可以看到元素可以用此方法。 

private static void runJSTest1(WebDriver driver) throws InterruptedException {
    String js ="alert(\"hello,this is a alert!\")";
    ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js);
    Thread.sleep(2000);
}

private static void runJSTest2(WebDriver driver) throws InterruptedException {
    driver.get("https://mimvp.com");
    String js ="arguments[0].click();";
    driver.findElement(By.id("kw")).sendKeys("JAVA");
    WebElement searchButton = driver.findElement(By.id("su"));
    ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js,searchButton);
    Thread.sleep(2000);
}

 

4.3 模拟键盘操作

有时候有些元素不便点击或者做其他的操作,这个时候可以借助selenium提供的Actions类,

它可以模拟鼠标和键盘的一些操作,比如点击鼠标右键,左键,移动鼠标等操作。对于这些操作,使用perform()方法进行执行。

private static void actionsTest(WebDriver driver) throws InterruptedException {
    // 设置等待页面完全加载的时间是10秒,如果在10秒内加载完毕,剩余时间不在等待
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.get("https://mimvp.com");
    By inputBox = By.id("kw");
    By searchButton = By.id("su");
    
    // 智能等待元素加载出来
    intelligentWait(driver, 10, inputBox);
    
    // 智能等待元素加载出来
    intelligentWait(driver, 10, searchButton);
    
    // 实例化action对象
    Actions action = new Actions(driver);
    
    // 通过action模拟键盘输入java关键字到 输入框,只有使用了perform方法才会输入进去
    action.sendKeys(driver.findElement(searchButton), "java").perform();
    
    // 鼠标模拟移动到搜索按钮
    action.moveToElement(driver.findElement(searchButton)).perform();
    
    // 模拟点击操作
    action.click().perform();
    Thread.sleep(2000);
}

 

原文参考Selenium Web 自动化 - Selenium常用API  (推荐

 

 

参考推荐

Python3.5 + Selenium3.4 + Webdriver 自动化测试

Selenium2.0 Python 常用函数

WebDriver配置Firefox代理服务器

Python+Selenium2 搭建自动化测试环境

Python + Selenium + Firefox 使用代理 auth 的用户名密码授权

Python + Selenium + Chrome 使用代理 auth 的用户名密码授权

Selenium Webdriver 以代理proxy方式启动firefox,ie,chrome

Selenium 设置 webdriver 启动浏览器、设置profile、加载插件

Python + Selenium2 + Chrome 爬取网页