您的位置:首页 > 编程语言 > Java开发

通过正则表达式提取HTML正文(java实现)

2016-01-04 20:15 567 查看

场景:现有一批大量的网页数据,已经抓取到网页的body内容,但是其中有很多 <\span>、 <\p>、<\img>、<\br>、<\strong> 等标签,需要将这些标签全部过滤掉,只留下正文信息。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetContent {

private static String REGEX = "<.+?>";
private static String INPUT = "";
private static String REPLACE = "";

public static void main(String[] args) throws IOException {
File file = new File("G:\\test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
INPUT += tempString;
}
reader.close();

Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // 获得匹配器对象
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: