闲是一种病,得治!!!
好多天了,新欢旧爱,还是要更新一下,表示我还活着。。。
今天的主题是:爬虫(好吧!是基于java的,谁让我不会Python,谁会?欢迎可以留言不同语言的同款代码)
package com.zby.home.novel;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class TestNovel1 {
//抽取方法 传入URL 获得document对象
public static Document getDocument(String url) throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
String html = EntityUtils.toString(response.getEntity(), "utf-8");
Document document = Jsoup.parse(html);
return document;
}
public static void main(String[] args) throws Exception {
//随便找的小说页面url (注:炮灰攻略我的最爱,可是这个网站怎么没有更新完?表示我看完好多年了)
String url ="https://www.qidian.com/search?kw=炮灰攻略";
//获取document
Document document = getDocument(url);
//打开网站页面 F12,你会CSS的吧!找想要模块的class...吧啦吧啦说不完啊
//Elements aEl = document.select("[class=rank-list mr0] li a[href*=book.qidian.com][class!=link]");
Elements aEl = document.select("[class=book-img-text] li a[href*=book.qidian.com][class!=link]");
//遍历获得的a标签 取出url 依次获得每本书的链接
for (Element a : aEl) {
url="https:"+a.attr("href");
document=getDocument(url);
//获得开始阅读的url
Elements readBtn = document.select("#readBtn");
String bookName = document.select(".book-info h1 em").text();
url="https:"+readBtn.attr("href");
//创建一个输出流,将爬到的小说以txt形式保存在硬盘
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E://novel/"+bookName+".txt")));
//遍历某一本书的章节
while(true){
document=getDocument(url);
//获得本章的章节名称 并输出到文本中
Elements chapterName = document.select(".j_chapterName");
bw.write(chapterName.text());
bw.newLine();
bw.flush();
//获得本章的小说内容 并输出到文本中
Elements pEl = document.select("[class=read-content j_readContent] p");
for (Element p : pEl) {
bw.write(p.text());
bw.newLine();
bw.flush();
}
//获得下一章的元素
Elements chapterNext = document.select("#j_chapterNext[href*=read.qidian.com]");
//判断下一章是否存在
//存在则继续进入下一章的链接
//不存在则跳出本书的章节遍历,进入下一本书的遍历
if(chapterNext==null || chapterNext.size()==0){
break;
}
//获得下一章的链接
url="https:"+chapterNext.attr("href");
}
//关流
bw.close();
}
}
}
好吧,磨磨蹭蹭的搞完了小说的,勉强爬了一些小说,CSS太难了o(╥﹏╥)o,但是问题有很多,我再研究研究,然后完善一下。
我的漫画