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. dfs.datanode.max.xcievers参数导致hbase集群报错

    2013/08/09 转发自http://bkeep.blog.163.com/blog/static/123414290201272644422987/ [案例]dfs.datanode.max.x ...

  2. MAC机常用快捷键整理表格

    MAC机常用快捷键整理表格 范围 快捷键 说明 图形   (Command 键)在某些 Apple 键盘上,此键也可能为标志()     Control (Control 键)     Alt Opt ...

  3. Spark SQL概念学习系列之Spark SQL 优化策略(五)

    查询优化是传统数据库中最为重要的一环,这项技术在传统数据库中已经很成熟.除了查询优化, Spark SQL 在存储上也进行了优化,从以下几点查看 Spark SQL 的一些优化策略. (1)内存列式存 ...

  4. work_6

    这次的作业是阅读C++11的新特性并提出问题,作为一个大部分代码都是用C++的基本语法并没有特别关注C++一代又一代新特性的学生来说,首先我阅读了一些关于新特性的文章.为了更快的理解,我首先选择了阅读 ...

  5. Hibernate3注解

    1.@Entity(name="EntityName") 必须,name为可选,对应数据库中一的个表 2.@Table(name="",catalog=&quo ...

  6. codeforces 630 I(规律&&组合)

    I - Parking Lot Time Limit:500MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Subm ...

  7. Linux 的进程组、会话、守护进程

    一.进程组ID 每个进程都属于一个进程组.每个进程组有一个领头进程.进程组是一个或多个进程的集合,通常它们与一组作业相关联,可以接受来自同一终端的各种信号.每个进程组都有唯一的进程组ID(整数,也可以 ...

  8. OpenStack API 与 CloudStack API 模块比较

    OpenStack API Block Storage Service API Compute API Compute API extensions Identity Service API and ...

  9. SessionFactory、HibernateTemplate、HibernateDaoSupport之间的关系说明

    在接触HibernateTemplate之前,我们知道,在对数据库进行CRUD操作之前,需要开启session.transaction等等.在hibernate学习过程中,我们知道了,得到sessio ...

  10. C#中反射的使用(How to use reflect in CSharp)(3)Emit的使用

    Emit意在动态构建一个可以执行(当然也就可以反射)或者只可以反射的动态库. 个人认为在不得不使用反射的情况下,使用Emit会使得效率提升空间很大.亦或者动态插件模式的软件设计中会用到. 依然2%的废 ...