这两天一直在做Java数据的抓取问题。我编写了一个程序用于实现上述功能。但在运行时出现了栈溢出问题。查了一些资料,解决未果。最终想出了如下的思路。(我会附上我的Java源码)。
首先,编写了一个工具类,用于获取网站的html语言,并在此类中添加一个获取字符串str中符合正则表达式regexp的部分字符串的方法,代码如下:
package com.hjb;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CollarDataUtil {
//通过传递参数获取特定网站的HTML语言
public static String getURLHtml(String surl,String encoding) {
String htmlContent = "";
try {
InputStream inputStream;
URL url = new URL(surl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
byte bytes[] = new byte[1024 * 2000];
int index = 0;
int count = inputStream.read(bytes, index, 1024 * 2000);
while (count != -1) {
index += count;
count = inputStream.read(bytes, index, 1);
}
htmlContent = new String(bytes, encoding);
connection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
return htmlContent.trim();
}
//获取字符串str中符合正则表达式regexp的部分字符串
public static List<String> getList(String str,String regexp) {
List<String> list = new ArrayList<String>();
//此处在compile加上参数Pattern.DOTALL + Pattern.MULTILINE可以解决读取字符串过长
//但会出现一些意想不到的问题,不建议使用
Pattern pattern = Pattern.compile(regexp,Pattern.MULTILINE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
if (!list.contains(matcher.group()))
list.add(matcher.group());
}
return list;
}
}
接下来我们编写实现类,但如果直接从获取的html语言中使用正则表达式获取所需资源会出现栈溢出现象,所以先要将所获取的html语言进行字符串的处理,以此减少处理的字符串,代码如下(可运行):
package com.hjb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProcuratorateOfJiangsuData {
/**
* 获取江苏省检察院网站通知的信息
*/
public static void main(String[] args) {
Map<String, String> proOfSZData=new HashMap<String, String>();
List<String> list = new ArrayList<String>();
String url="http://218.94.117.253/jsjc/";
String regexp="<a.*(?=_blank)(.|\n)*?</a>";
String str=CollarDataUtil.getURLHtml(url,"utf-8");
//处理字符串,缩减str的长度
str=str.substring(str.indexOf("<div class=\"sjdt\">"),str.indexOf("<div class=\"fzxw\">"));
//System.out.println(str);
//System.out.println("-----------------------------------------------------------");
list=CollarDataUtil.getList(str, regexp);
for (String str1 : list) {
// System.out.println(str1);
// System.out.println("----------------------------------------------------------------");
proOfSZData.put(getStrArray(str1)[0], getStrArray(str1)[1]);
System.out.println(getStrArray(str1)[0]+" "+getStrArray(str1)[1]);
}
}
//拆分字符串,获得想要数据
private static String[] getStrArray(String str){
str=str.substring(9, str.length()-4);
String[] ary=str.split("\" target=\"_blank\">");
return ary;
}
}