WebDriver+PhantomJs爬虫运用(Java)
需要的添加的jar包及工具:我这里使用maven来构建项目,添加依赖如下:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.2.0</version>
</dependency>
PhantomJs工具到官网去下载:http://phantomjs.org/download.html
尽量都使用最新版本,不然会出现版本兼容的情况。
这里有一个已经写好的获取PhantomJSDriver的工具类
public static WebDriver getPhantomJs() {
String osname = System.getProperties().getProperty("os.name");
if (osname.equals("Linux")) {//判断系统的环境win or Linux
System.setProperty("phantomjs.binary.path", "/usr/bin/phantomjs");
} else {
System.setProperty("phantomjs.binary.path", "./phantomjs/win/phantomjs.exe");//设置PhantomJs访问路径
}
DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
//设置参数
desiredCapabilities.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
desiredCapabilities.setCapability("phantomjs.page.customHeaders.User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
if (Constant.isProxy) {//是否使用代理
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setProxyType(org.openqa.selenium.Proxy.ProxyType.MANUAL);
proxy.setAutodetect(false);
String proxyStr = "";
do {
proxyStr = ProxyUtil.getProxy();//自定义函数,返回代理ip及端口
} while (proxyStr.length() == 0);
proxy.setHttpProxy(proxyStr);
desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
}
return new PhantomJSDriver(desiredCapabilities);
}
获取方式
try{
WebDriver webDriver = PhantomJsUtil.getPhantomJs();
webDriver.get(url);
SleepUtil.sleep(Constant.SEC_5);
PhantomJsUtil.screenshot(webDriver);
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(inputId)));//开始打开网页,等待输入元素出现
Document document = Jsoup.parse(webDriver.getPageSource());
//TODO 剩下页面的获取就按照Jsoup获取方式来做
}finally{
if (webDriver != null) {
webDriver.quit();
}
}
python版使用webdriver+PhantomJs爬虫使用,参考http://www.cnblogs.com/kuqs/p/6395284.html
最新文章
- [.NET Core].NET Core R2安装教程及Hello示例
- JS里设定延时:js中SetInterval与setTimeout用法
- 服务发现之 Etcd VS Consul
- linux ll 命令各列的含义
- 第五课,T语言转义字符()(版本5.0)
- ulua学习笔记(二):官方资料及问题解决方案
- velocity-字母序号 list
- js 之 复制一段代码
- Windows Azure 自动伸缩已内置
- POJ 3422 Kaka&;#39;s Matrix Travels(费用流)
- stm单片机之STM32F4-Discovery资料汇总 (转载自http://blog.163.com/thinki_cao/blog/static/83944875201362493134992/)
- 联想笔记本电脑 Z500除尘过程
- java to kotlin (2) - lambda编程
- 你必须知道的.net读书笔记之第二回深入浅出关键字---对抽象编程:接口和抽象类
- LeetCode 50 - Pow(x, n) - [快速幂]
- adaboost-笔记(1)
- NodeJs——router报错原因
- ngx_pagespeed-nginx前端优化模块介绍
- JSP生成静态Html页面
- hive之案例分析(grouping sets,lateral view explode, concat_ws)
热门文章
- 使用SpringWebFlow
- 2018-12-10 发布 vue全家桶实现的商城web-app,真实数据接口开发
- 根据输入的整数n使得输出精确到小数n位
- centos7 安装mongodb4.0笔记
- python__007内置函数
- 图片下载&;&;非同源图片下载&;&;同源下载&;&;网页点击下载图片
- backbone.js 教程(1) View &; Model &; Collection
- xc语言l博客作业03
- spring boot-13.数据访问
- 小记---------kafka理论及命令行操作