java 爬一本小说(斗破苍穹)

import org.apache.http.HttpEntity;
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 org.junit.Test;
import java.nio.charset.Charset;

/**
 * @ClassName: demo
 * @Auther: wqy
 * @CreateTime: 2019-02-14  19:27:20
 * @Description:
 */
public class demo {
    @Test
    public void getContent() throws Exception {
        String url = "https://read.qidian.com/chapter/2R9G_ziBVg41/eSlFKP1Chzg1";
        while(url!=null){
            //1.发送一个请求
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //2.获得响应
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String html = EntityUtils.toString(entity, Charset.forName("utf-8"));
            //3.解析章节内容
            Document doc = Jsoup.parse(html);
            //3.1 获取章节名称
            Element name = doc.select(".j_chapterName").get(0);
            System.out.println("------------------------------------------------------------------------");
            System.out.println(name.text());
            //3.2 获取章节内容
            Elements contents = doc.select("div[class=read-content j_readContent] p");
            for (Element content : contents) {
                System.out.println(content.text());
            }
            //3.3 获取下一个章节的url
            Elements nextUrls = doc.select("#j_chapterNext");
            Element nextUrl = nextUrls.get(0);
            url = "https:"+nextUrl.attr("href");
        }
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值