2019独角兽企业重金招聘Python工程师标准>>>

Selenium2.41.0—获取动态资源 (转) 博客分类: java

一概述

    获取动态资源,可以使用HtmlUnit,但是其对JS的支持还是不够完善。相对与HtmlUnit还有一种驱动浏览器的下载还原工具Selenium。可以打开浏览器,获取网页,下载解析,支持dom,js,解析效果更好,但是打开浏览器速度方面有一定损失。个人实验,禁用CSS,图片下载,速度还尚可。

Selenium也是自动化测试工具,支持驱动不同的浏览器,Firefox,IE,Chrome等,也包含HtmlUnit提供的驱动实现。

本文描述Selenium驱动Firefox,请求响应,设置cookies,驱动JS等方法,用他登录某主流weibo还是不错的。

二 版本

Xml代码  
  1. <dependency>
  2. <groupId>org.seleniumhq.selenium</groupId>
  3. <artifactId>selenium-java</artifactId>
  4. <version>2.41.0</version>
  5. </dependency>
<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>2.41.0</version>
</dependency>

三 典型应用

1)打开Google,搜索baidu

可以看到Firefox从打开,填写表单,到提交打开新页面过程。

Java代码  
  1. /**
  2. * 打开google搜索百度
  3. *
  4. * @param queryStr
  5. */
  6. public static void demo() {
  7. String url = "http://www.google.com.hk";
  8. WebDriver webDriver = new FirefoxDriver();
  9. // 打开google
  10. webDriver.get(url);
  11. // 使用Selenium的dom模型获取form
  12. WebElement webElement = webDriver.findElement(By.name("q"));
  13. webElement.sendKeys("baidu");
  14. webElement.submit();
  15. // 通过判断 title 内容等待搜索页面加载完毕,Timeout 设置10秒
  16. (new WebDriverWait(webDriver, 100)).until(new ExpectedCondition<Boolean>() {
  17. public Boolean apply(WebDriver d) {
  18. return d.getTitle().toLowerCase().indexOf("baidu") != -1;
  19. }
  20. });
  21. String responseBody = webDriver.getPageSource();
  22. System.out.println("Response : " + responseBody);
  23. // 关闭浏览器
  24. webDriver.close();
  25. }
/*** 打开google搜索百度* * @param queryStr*/
public static void demo() {String url = "http://www.google.com.hk";WebDriver webDriver = new FirefoxDriver();// 打开googlewebDriver.get(url);// 使用Selenium的dom模型获取formWebElement webElement = webDriver.findElement(By.name("q"));webElement.sendKeys("baidu");webElement.submit();// 通过判断 title 内容等待搜索页面加载完毕,Timeout 设置10秒(new WebDriverWait(webDriver, 100)).until(new ExpectedCondition<Boolean>() {public Boolean apply(WebDriver d) {return d.getTitle().toLowerCase().indexOf("baidu") != -1;}});String responseBody = webDriver.getPageSource();System.out.println("Response : " + responseBody);// 关闭浏览器webDriver.close();
}

2)获取动态网页

与下面的请求响应一样,打开页面等待加载完毕即可,JS填充页面,AJAX都OK。

四 样例

1)请求响应

Java代码  
  1. public static void main(String[] args) throws Exception {
  2. String url = "http://www.google.com";
  3. WebDriver webDriver = new FirefoxDriver();
  4. // 打开google
  5. webDriver.get(url);
  6. String responseBody = webDriver.getPageSource();
  7. System.out.println("Response : " + responseBody);
  8. webDriver.quit();
  9. }
public static void main(String[] args) throws Exception {String url = "http://www.google.com";WebDriver webDriver = new FirefoxDriver();// 打开googlewebDriver.get(url);String responseBody = webDriver.getPageSource();  System.out.println("Response : " + responseBody);  webDriver.quit();
}

(2)配置不加载资源

Java代码  
  1. /**
  2. * 获得不加载 css,图片,flash的浏览器
  3. * @return
  4. */
  5. public WebDriver getNoResouceWebDriver(){
  6. FirefoxProfile firefoxProfile = new FirefoxProfile();
  7. // 去掉css
  8. firefoxProfile.setPreference("permissions.default.stylesheet", 2);
  9. // 去掉图片
  10. firefoxProfile.setPreference("permissions.default.image", 2);
  11. // 去掉flash
  12. firefoxProfile.setPreference("dom.ipc.plugins.enabled.libflashplayer.so", false);
  13. return new FirefoxDriver(firefoxProfile);
  14. }
/*** 获得不加载 css,图片,flash的浏览器* @return*/
public WebDriver getNoResouceWebDriver(){FirefoxProfile firefoxProfile = new FirefoxProfile();// 去掉cssfirefoxProfile.setPreference("permissions.default.stylesheet", 2);// 去掉图片firefoxProfile.setPreference("permissions.default.image", 2);// 去掉flashfirefoxProfile.setPreference("dom.ipc.plugins.enabled.libflashplayer.so", false);return new FirefoxDriver(firefoxProfile);
}

(3)配置Firefox路径

启动报找不到Firefox的时候可以使用:System.setProperty("webdriver.firefox.bin", firefoxPath)

(4)Cookies

1)设置Cookies

Java代码  
  1. public void setCookies(WebDriver,webDriver,Map<String, String> cookies) {
  2. if (cookies != null && cookies.size() > 0) {
  3. for (Entry<String, String> c : cookies.entrySet()) {
  4. Cookie cookie = new Cookie(c.getKey(), c.getValue());
  5. webDriver.manage().addCookie(cookie);
  6. System.out.println("Set Cookies : " + c.getKey() + " | " + c.getValue());
  7. }
  8. }
  9. }
public void setCookies(WebDriver,webDriver,Map<String, String> cookies) {if (cookies != null && cookies.size() > 0) {for (Entry<String, String> c : cookies.entrySet()) {Cookie cookie = new Cookie(c.getKey(), c.getValue());webDriver.manage().addCookie(cookie);System.out.println("Set Cookies : " + c.getKey() + " | " + c.getValue());}}
}

2)获取响应Cookies

Java代码  
  1. public Map<String,String> getCookies(WebDriver webDriver){
  2. Set<Cookie> cookies = webDriver.manage().getCookies();
  3. Map<String, String> responseCookies = new HashMap<String,String>();
  4. for (Cookie c : cookies) {
  5. responseCookies.put(c.getName(), c.getValue());
  6. }
  7. return responseCookies;
  8. }
public Map<String,String> getCookies(WebDriver webDriver){Set<Cookie> cookies = webDriver.manage().getCookies();Map<String, String> responseCookies = new HashMap<String,String>();for (Cookie c : cookies) {responseCookies.put(c.getName(), c.getValue());}return responseCookies;
}

3)清理Cookies

Java代码  
  1. /**
  2. * 清除所有cookie
  3. */
  4. public void clearCookies(WebDriver webDriver) {
  5. webDriver.manage().deleteAllCookies();
  6. }
/*** 清除所有cookie*/
public void clearCookies(WebDriver webDriver) {webDriver.manage().deleteAllCookies();
}

(5)驱动JS

Selenium 的Dom对不可见的Element(html有但是CSS属性为不显示等)找不到,这时候使用JS操作和提交是个不错的选择:

Java代码  
  1. public void doWeb(WebDriver webDriver) {
  2. StringBuilder js = new StringBuilder();
  3. js.append("document.getElementsByName('username')[1].value='").append(WeiboAccount.USERNAME)
  4. .append("';");
  5. js.append("document.getElementsByName('password')[1].value='").append(WeiboAccount.PASSWORD)
  6. .append("';");
  7. js.append("document.getElementsByClassName('W_btn_g')[1].click();");
  8. ((JavascriptExecutor) webDriver).executeScript(js.toString());
  9. (new WebDriverWait(webDriver, 100)).until(new ExpectedCondition<Boolean>() {
  10. public Boolean apply(WebDriver d) {
  11. return d.getTitle().indexOf("我的首页") != -1;
  12. }
  13. });
  14. }

转载至: http://shihlei.iteye.com/blog/2067716

转载于:https://my.oschina.net/xiaominmin/blog/1597993

Selenium2.41.0—获取动态资源 (转)相关推荐

  1. 货拉拉 Android 动态资源管理系统原理与实践(上)

    点击上方蓝字关注我,知识会给你力量 ❝ jary,货拉拉高级客户端工程师,目前负责货拉拉App Android端稳定性提升,包体积优化相关工作. ❞ 前言 随着公司业务的扩展,货拉拉用户端apk包的体 ...

  2. android动态获取地理位置权限,Android6.0获取GPS定位和获取位置权限和位置信息的方法...

    1.添加权限--6.0之后要动态获取,下面会说 2.直接上代码,不多说,代码中注释很详细. private static final int BAIDU_READ_PHONE_STATE = 100; ...

  3. Silverlight 2.5D RPG游戏技巧与特效处理:(十六)动态资源

    即开即玩是网页游戏相比传统客户端游戏的最大优势.如果说在每台电脑安装上G的客户端是一种资源浪费及时间污染:那么Silverlight作为RIA界的新宠儿,在继承祖辈优秀血统的前提下拥有更加卓越的性能及 ...

  4. 动态资源Servlet接口

    1.Servlet接口的作用 Servlet是运行在Web服务器上的应用程序.Servlet本身是一个Java接口,它定义了浏览器访问服务器程序的规则,我们写服务器程序只需要按照需求复写Servlet ...

  5. 借助 OpenGL* ES 2.0 实现动态分辨率渲染

    作者:omar-a-rodrigue 下载 借助 OpenGL* ES 2.0 实现动态分辨率渲染[PDF 677KB] 代码样本: dynamic-resolution.zip[ZIP 4MB] 像 ...

  6. java Http消息传递之POST和GET两种方法--通过实用工具类来获取服务器资源

    实现该方法需要导入一些jar包 可以去一下地址下载: http://pan.baidu.com/s/1hqrJF7m /** * 实用工具类来获取服务器资源 * * get方法传送数据 * * 1.通 ...

  7. 货拉拉 Android 动态资源管理系统原理与实践(下)

    点击上方蓝字关注我,知识会给你力量 so资源动态化方案 so资源打包问题 在打包so资源的过程中,我们遇到了如下问题. 如何移除apk中的so文件,并将他们收集起来? 如何将多个so文件压缩打包,并生 ...

  8. nodejs01——安装及使用、服务端及客户端、commonjs规范、fs模块的使用(文件操作及目录操作)、stream、buffer、WebServer、端口、动态资源及静态资源、头信息、请求方式

    nodejs的安装及使用 服务端及客户端 commonjs规范 fs模块的使用(文件操作及目录操作) stream buffer // Node.js介绍 Node.js 诞生于2009年,Node. ...

  9. ae稳定不能获取动态服务器,ae 获取动态链接服务器超时

    ae 获取动态链接服务器超时 内容精选 换一换 IPv6的使用,可以有效弥补IPv4网络地址资源有限的问题.如果当前云服务器使用IPv4,那么启用IPv6后,云服务器可在双栈模式下运行,即云服务器可以 ...

  10. 静态资源(StaticResource)和动态资源(DynamicResource)

    静态资源(StaticResource)和动态资源(DynamicResource) 资源可以作为静态资源或动态资源进行引用.这是通过使用 StaticResource 标记扩展或 DynamicRe ...

最新文章

  1. 2.javascript之缓存 localStorage 和sessionStorage之间的区别
  2. 服务器mac地址查询修改,服务器mac地址查询修改
  3. python简单编程语言_功能强大而又简单易学的编程语言Python
  4. python 基础 9.0 安装MySQL-python-1.2.5客户端
  5. WPF中的动画——(二)From/To/By 动画(二)
  6. hadoop环境搭建之伪分布集群环境搭建(单节点)
  7. MVC视图中处理Json
  8. 深度学习模型压缩方法
  9. 设计模式学习(三):确保对象的唯一性—单例模式
  10. Deep Learning资源搜集
  11. 介绍一下小规模纳税人如何开具增值税专用发票的流程
  12. MyBatis拦截器执行顺序
  13. 公众号与服务器验证失败,微信公众号服务器配置token验证失败原因
  14. 进程管理——PV操作
  15. 如何利用炒股中的L2行情数据功能对比,以及用途数据分析。(附代码)
  16. 易中天品汉代风云人物02: 冤死的晁错(下)
  17. 全球顶尖科创和商业巨头齐聚,巨杉数据库亮相2021CNBC全球科技大会
  18. 使用css实现扫描效果
  19. 马丁福勒微服务论文网址
  20. 毕业这五年走来,这些私藏Redis的最全知识点我贡献出来了

热门文章

  1. 不洗袜子的高文博_那个孩子在夏天中旬用高袜子大笑?
  2. pandas中DataFrame的修改元素值、缺失值处理、合并操作的方法
  3. php读取xml的值,PHP读取XML值的代码(推荐)
  4. 【C++】STL-函数对象(仿函数)
  5. stata软件不出图_Stata软件的图形绘制—1
  6. Event Loop - JavaScript和node运行机制
  7. 003_ElasticSearch详解与优化设计
  8. [原创]差分放大器阻抗匹配计算+阻抗计算小工具
  9. Scrapy入门程序点评
  10. 输入一个年份,并判断是否为闰年