java网络爬虫-爬取小说

今天突然想写一个网络爬虫爬取一下我自己正在看的小说《圣墟》

小说网址:http://www.biqudu.com/43_43821/

大家也可以用这个去试一试爬取另外的小说。(主要就是写正则表达式,找规律)

我的思路:

1.找到小说章节目录的网址

2.在章节目录的网址中爬取每一章的网址

3.通过每一章的网页爬取每一章节的内容

下面是代码:

package cn.hncu.net.spider;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class SpiderDemo2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			URL mulu=new URL("http://www.biqudu.com/43_43821/");
			BufferedReader br=new BufferedReader(new InputStreamReader(mulu.openStream()));
			BufferedWriter bw=new BufferedWriter(new FileWriter("abcde.txt"));
			
			String mainContextReg="
《圣墟》正文
"; //
第一章 沙漠中的彼岸花
String urlReg=""; Pattern mainContextPattern=Pattern.compile(mainContextReg); Pattern urlPattern=Pattern.compile(urlReg); String str=null; boolean boo=false; //是否是正文 while((str=br.readLine())!=null){ if(!boo){ Matcher mainContextMatcher=mainContextPattern.matcher(str); if(mainContextMatcher.find()){ boo=true; System.out.println(str.substring(str.indexOf("
")+4, str.lastIndexOf("
"))); } }else{ Matcher urlmatcher=urlPattern.matcher(str); if(urlmatcher.find()){ // System.out.println(urlmatcher.group()); //第一章 沙漠中的彼岸花 String str1=urlmatcher.group(); String url="http://www.biqudu.com"+str1.substring(str1.indexOf("")); // System.out.println(str1); // System.out.println(url); zj(url,bw); } } } br.close(); bw.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void zj(String url,BufferedWriter bw){ try { URL mainUrl=new URL(url); BufferedReader br=new BufferedReader(new InputStreamReader(mainUrl.openStream())); String titleReg="

[\\s\\S]*

"; String contextReg="
[\\s\\S]*
"; String newLine="
"; String spac=" "; Pattern titlePattern=Pattern.compile(titleReg); Pattern contextPattern=Pattern.compile(contextReg); Pattern newLinePattern=Pattern.compile(newLine); Pattern spacPattern=Pattern.compile(spac); String str=null; String title=null; String context=null; while((str=br.readLine())!=null){ Matcher m = titlePattern.matcher(str); if(m.find()){ title=m.group(); bw.write(title.substring(4, title.lastIndexOf("<"))+"\r\n"); bw.flush(); System.out.println(title.substring(4, title.lastIndexOf("<"))); //标题 } m=contextPattern.matcher(str); if(m.find()){ context=m.group(); //正文--因为这里的正文是一行,所以需要继续在拆 char cs[]=context.toCharArray(); for(int i=0;i


你可能感兴趣的:(----java,net,网络编程-----)