提取网页标题信息
对指定目录下全部网页文件标题信息抽取工具的设计与实现
掌握实际应用需求Java基于文件读写的应用,掌握文件读写的应用File掌握目录文件的方法;String处理字符串的方法。
1) 选择至少3个不同的互联网页面并保存到指定的目录中;
2) 扫描目录下的所有网页文件,识别并提取网页中的网页标题信息(如:
3) 将提取结果保存到结果文件中result.txt。
4)可选扩展功能:可视化操作界面、自动采集等。
1) 基于Java语言实现;
2) 提取结果保存格式:网页文件(包括完整路径)#网页标题(不为空);
3) 每个网页文件的抽取结果是单独的。
Java代码:
package pk1; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class cl1 {
//匹配标题函数 public static List getContext(String html) {
List resultList = new ArrayList(); Pattern p = Pattern.compile("<title>([^</title>]*)"); //匹配<title>开头,</title>结尾的文档 Matcher m = p.matcher(html ); //开始编译 while (m.find()) {
resultList.add(m.group(1)); ////获得匹配部分 } return resultList; } //获取网页源代码 publicstatic String getHtml(String address, String param) {
String result = "";
String urlName = "";
try {
urlName = address + param;
URL url = new URL(urlName);
BufferedReader in = new BufferedReader(
new InputStreamReader( url.openStream(), "utf-8"));
String line;
PrintWriter pw=null;
while ((line = in.readLine()) != null) {
result += line+"\n";
List resultList = getContext(line);
for (Iterator iterator = resultList.iterator(); iterator.hasNext();)
{
String context = (String) iterator.next();
if(context==null) {
//判断抽取的标题是否为空,在输入指定文件中
pw=new PrintWriter(new FileWriter("D:\\result.txt",true));
pw.print(address + " #" + "\n");
}
else {
pw=new PrintWriter(new FileWriter("D:\\result.txt",true));
pw.print(address + " #" + context + "\n");
}
}
}
pw.flush();
pw.close();
in.close();
} catch (Exception e) {
System.out.println( "与服务器连接发生异常错误 : " + e.toString());
System.out.println( "连接地址是 : "+urlName);
}
return result;
}
@SuppressWarnings("static-access")
public static void main(String[] args) {
cl1 gh = new cl1();
gh.getHtml("https://www.sina.com.cn/", "");
gh.getHtml("https://www.baidu.com/", "");
gh.getHtml("https://www.ifeng.com/", "");
}
}
https://www.sina.com.cn/ #新浪首页
https://www.baidu.com/ #百度一下,你就知道
https://www.ifeng.com/ #凤凰网