对于这一段还蛮有感慨的,只想说,代码还是需要自己去敲的。

1. 改变用户代理

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile; public class ProxyTest {
static WebDriver driver; @BeforeClass
public static void beforeClass(){
//代理的IP和端口
String proxyIP="192.168.12.0";
int proxyPort=80;
FirefoxProfile profile=new FirefoxProfile();
//使用代理
profile.setPreference("network.proxy.type", 1);
//配置“HTTP代理:(N)”
profile.setPreference("network.proxy.http", proxyIP);
profile.setPreference("network.proxy.http_prot", proxyPort);
//选中 “为所有协议使用相同代理(S)” 选框
profile.setPreference("network.proxy.share_proxy_settings", true);
//配置“不使用代理:(N)”文本框
profile.setPreference("network.proxy.no_proxies_on", "localhost, 127.0.0.1");
//以代理的方式启动火狐
driver=new FirefoxDriver(profile);
} @Test
public void test() {
driver.get("http://www.baidu.com");
} @AfterClass
public static void afterClass(){
//driver.quit();
}
}

运行之后,在打开的火狐上查看代理设置(选项->高级->网络->连接->设置),显示如下:

友情提示:测试完之后一定要改回来。默认是“使用系统代理设置”。

2.读取Cookies

增加cookie:

Cookie cookie = new Cookie("key", "value");

driver.manage().addCookie(cookie);

获取cookie的值:

Set<Cookie> allCookies = driver.manage().getCookies();

根据某个cookie的name获取cookie的值:

driver.manage().getCookieNamed("cookieName");

删除cookie:

driver.manage().deleteCookieNamed("CookieName");

driver.manage().deleteCookie(loadedCookie);

driver.manage().deleteAllCookies();

下面是一个例子:

import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; public class CookieTest {
WebDriver driver; @Before
public void setUp() throws Exception {
driver=new FirefoxDriver();
} @After
public void tearDown() throws Exception {
driver.quit();
} @Test
public void test() {
printCookie();
//添加一个cookie
Cookie cookie=new Cookie("s","selenium");
driver.manage().addCookie(cookie);
printCookie();
//删除一个cookie
driver.manage().deleteCookie(cookie); //driver.manage().deleteCookieNamed("s");也可以
printCookie();
} public void printCookie(){
//获取并打印所有的cookie
Set<Cookie> allCookies=driver.manage().getCookies(); System.out.println("----------Begin---------------");
for(Cookie c:allCookies){
System.out.println(String.format("%s->%s",c.getName(),c.getValue()));
}
System.out.println("----------End---------------");
}
}

运行结果显示为:

----------Begin---------------
----------End---------------
----------Begin---------------
s->selenium
----------End---------------
----------Begin---------------
----------End---------------
可以看到添加cookie之前,系统的cookie为空。之后成功添加了cookie(s,selenium)并且最后成功删除。

3. 调用Java Script

selenium提供了executeScriptexecuteAsyncScript两个方法来处理JS调用的问题。其中executeScript是同步方法,用它执行js代码会阻塞主线程执行,直到js代码执行完毕;executeAsyncScript方法是异步方法,它不会阻塞主线程执行。

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor; public class JSTest {
@Test
public void test() {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.baidu.com");
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("document.getElementById(\"kw\").value=\"selenium\"");
//利用js代码获取百度搜索框内文字
String keyword = (String) (js.executeScript("var input = document.getElementById(\"kw\").value;return input"));
System.out.println(keyword);
driver.quit();
}
}

运行结果:

selenium

4. Webdriver截图

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; public class ScreenShotTest { @Test
public void test() {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.baidu.com");
screenShot("selenium.jpg", (TakesScreenshot)driver);
driver.quit();
} public static void screenShot(String name,TakesScreenshot driver){
String savaPath=System.getProperty("user.dir");
File sourceFile=driver.getScreenshotAs(OutputType.FILE);
try{
System.out.println("Begin saving screenshot to path:"+savaPath);
FileUtils.copyFile(sourceFile, new File(savaPath+"\\"+name));
} catch(IOException e){
System.out.println("Save screenshot failed!");
e.printStackTrace();
} finally{
System.out.println("Finish screenshot!");
}
}
}

运行结果:

Begin saving screenshot to path:D:\workspace_luna\SeleniumDemo
Finish screenshot!

由于eclipse的workspace不一样,会导致上面的路径不一样。不过没关系,我们打开对应的路径就可以看到selenium.jpg。打开以后是百度首页的截图。

5. 页面等待

因为Load页面需要一段时间,如果页面还没加载完就查找元素,必然是查找不到的。最好的方式,就是设置一个默认等待时间,在查找页面元素的时候如果找不到就等待一段时间再找,直到超时。Webdriver提供两种方法,一种是显性等待,另一种是隐性等待。

显性等待:

显示等待就是明确的要等到某个元素的出现或者是某个元素的可点击等条件,等不到,就一直等,除非在规定的时间之内都没找到,那么就跳出Exception.

new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));

当然也可以自己重写内部类:

WebElement e = (new WebDriverWait( driver, 10)).until(
new ExpectedCondition< WebElement>(){
@Override
public WebElement apply( WebDriver d) {
return d.findElement(By.linkText("Selenium_百度百科"));
}
});

下面的例子是:打开百度,搜索“selenium",等待搜索结果里出现“Selenium_百度百科”的时候点击该链接。

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait; public class ExplicitWaitTest {
@Test
public void test() {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.baidu.com");
driver.findElement(By.id("kw")).sendKeys("selenium");
driver.findElement(By.id("su")).click();
//方法一
//new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.linkText("Selenium_百度百科")));
//driver.findElement(By.linkText("Selenium_百度百科")).click();
//方法二
WebElement e = (new WebDriverWait( driver, 10)).until(
new ExpectedCondition< WebElement>(){
@Override
public WebElement apply( WebDriver d) {
return d.findElement(By.linkText("Selenium_百度百科"));
}
}
);
e.click(); driver.quit();
}
}

运行的话是通过的,但是如果中间不显示等待的话,直接查找就会fail。

隐性等待:

隐形等待只是等待一段时间,元素不一定要出现,只要时间到了就会继续执行。

还是上面的例子,用隐性等待写就是:

import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; public class ImplicitWaitTest {
@Test
public void test() {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.baidu.com");
driver.findElement(By.id("kw")).sendKeys("selenium");
driver.findElement(By.id("su")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.linkText("Selenium_百度百科")).click(); driver.quit();
}
}

运行结果还是通过的。不过个人觉得看起来跟笨方法”Thread.sleep()"差不多,只不多比它更高效了而已。

Selenium webdriver Java 高级应用的更多相关文章

  1. Selenium Webdriver java 积累一

    Selenium Webdriver 学习: http://jarvi.iteye.com/category/203994 https://github.com/easonhan007/webdriv ...

  2. [selenium webdriver Java]常用api

    1. 获取元素文本 WebElement类的getText()方法返回元素的innerText属性.所以元素里如果有子节点一样也会被返回出来.如下所示 public class GetText { @ ...

  3. [selenium webdriver Java]元素定位——findElement/findElements

    策略 语法 语法 描述 By id driver.findElement(By.id()) driver.findElements(By.id()) 通过id属性定位元素 By name driver ...

  4. [selenium webdriver Java]隐式的等待同步

    Selenium WebDriver提供了隐式等待来同步测试.当使用了隐式等待执行测试的时候,如果WebDriver没有在DOM中找到元素,将继续等待,超出设定时间后,抛出找不到元素异常 即,当元素没 ...

  5. Selenium WebDriver java 简单实例

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

  6. Java 学习笔记 (二) Selenium WebDriver Java 弹出框

    下面这段实例实现了以下功能: 1. profile使用用户本地电脑上的 (selenium 3有问题.因为selenium 3把profile复制到一个temp文件夹里,但并不复制回去.所以每次打开仍 ...

  7. Selenium webdriver Java 操作IE浏览器

    V1.0版本:直接新建WebDriver使用 import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetE ...

  8. Selenium webdriver Java firefox 路径设置问题

    问题: Cannot find firefox binary in PATH. Make sure firefox is installed. 原因:selenium找不到Firefox浏览器. 方法 ...

  9. Selenium webdriver Java 开始

    最早接触的selenium是 selenium IDE,当时是为了准备论文.为了用IDE还下载了Firefox浏览器.后来接触过两个项目都需要selenium,一个采用selenium webdirv ...

随机推荐

  1. sping PropertyPlaceholderConfigurer

    例如,要载入配置文件中的mysql配置信息: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mypage ...

  2. [BZOJ3209]花神的数论题 组合数+快速幂

    3209: 花神的数论题 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 2498  Solved: 1129[Submit][Status][Disc ...

  3. C# 连接SQL数据库以及操作数据库

    1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlCommand对象,负责SQL语句的执行和存储过程的调 ...

  4. 随机数问题--已知有个Random7()的函数,返回1到7随机自然数,让利用这个Random7()构造Random10()随机1~10.

    Math.random()随机生成(0,1)之间的float数,Random7随机生成[1,7]之间的整数,利用Random7构造Random10的步骤: 1.生成数a:a是两次Random7的结果, ...

  5. Educational Codeforces Round 30 A[水题/数组排序]

    A. Chores time limit per test 2 seconds memory limit per test 256 megabytes input standard input out ...

  6. HDU 3516 Tree Construction

    区间$dp$,四边形优化. #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio&g ...

  7. Python_Tips[7] -> 偏函数

    偏函数 / Partial Function 使用偏函数可以对函数的部分预先知道的参数进行冻结,从而缓存函数参数,而在运行时再释放参数进行使用.所以偏函数适用于需要多次调用同样一个函数且其中一个参数固 ...

  8. Tarjan缩点【p1262】间谍网络

    Description 由于外国间谍的大量渗入,国家安全正处于高度的危机之中.如果A间谍手中掌握着关于B间谍的犯罪证据,则称A可以揭发B.有些间谍收受贿赂,只要给他们一定数量的美元,他们就愿意交出手中 ...

  9. 洛谷——P2421 A-B数对(增强版)

    题目背景 woshiren在洛谷刷题,感觉第一题:求两数的和(A+B Problem)太无聊了,于是增加了一题:A-B Problem,难倒了一群小朋友,哈哈. 题目描述 给出N 个从小到大排好序的整 ...

  10. 洛谷——P2958 [USACO09OCT]木瓜的丛林Papaya Jungle

    P2958 [USACO09OCT]木瓜的丛林Papaya Jungle 题目描述 Bessie has wandered off the farm into the adjoining farmer ...