Java实现一个小说采集程序的简单实例
被标题吸引进来的不要骂我。
只是一个简单的实现,随手写了来下载一部喜欢的小说的。示例中的小说只是示例,不是我的菜。
使用了jsoup。挺好用的一个工具。
有需要的话,参考下自己改吧。挺简单的,是吧。
代码如下:
packagecom.zhyea.doggie;
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importorg.jsoup.Jsoup;
importorg.jsoup.nodes.Document;
importorg.jsoup.select.Elements;
publicclassDoggie{
publicstaticvoidmain(String[]args){
try{
FiletxtFile=newFile("D:/无限崩坏.txt");
createTxtDoc(txtFile);
addContent(txtFile);
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*向小说文件中添加内容
*@paramtxtFile
*小说文件
*@throwsIOException
*@throwsInterruptedException
*/
privatestaticvoidaddContent(FiletxtFile)throwsIOException,InterruptedException{
appendTxt(txtFile,getBookInfo("无限崩坏","啪啪啪狂魔"));
Stringurl="http://www.83kxs.com/View/12/12653/{pattern}.html";
for(inti=5850686;i<=5945501;i++){
try{
Stringtmp=url.replace("{pattern}",i+"");
appendTxt(txtFile,getPageContent(tmp));
}catch(Exceptione){
e.printStackTrace();
continue;
}
}
}
/**
*设置书名和作者
*@parambookName
*书名
*@paramauthor
*作者
*@return
*/
privatestaticStringgetBookInfo(StringbookName,Stringauthor){
returnCOMMON.replace("{book}",bookName).replace("{author}",author);
}
/**
*读取页面内容
*@paramurl
*访问路径
*@return
*@throwsIOException
*/
privatestaticStringgetPageContent(Stringurl)throwsIOException{
Stringrtn=null;
Documentdoc=Jsoup.connect(url).get();
Elementscontent=doc.select(".textp");
Elementstitle=doc.select("#title");
System.out.println(title.text());
content.select("font").remove();
content.select("script").remove();
content.select("ins").remove();
content.select("a").remove();
rtn=title.text()+NEWLINE
+content.html().replaceAll("<p>","")
.replaceAll("</p>","")
.replaceAll("\\<!--(.+)--\\>","")
.replaceAll(" ","")
.replaceAll("<br>",NEWLINE)
+NEWLINE;
returnrtn;
}
/**
*创建新的txt文件
*@paramfullName
*文件全名
*@return
*@throwsException
*/
privatestaticbooleancreateTxtDoc(FiletxtFile)throwsException{
try{
returntxtFile.createNewFile();
}catch(Exceptione){
throwe;
}
}
/**
*向txt文件中追加内容
*@paramtxtFile
*要操作的txt文件
*@paramcontent
*要追加的内容
*@throwsIOException
*/
privatestaticvoidappendTxt(FiletxtFile,Stringcontent)throwsIOException{
FileWriterwriter=null;
try{
writer=newFileWriter(txtFile,true);
writer.append(content);
}finally{
if(null!=writer)writer.close();
}
}
/**
*换行符
*/
staticfinalStringNEWLINE=System.getProperty("line.separator");
/**
*书前的通用信息
*/
staticStringCOMMON="------------------------------------------------------------------"+NEWLINE
+"---------------书名:{book}"+NEWLINE
+"---------------作者:{author}"+NEWLINE
+"---------------zhyea.com"+NEWLINE
+"------------------------------------------------------------------"+NEWLINE;
}
以上就是小编为大家带来的Java实现一个小说采集程序的简单实例全部内容了,希望大家多多支持毛票票~