Jsoup 爬取文章

//爬虫类
public class Test {
//需求1:通过一个定的技术,从http://news.sohu.com/爬取这个网站上的文章
//需求2:获取文章的标题,获取文章的内容,最终保存到本地(以文章标题作为文件的名称,文章内容作为文件内容,后缀名为txt的文件) 标题.txt
public static void main(String[] args) throws Exception {
//jsoup是一个java后台解析html代码的一个工具(也可以模拟浏览器发送网络请求)
//1.用jsoup的方式模拟浏览器发送一个请求
Document document = Jsoup.connect("http://news.sohu.com/").get();
//2.获取class属性为list16的div
Elements divs = document.select(".list16");
//3.得到每一个div
for (Element div : divs) {
// System.out.println(div);
//因为标题在a标签中,想获取标题,必须现获取a标签
Elements as = div.select("a");
for (Element a : as) {
// System.out.println(a);
//获取a标签中属性为title的值
String title = a.attr("title");
title.replace("|", "").replace("|", "").replace("\\", "").replace(":", "").replace("*", "").replace("\"", "").replace("?", "").replace("<", "").replace(">", "");
//a标签的href属性值的连接,就是文章详情的链接地址,因此我们必须现获取文章href的值(是一个网址),这个网址
//就是进入文章详情的网址,想要获取文章内容,必须得访问文章详情的网址
String url = a.attr("href");
// //www.sohu.com/a/384139596_114941
if(!url.startsWith("http")) {
// http://www.sohu.com/a/384139596_114941
url="http:"+url;
}

System.out.println(url);
System.out.println(title);
//再次利用jsoup来模拟浏览器发送请求
Document document2 = Jsoup.connect(url).get();
// System.out.println(document2);
//获取标签为article的所有的元素
Elements articles = document2.select("article");
for (Element element : articles) {
//获取所有的文章内容
String content = element.text();
// System.out.println(content);
//把文章内容和标题,分别写入到本地文件(以文章标题作为文件标题,文章内容作为文件内容)
FileUtilIO.writeFile("D:/爬虫/"+title+".txt", content, "utf-8");
}

}

}
}

}

进行读写的util

public class FileUtilIO {


public static void writeFile(String path, String content, String charset) throws IOException {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
if(content!=null) {
bw.write(content);
}
bw.flush();
bw.close();
}

public static String readFile(File file, String charset) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
StringBuffer sb = new StringBuffer();
String content = null;
while ((content = br.readLine()) != null) {

sb.append(content);
}
br.close();
return sb.toString();

}

}

猜你喜欢

转载自www.cnblogs.com/shanzhongqi/p/12691094.html