1. 改变用户代理
  2. 读取Cookies
  3. 调用Java Script
  4. Webdriver截图
  5. 页面等待

1. 改变用户代理

  1. import org.junit.AfterClass;
  2. import org.junit.BeforeClass;
  3. import org.junit.Test;
  4. import org.openqa.selenium.WebDriver;
  5. import org.openqa.selenium.firefox.FirefoxDriver;
  6. import org.openqa.selenium.firefox.FirefoxProfile;
  7. public class ProxyTest {
  8. static WebDriver driver;
  9. @BeforeClass
  10. public static void beforeClass(){
  11. //代理的IP和端口
  12. String proxyIP="192.168.12.0";
  13. int proxyPort=80;
  14. FirefoxProfile profile=new FirefoxProfile();
  15. //使用代理
  16. profile.setPreference("network.proxy.type", 1);
  17. //配置“HTTP代理:(N)”
  18. profile.setPreference("network.proxy.http", proxyIP);
  19. profile.setPreference("network.proxy.http_prot", proxyPort);
  20. //选中 “为所有协议使用相同代理(S)” 选框
  21. profile.setPreference("network.proxy.share_proxy_settings", true);
  22. //配置“不使用代理:(N)”文本框
  23. profile.setPreference("network.proxy.no_proxies_on", "localhost, 127.0.0.1");
  24. //以代理的方式启动火狐
  25. driver=new FirefoxDriver(profile);
  26. }
  27. @Test
  28. public void test() {
  29. driver.get("http://www.baidu.com");
  30. }
  31. @AfterClass
  32. public static void afterClass(){
  33. //driver.quit();
  34. }
  35. }

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

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

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();

下面是一个例子:

  1. import java.util.Set;
  2. import org.junit.After;
  3. import org.junit.Before;
  4. import org.junit.Test;
  5. import org.openqa.selenium.Cookie;
  6. import org.openqa.selenium.WebDriver;
  7. import org.openqa.selenium.firefox.FirefoxDriver;
  8. public class CookieTest {
  9. WebDriver driver;
  10. @Before
  11. public void setUp() throws Exception {
  12. driver=new FirefoxDriver();
  13. }
  14. @After
  15. public void tearDown() throws Exception {
  16. driver.quit();
  17. }
  18. @Test
  19. public void test() {
  20. printCookie();
  21. //添加一个cookie
  22. Cookie cookie=new Cookie("s","selenium");
  23. driver.manage().addCookie(cookie);
  24. printCookie();
  25. //删除一个cookie
  26. driver.manage().deleteCookie(cookie);   //driver.manage().deleteCookieNamed("s");也可以
  27. printCookie();
  28. }
  29. public void printCookie(){
  30. //获取并打印所有的cookie
  31. Set<Cookie> allCookies=driver.manage().getCookies();
  32. System.out.println("----------Begin---------------");
  33. for(Cookie c:allCookies){
  34. System.out.println(String.format("%s->%s",c.getName(),c.getValue()));
  35. }
  36. System.out.println("----------End---------------");
  37. }
  38. }

运行结果显示为:

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

3. 调用Java Script

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

  1. import org.junit.Test;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.firefox.FirefoxDriver;
  4. import org.openqa.selenium.JavascriptExecutor;
  5. public class JSTest {
  6. @Test
  7. public void test() {
  8. WebDriver driver=new FirefoxDriver();
  9. driver.get("http://www.baidu.com");
  10. JavascriptExecutor js=(JavascriptExecutor)driver;
  11. js.executeScript("document.getElementById(\"kw\").value=\"selenium\"");
  12. //利用js代码获取百度搜索框内文字
  13. String keyword = (String) (js.executeScript("var input = document.getElementById(\"kw\").value;return input"));
  14. System.out.println(keyword);
  15. driver.quit();
  16. }
  17. }

运行结果:

selenium

4. Webdriver截图

  1. import java.io.File;
  2. import java.io.IOException;
  3. import org.apache.commons.io.FileUtils;
  4. import org.junit.Test;
  5. import org.openqa.selenium.OutputType;
  6. import org.openqa.selenium.TakesScreenshot;
  7. import org.openqa.selenium.WebDriver;
  8. import org.openqa.selenium.firefox.FirefoxDriver;
  9. public class ScreenShotTest {
  10. @Test
  11. public void test() {
  12. WebDriver driver=new FirefoxDriver();
  13. driver.get("http://www.baidu.com");
  14. screenShot("selenium.jpg", (TakesScreenshot)driver);
  15. driver.quit();
  16. }
  17. public static void screenShot(String name,TakesScreenshot driver){
  18. String savaPath=System.getProperty("user.dir");
  19. File sourceFile=driver.getScreenshotAs(OutputType.FILE);
  20. try{
  21. System.out.println("Begin saving screenshot to path:"+savaPath);
  22. FileUtils.copyFile(sourceFile, new File(savaPath+"\\"+name));
  23. } catch(IOException e){
  24. System.out.println("Save screenshot failed!");
  25. e.printStackTrace();
  26. } finally{
  27. System.out.println("Finish screenshot!");
  28. }
  29. }
  30. }

运行结果:

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

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

5. 页面等待

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

显性等待:

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

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

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

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

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

  1. import org.junit.Test;
  2. import org.openqa.selenium.By;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.WebElement;
  5. import org.openqa.selenium.firefox.FirefoxDriver;
  6. import org.openqa.selenium.support.ui.ExpectedCondition;
  7. import org.openqa.selenium.support.ui.ExpectedConditions;
  8. import org.openqa.selenium.support.ui.WebDriverWait;
  9. public class ExplicitWaitTest {
  10. @Test
  11. public void test() {
  12. WebDriver driver=new FirefoxDriver();
  13. driver.get("http://www.baidu.com");
  14. driver.findElement(By.id("kw")).sendKeys("selenium");
  15. driver.findElement(By.id("su")).click();
  16. //方法一
  17. //new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.linkText("Selenium_百度百科")));
  18. //driver.findElement(By.linkText("Selenium_百度百科")).click();
  19. //方法二
  20. WebElement e = (new WebDriverWait( driver, 10)).until(
  21. new ExpectedCondition< WebElement>(){
  22. @Override
  23. public WebElement apply( WebDriver d) {
  24. return d.findElement(By.linkText("Selenium_百度百科"));
  25. }
  26. }
  27. );
  28. e.click();
  29. driver.quit();
  30. }
  31. }

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

隐性等待:

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

  1. driver.manage().timeouts().implicitlyWait(second, TimeUnit.SECONDS);

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

  1. import java.util.concurrent.TimeUnit;
  2. import org.junit.Test;
  3. import org.openqa.selenium.By;
  4. import org.openqa.selenium.WebDriver;
  5. import org.openqa.selenium.firefox.FirefoxDriver;
  6. public class ImplicitWaitTest {
  7. @Test
  8. public void test() {
  9. WebDriver driver=new FirefoxDriver();
  10. driver.get("http://www.baidu.com");
  11. driver.findElement(By.id("kw")).sendKeys("selenium");
  12. driver.findElement(By.id("su")).click();
  13. driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  14. driver.findElement(By.linkText("Selenium_百度百科")).click();
  15. driver.quit();
  16. }
  17. }

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

selenium 代理 Cookies 截图 等待 调用JS的更多相关文章

  1. python之selenium调用js(execute_script)

    转载: http://www.cnblogs.com/fnng/p/3230768.html 本节重点: 调用js方法 execute_script(script, *args) 在当前窗口/框架 同 ...

  2. python selenium --调用js

    转自:http://www.cnblogs.com/fnng/p/3230768.html 本节重点: 调用js方法 execute_script(script, *args) 在当前窗口/框架 同步 ...

  3. Selenium with Python 005 - 调用js操作页面元素

    WebDriver提供了execute_script()方法来执行JavaScript方法,格式如 driver.execute_script(script,*args) 执行js一般有两种场景,一是 ...

  4. Java&Selenium自动化测试调用JS实现单击

    Java&Selenium自动化测试调用JS实现单击 /* * the method of invoking js to do something * * @author davieyang ...

  5. Java&Selenium调用JS实现高亮被操作页面元素高亮

    Java&Selenium调用JS实现高亮被操作页面元素高亮 /* * the method of invoking js to do something * * @author daviey ...

  6. Selenium中三种等待的使用方式---规避网络延迟、代码不稳定问题

    在UI自动化测试中,必然会遇到环境不稳定,网络慢的情况,这时如果你不做任何处理的话,代码会由于没有找到元素,而报错.这时我们就要用到wait(等待),而在Selenium中,我们可以用到一共三种等待, ...

  7. iOS:在OC中调用JS脚本

    示例一:在webView中调用js脚本进行搜索 1.首先导入JavaScriptCore.framework这个框架 2.创建webView.设置代理.请求手机端百度 #import "Vi ...

  8. JS调用OC方法并传值,OC调用JS方法并传值////////////////////////zz

     iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)     最近项目里面有有个商品活动界面,要与web端传值,将用户在网页点击的商品id 传给客户端,也就是js交互,其实再说明白一点 ...

  9. Magento中调用JS文件的几种方法

    一.全局调用方法: 通过该方法每个页面都会引用这个JS文件,除非是类似jQuery这样的系统文件,不然不推荐这种方法. 文件路径:/app/design/frontend/default/Your_T ...

随机推荐

  1. TrustZone——开源库—Linaro—OP-TEE

    想研究安全系统源代码的有福气了.曾经OVOS的代码缺少TA相关的实现. 这次的版本号,基本框架都有了.先看看架构图吧. 几家大公司做的,可能是ST牵头.页面有ST的LOGO. 代码质量较高. 未来也会 ...

  2. 数据透视表sql:用SQL行列转换实现数据透视的一些思考

    用SQL行列转换实现数据透视的一些思考 摘要:根据对报表开发过程中碰到的需要用SQL行列转换进行解决的一类查询统计问题的分析,逐步探索求解得到一种较通用的解决思路,并用函数进行实现.该解决思路及函数实 ...

  3. 漫游Kafka入门篇之简单介绍(1)

    介绍 Kafka是一个分布式的.可分区的.可复制的消息系统.它提供了普通消息系统的功能,但具有自己独特的设计.这个独特的设计是什么样的呢?   首先让我们看几个基本的消息系统术语: Kafka将消息以 ...

  4. Linux JAVA 配置

    wget http://download.oracle.com/otn-pub/java/jdk/7u25-b15/jdk-7u25-linux-x64.tar.gz tar zxvf jdk-7u2 ...

  5. SQL语句,标准表达式中数据类型不匹配

    id索引进行数据查询时提示错误! 标准表达式中数据类型不匹配. 两边的单引号去掉就好了,否则是在使用文本型. 改为:去掉两个单引号 ok,成功!

  6. An Edge-Guided Image Interpolation Algorithm via Directional Filtering and Data Fusion【翻译】

    基于定向滤波和数据融合的边缘引导图像插值算法 http://ieeexplore.ieee.org/document/1658087/ 摘要: 保留边缘结构对于从低分辨率对应物重建高分辨率图像的图像插 ...

  7. JQuery------鼠标双击时,不选中div里面的文字

    如图:(去掉选中文字的蓝色背景色) 代码: //方法一:<div class="test" onselectstart="return false" &g ...

  8. 论坛模块__发帖时使用FCKeditor

    论坛模块__发帖时使用FCKeditor 测试 <html> <head> <meta http-equiv="content-type" conte ...

  9. 内存泄露,GC相关

    内存泄露就是对象不在GC的掌控之内 下面对象会发生内存泄露现象: 1.没有引用的对象 2.虚,软,弱 引用对象 GC引用的对象指的是 1.JavaStack中引用的对象 2.方法区中静态引用指向的对象 ...

  10. codevs 5965 [SDOI2017]新生舞会

    分数规划的裸题. 不会分数规划的OIer.百度:胡伯涛<最小割模型在信息学竞赛中的应用> /* TLE1: last:add(i,j+n,1e9,(real)((real)a[i][j]- ...