import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import com.creditcloud.brick.task.CrawlTask;
import com.creditcloud.brick.task.Extractor;
import com.creditcloud.brick.task.Field; @NoArgsConstructor
@AllArgsConstructor
@Data
@Slf4j
public class DataCrawler {
String url;
String space; public HashMap<String, Object> doCrawl(CrawlTask task ) {
HashMap<String, Object> result = new HashMap<String, Object>();
this.url = task.getUrl();
this.space = task.getId();
//
String content=this.doGet(url);
if( StringUtils.isNotEmpty(content)) {
Extractor actor=task.getExtractor();
if( actor != null )
this.parse(actor, content, result);
}
return result;
} public String doGet( String url ) {
String data=null;
//return Jsoup.connect(url).userAgent("Mozilla").get();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet hGet = new HttpGet(url);
log.info(url);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(hGet);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
log.info( response.getStatusLine().toString() );
//
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
data = EntityUtils.toString(entity);
System.out.println(data);
EntityUtils.consume(entity); }
}
catch(Exception e){
log.error(e.getMessage());
}
//response
try
{
if( response != null )
response.close();
}
catch(Exception e) {
log.error(e.getMessage());
}
//httpclient
try {
if( httpclient != null )
httpclient.close();
} catch (Exception e) {
log.error(e.getMessage());
} return data;
} public String removeHtmlLabel( String input ) {
return input.replaceAll("<[^>]+>", "").replaceAll("&nbsp;"," ").trim();
} //
public ArrayList<String> match( Extractor extractor, String input ) {
ArrayList<String> result = new ArrayList<String>();
switch (extractor.getType()) {
case css: //call css
{
Document doc = Jsoup.parse(input);
Elements elems = doc.select(extractor.getPattern());
for( Element elem:elems ) {
result.add( elem.toString() );
}
}
break;
case regex: //call regex
{
Pattern p = Pattern.compile( extractor.getPattern());
Matcher m = p.matcher( input );
String matchValue = null;
while(m.find()) {
matchValue = StringEscapeUtils.unescapeHtml4( m.group());
result.add(matchValue);
}
}
break;
case empty:
result.add(input);
break;
}
return result;
} public void parse( Extractor extractor, String input, HashMap<String, Object> result ) {
//1. match by css or regex
ArrayList<String> strlist = this.match(extractor, input);
if( strlist.isEmpty() ) {
//result.put( extractor.getId(), null);
return;
}
//2. call children extractors
switch(extractor.getData()) {
case array:{
//result.setType(ResultDataType.array);
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
for( String str:strlist ) {
HashMap<String, Object> childResult = new HashMap<String, Object>();
for( Extractor one:extractor.getChildren()) {
this.parse(one, str, childResult);
}
if( childResult.isEmpty() == false )
list.add(childResult);
}
if(list.isEmpty() == false )
result.put( extractor.getId(), list );
}
break;
case field:{
for(Field fd:extractor.getFields()) {
String val=strlist.get( fd.getIndex() );
result.put( fd.getName(), this.removeHtmlLabel(val) );
}
}
break;
case none: {
for( String str:strlist ) {
for( Extractor one:extractor.getChildren()) {
this.parse(one, str, result);
}
}
}
break;
}
}
}

a code snip的更多相关文章

  1. CSS code snip enjoy.

    <!-- information-total得是动态获取吧. --> <div class="information-mod"> <div class ...

  2. C# Code Snip

    1.Tryf + TAB+TAB try { } finally { } 2.Prop+Tab+Tab public int MyProperty { get; set; } 3. #region + ...

  3. WPF整理-跨程序集访问资源

    “Sometimes binary resources are defined in one assembly (typically a class library), but areneeded i ...

  4. WPF整理-使用用户选择主题的颜色和字体

    “Sometimes it's useful to use one of the selected colors or fonts the user has chosen in theWindows ...

  5. WPF整理-XAML访问静态属性

    "XAML provides an easy way to set values of properties—type converters and the extended propert ...

  6. WPF整理-XAML构建后台类对象

    1.XAML 接触WPF的第一眼就是XAML---XAML是用来描绘界面的.其实不然! "Actually, XAML has nothing to do with UI. It's mer ...

  7. Call C# in powershell

    How to call C# code in powershell Powershell Command Add-Type usage of Add-Type we use Add-Type -Typ ...

  8. Windows Phone 8 开发必备资源

    一.MVVM框架推荐 1. MVVM-Light 这个框架是我最常用的MVVM框架之一,它比Prism更轻量级,但对于一般的小应用,功能足够. 官方网站:http://mvvmlight.codepl ...

  9. 字符串的驻留(String Interning)

    http://www.cnblogs.com/artech/archive/2007/03/04/663728.html 关于字符串的驻留的机制,对于那些了解它的人肯定会认为很简单,但是我相信会有很大 ...

随机推荐

  1. ActiveReport资料

    1. ActiveReports for .NET 2 Online | ActiveReports for .NET 3 Online 2.GroupHeader块 ①GroupHeader块为每个 ...

  2. Asmack离线消息时间获取

    DelayInformation info = (DelayInformation)message.getExtension("x","jabber:x:delay&qu ...

  3. Java NIO 缓冲区学习笔记

    Buffer其实就是是一个容器对象,它包含一些要写入或者刚读出的数据.在NIO中加入Buffer对象,体现了新库与原I/O的一个重要区别.在面向流的I/O中,您将数据直接写入或者将数据直接读到Stre ...

  4. vector 之 find 重载

    众所周知,map有find,但vector的find只能调用algorithm中的find通用方法. 参考<How to find an item in a std::vector?> 对 ...

  5. 排序算法之快速排序(java实现)

    package com.javaTest300; public class Test039 { public static void main(String[] args) {// 快速排序 int ...

  6. iOS事件机制(一)

    运用的前提是掌握 掌握的本质是理解 本篇内容将围绕iOS中事件及其传递机制进行学习和分析.在iOS中,事件分为三类: 触控事件(单点.多点触控以及各种手势操作) 传感器事件(重力.加速度传感器等) 远 ...

  7. POJ 3660 Cow Contest (floyd求联通关系)

    Cow Contest 题目链接: http://acm.hust.edu.cn/vjudge/contest/122685#problem/H Description N (1 ≤ N ≤ 100) ...

  8. poj3259

    Wormholes Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 24864   Accepted: 8869 Descri ...

  9. [转]sql server 数据库日期格式化函数

    转至:http://www.cnblogs.com/hantianwei/archive/2009/12/03/1616148.html 0   或   100   (*)     默认值   mon ...

  10. 201. Segment Tree Build

    最后更新 二刷 08-Jan-2017 一刷忘了什么时候做的,只是觉得这几个题挺好的,一步一步手动构建线段树,最终理解了这个数据结构,并且后面有利用的地方. 其实重要的3个东西题目已经提供了: 1) ...