webMagic虽然方便,但是也有它不适用的地方,比如定向的某个单页面爬虫,或者存在大量ajax请求,页面的跳转请求全都混淆在js里。

这时可以用webMagic结合phantomjs来真实模拟页面请求,即不仅仅获取数据,而是将整个页面完整渲染出来。虽然这样会使爬虫速度变慢很多,但是不失为一种快捷方便的解决方法。

PhantomJS是一个基于 WebKit 的服务器端JavaScript API。它全面支持web而不需浏览器支持,其快速,原生支持各种Web标准: DOM 处理, CSS 选择器, JSON, Canvas, 和 SVG。 PhantomJS 可以用于页面自动化 , 网络监测, 网页截屏,以及 无界面测试 等。

淘宝就是这种难以用普通爬虫方法爬取的网站。直接发送GET请求到淘宝基本获取不到什么有效的内容和链接。

还好webMagic虽然默认使用httpClient获取网页,但是它也将它获取网页的方法Downloader开放出来。这样可以在Downloader里使用phantomjs获取页面。

phantomjs使用方法

1.下载安装phantomjs

2.编写js脚本

system = require('system')   //传递一些需要的参数给js文件  

address = system.args[1];//获得命令行第二个参数 ,也就是指定要加载的页面地址,接下来会用到    

var page = require('webpage').create();  

var url = address;  

page.open(url, function (status) {  

    if (status !== 'success') {  

        console.log('Unable to post!');
} else { var encodings = ["euc-jp", "sjis", "utf8", "System"];//这一步是用来测试输出的编码格式,选择合适的编码格式很重要,不然你抓取下来的页面会乱码o(╯□╰)o,给出的几个编码格式是官网上的例子,根据具体需要自己去调整。 for (var i = 3; i < encodings.length; i++) {//我这里只要一种编码就OK啦 phantom.outputEncoding = encodings[i]; console.log(phantom.outputEncoding+page.content);//最后返回webkit加载之后的页面内容
} }
phantom.exit();
});

3.测试

package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter; import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.PlainText; public class GetAjaxHtml {
public static String getAjaxContent(String url) throws Exception {
Runtime rt = Runtime.getRuntime();
Process p = rt
.exec("D:/phantomjs-2.1.1-windows/bin/phantomjs.exe D:/s.js "
+ url);
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sbf = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sbf.append(tmp + "\n");
}
return sbf.toString();
} public static Page download(Request request) {
Page page = new Page();
try {
String url = request.getUrl();
String html = getAjaxContent(url);
page.setRawText(html);
page.setUrl(new PlainText(url));
page.setRequest(request);
return page;
} catch (Exception e) {
System.out.println("download出错了!");
return page;
}
} public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
String result = getAjaxContent("http://www.taobao.com");
System.out.println(result);
// 创建新文件
String path = "D:\\testFile\\taobao.html";
PrintWriter printWriter = null;
printWriter = new PrintWriter(new FileWriter(new File(path)));
printWriter.write(result);
printWriter.close();
long end = System.currentTimeMillis();
System.out.println("===============耗时:" + (end - start)
+ "===============");
}
}

webMagic结合phantomjs淘宝爬虫

package taobao;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.downloader.Downloader;
import us.codecraft.webmagic.processor.PageProcessor;
import util.GetAjaxHtml;
import util.UuidUtil;
import csdnblog.dao.TaobaoDao;
import csdnblog.model.Taobao; public class TaobaoPageProcessor implements PageProcessor { private TaobaoDao taobaoDao = new TaobaoDao(); // 抓取网站的相关配置,包括:编码、抓取间隔、重试次数等
private Site site = Site.me().setRetryTimes(3).setSleepTime(1000); @Override
public Site getSite() {
return site;
} @Override
public void process(Page page) {
page.addTargetRequests(page.getHtml().links()
.regex(".*item\\.taobao\\.com/item\\.htm\\?id=.*")
.all());
page.addTargetRequests(page.getHtml().links()
.regex("https://s\\.taobao\\.com/list.*")
.all()); //如果是详情页
if(page.getUrl().regex("https://item\\.taobao\\.com/item\\.htm\\?id=.*").match()) { Taobao taobao = new Taobao();
taobao.setId(UuidUtil.getId());
taobao.setUrl(page.getUrl().toString());
taobao.setMaintitle(page.getHtml().xpath("//h3[@class='tb-main-title']/text()").get());
taobao.setSubtitle(page.getHtml().xpath("//p[@class='tb-subtitle']/text()").get());
taobao.setPrice(page.getHtml().xpath("//strong[@id='J_StrPrice']/em[@class='tb-rmb-num']/text()").get());
taobao.setTaobaoprice(page.getHtml().xpath("//em[@id='J_PromoPriceNum']/text()").get());
taobao.setRatecounter(page.getHtml().xpath("//strong[@id='J_RateCounter']/text()").get());
taobao.setSellcounter(page.getHtml().xpath("//strong[@id='J_SellCounter']/text()").get());
// 把对象存入数据库
taobaoDao.addTaobao(taobao);
// 把对象输出控制台
System.out.println(taobao.toString());
}
} public static void main(String[] args) {
Spider.create(new TaobaoPageProcessor()).setDownloader(new Downloader() { @Override
public void setThread(int threadNum) {
} @Override
public Page download(Request request, Task task) {
return GetAjaxHtml.download(request);
}
}).addUrl("https://s.taobao.com/list?q=%E5%A4%B9%E5%85%8B&cat=50344007&style=grid&seller_type=taobao").thread(5).run();
}
}

Model

package csdnblog.model;

public class Taobao {

    private String id;
private String maintitle;
private String subtitle; // url
private String url; // 价格
private String price; // 淘宝价
private String taobaoprice; // 累计评价
private String ratecounter; // 交易成功
private String sellcounter; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getMaintitle() {
return maintitle;
} public void setMaintitle(String maintitle) {
this.maintitle = maintitle;
} public String getSubtitle() {
return subtitle;
} public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
} public String getPrice() {
return price;
} public void setPrice(String price) {
this.price = price;
} public String getTaobaoprice() {
return taobaoprice;
} public void setTaobaoprice(String taobaoprice) {
this.taobaoprice = taobaoprice;
} public String getRatecounter() {
return ratecounter;
} public void setRatecounter(String ratecounter) {
this.ratecounter = ratecounter;
} public String getSellcounter() {
return sellcounter;
} public void setSellcounter(String sellcounter) {
this.sellcounter = sellcounter;
} public Taobao(String id, String maintitle, String subtitle, String url,
String price, String taobaoprice, String ratecounter,
String sellcounter) {
super();
this.id = id;
this.maintitle = maintitle;
this.subtitle = subtitle;
this.url = url;
this.price = price;
this.taobaoprice = taobaoprice;
this.ratecounter = ratecounter;
this.sellcounter = sellcounter;
} public Taobao() {
super();
} @Override
public String toString() {
return "Taobao [id=" + id + ", maintitle=" + maintitle + ", subtitle="
+ subtitle + ", url=" + url + ", price=" + price
+ ", taobaoprice=" + taobaoprice + ", ratecounter="
+ ratecounter + ", sellcounter=" + sellcounter + "]";
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} }

JAVA爬虫实践(实践四:webMagic和phantomjs和淘宝爬虫)的更多相关文章

  1. Python爬虫实战八之利用Selenium抓取淘宝匿名旺旺

    更新 其实本文的初衷是为了获取淘宝的非匿名旺旺,在淘宝详情页的最下方有相关评论,含有非匿名旺旺号,快一年了淘宝都没有修复这个. 可就在今天,淘宝把所有的账号设置成了匿名显示,SO,获取非匿名旺旺号已经 ...

  2. Python网页信息采集:使用PhantomJS采集淘宝天猫商品内容

    1,引言 最近一直在看Scrapy 爬虫框架,并尝试使用Scrapy框架写一个可以实现网页信息采集的简单的小程序.尝试过程中遇到了很多小问题,希望大家多多指教. 本文主要介绍如何使用Scrapy结合P ...

  3. 23个Python爬虫开源项目代码,包含微信、淘宝、豆瓣、知乎、微博等

    今天为大家整理了23个Python爬虫项目.整理的原因是,爬虫入门简单快速,也非常适合新入门的小伙伴培养信心,所有链接指向GitHub,微信不能直接打开,老规矩,可以用电脑打开. 关注公众号「Pyth ...

  4. 爬虫实战4:用selenium爬取淘宝美食

    方案1:一次性爬取全部淘宝美食信息 1. spider.py文件如下 __author__ = 'Administrator' from selenium import webdriver from ...

  5. [Python爬虫] 之十四:Selenium +phantomjs抓取媒介360数据

    具体代码如下: # coding=utf-8import osimport refrom selenium import webdriverimport selenium.webdriver.supp ...

  6. Python 爬虫实例(9)—— 搜索 爬取 淘宝

    # coding:utf- import json import redis import time import requests session = requests.session() impo ...

  7. 爬虫实战--使用Selenium模拟浏览器抓取淘宝商品美食信息

    from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exce ...

  8. python爬虫实例,一小时上手爬取淘宝评论(附代码)

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 1 明确目的 通过访问天猫的网站,先搜索对应的商品,然后爬取它的评论数据. ...

  9. 学习用java基于webMagic+selenium+phantomjs实现爬虫Demo爬取淘宝搜索页面

    由于业务需要,老大要我研究一下爬虫. 团队的技术栈以java为主,并且我的主语言是Java,研究时间不到一周.基于以上原因固放弃python,选择java为语言来进行开发.等之后有时间再尝试pytho ...

随机推荐

  1. JS画几何图形之五【过圆外一点作切线】

    样例:http://www.zhaojz.com.cn/demo/draw9.html 依赖:[点].[直线].[圆] //画切线 //point 圆外的一点 //dot 圆心 //r 半径 func ...

  2. openstack操作之一 命令行

    在openstack环境中提供了多种操作虚拟机的方法,有最简单直接的dashborad界面,有不直观但高效的命令行,还有进阶版的postman调用openstack restfulapi和命令行中使用 ...

  3. 由linux命令谈学习操作系统的重要性

    linux命令妙趣横生,喜欢敲命令行的人会深有体会,但是没有系统学习过操作系统的话,很多命令还是难以理解的.讲实在话,大多数linux爱好者常敲的都是这些方面的: 文件系统 磁盘 网络 系统状态 账户 ...

  4. Oracle学习笔记_10_判断是否为日期类型

    FUNCTION isdate (datestr VARCHAR2, format VARCHAR2) RETURN number IS p_date DATE; BEGIN SELECT TO_DA ...

  5. Nginx 限制连接的实践 (DDOS)

    参考:  运维人员的日常 关于限制用户连接,Nginx 提供的模块: ngx_http_limit_req_module , ngx_http_limit_conn_module  , 还有 stre ...

  6. Python类方法、静态方法与实例方法

    静态方法是指类中无需实例参与即可调用的方法(不需要self参数),在调用过程中,无需将类实例化,直接在类之后使用.号运算符调用方法. 通常情况下,静态方法使用@staticmethod装饰器来声明. ...

  7. Python入门-数据类型

    一.变量 1)变量定义 name = 100(name是变量名 = 号是赋值号100是变量的值) 2)变量赋值 直接赋值 a=1 链式赋值  a=b=c=1 序列解包赋值  a,b,c = 1,2,3 ...

  8. mac上使用appium连接真机问题

    1.链接真机时一直报错 app is not install 日志如下: 解决办法:是因为lockdown挂了,在命令行输入sudo chmod -R 777 /var/db/lockdown/ 但是 ...

  9. python检测404页面

    某些网站为了实现友好的用户交互,提供了一种自定义的错误页面,而不是显示一个大大的404 ,比如CSDN上的404提示页面如下: 这样虽然提高了用户体验,但是在编写对应POC进行检测的时候如果只根据返回 ...

  10. unisound_asr 云知声 语音识别 python版接口

    抽空,实现了一份云知声 语音转写的python版本. 使用python通过调用动态库实现. 云知声官网: http://dev.hivoice.cn/sdk_download/schema_sdk.j ...