前言:
WebMagic定义了输出到控制台,和输出到文件的函数。
但是输出的文件名、格式、拆分、路径都是固定的,现在自己参考源码重新实现这个功能,可按照自己想要的输出。
根据该思路亦可将数据保存到数据库,而不仅仅是文件!
原生的保存到文件:
调用:上篇写的InfoByWebMagic类的main函数中调用
输出结果:保存为多个.json文件
自己实现保存到文件:
看WebMagic原生保存到文件的类-----JsonFilePipeline
JsonFilePipeline实现Pipeline类,继承FilePersistentBase类
自己写MyJsonFilePipeline类实现Pipeline,继承MyFilePersistentBase
public class MyJsonFilePipeline extends MyFilePersistentBase implements Pipeline{
private Logger logger;
/**
* 空参构造--使用默认路径
*/
public MyPipeline2(){
logger = LoggerFactory.getLogger(getClass());
setPath("/data/webmagic");
}
/**
* 参数构造--指定路径
* @param path
*/
public MyPipeline2(String path) {
logger = LoggerFactory.getLogger(getClass());
setPath(path);
}
@Override
public void process(ResultItems resultItems, Task task) {
try{
String filepath=new StringBuilder().append(this.path).
append(PATH_SEPERATOR).
append(filenameByDate()).append(".txt").toString();
//true---不将原先文件内容覆盖
PrintWriter printWriter = new PrintWriter(new FileWriter(
getFile(filepath),true));
printWriter.write(JSON.toJSONString(resultItems.getAll()));
printWriter.close();
} catch (IOException e) {
logger.warn("write file error", e);
//System.out.println("文件写入出异常!!!!");
}
}
}
写MyFilePersistentBase类
/**
* 基类
* @author zhl
*
*/
public class MyFilePersistentBase {
protected String path;
public static String PATH_SEPERATOR = "/";
static {//根据系统获取分隔符
String property = System.getProperties().getProperty("file.separator");
if (property != null)
PATH_SEPERATOR = property;
}
/**
* @param path
*/
public void setPath(String path) {
if (!path.endsWith(PATH_SEPERATOR))
path = (new StringBuilder()).append(path).append(PATH_SEPERATOR)
.toString();
this.path = path;
}
/**
* 创建文件
* @param fullName
* @return
*/
public File getFile(String fullName) {
checkAndMakeParentDirecotry(fullName);
return new File(fullName);
}
/**
* 创建路径
* 检查改文件所在路径是否存在
* @param fullName
*/
public void checkAndMakeParentDirecotry(String fullName) {
int index = fullName.lastIndexOf(PATH_SEPERATOR);
if (index > 0) {
String path = fullName.substring(0, index);
File file = new File(path);
if (!file.exists())
file.mkdirs();
}
}
public String getPath() {
return path;
}
private String filename="";
private DateFormat bf=null;
private Date date=null;
/**
* 日期格式化,作为文件名
* @return
*/
public String filenameByDate() {
bf = new SimpleDateFormat("yyyy-MM-dd");
date=new Date();
filename=bf.format(date).replaceAll("-", "");
return filename;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
String test=new MyFilePersistentBase().filenameByDate();
System.out.println(test);
}
}
最终调用:上篇写的InfoByWebMagic类的main函数中调用
public static void main(String[] args) {
//爬取的路径URL---1个线程去执行
//Spider.create(new InfoByWebMagic()).addUrl("http://www.dytt8.net").thread(1).run();
Spider.create(new InfoByWebMagic()).addUrl("http://www.dytt8.net").addPipeline(new MyFilePersistentBase ("E:\\webmagic3\\")).thread(1).run();
}
输出结果