爬虫之爬取起点热门小说并保存到本地

前言:

案例中用到的Httpclientutil工具类请参考上一篇文章https://blog.youkuaiyun.com/qq_15076569/article/details/83015044

import com.xucj.jsoup.Httpclientutil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;

public class QiDianSpider {

    public static void main(String[] args) throws IOException {
        String url = "https://read.qidian.com/chapter/R-_rpa5go0s1/eSlFKP1Chzg1";
        boolean first = true;
        FileOutputStream fileOutputStream = null;
        File f = null;
        while (true){
            String html = Httpclientutil.getHtmlByUrl(url);
            Document document = Jsoup.parse(html);
            if(first){
                //书名
                Elements bookName = document.select("#j_textWrap .book-cover-wrap h1");
                System.out.println(bookName.text());
                //作者
                Elements author = document.select("#j_textWrap .book-cover-wrap h2");
                System.out.println(author.text());
                //类型
                Elements typeAndTextCount = document.select("[class=info-list cf] ul li p");
                System.out.println(typeAndTextCount.text().split(" ")[0]);
                //连载字数
                System.out.println(typeAndTextCount.text().split(" ")[1]);
                //上架时间
                Elements sjDate = document.select("[class=info-list cf] ul li em");
                System.out.println(sjDate.text());
                first = false;
                f = new File("C:\\Users\\DELL\\Desktop\\"+bookName.text()+".txt");
                fileOutputStream = new FileOutputStream(f);
                if(!f.exists()){//不存在则创建路径
                    f.mkdirs();
                }
            }
            //内容
            StringBuffer sb = new StringBuffer();
            //1.内容标题
            Elements contextTitle = document.select(".main-text-wrap .j_chapterName");
            sb.append(contextTitle.text());
            //2.章节内容
            Elements contextText = document.select("[class=read-content j_readContent] p");
            for (Element text : contextText) {
                sb.append("\r\n"+text.text());
            }
            System.out.println(sb.toString());
            //写入到文本中
            fileOutputStream.write(sb.toString().getBytes());
            //获取下一章内容
            Elements next = document.select("#j_chapterNext[href*=read.qidian.com]");
            if(next == null || next.size() == 0){
                fileOutputStream.close();
                break;
            }
            url = "https:"+next.attr("href");
            System.out.println(url);
        }
    }
}  

 

### 使用 Python 编写爬虫程序抓取起点小说的内容 以下是基于 `requests` 和 `BeautifulSoup` 库编写的代码示例,用于抓取起点小说的内容: #### 安装依赖库 在运行代码之前,请确保安装了所需的库: ```bash pip install requests beautifulsoup4 ``` #### 爬虫代码示例 ```python import requests from bs4 import BeautifulSoup def fetch_novel_content(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } try: response = requests.get(url, headers=headers) response.raise_for_status() # 检查请求状态码是否正常 response.encoding = 'utf-8' # 设置编码方式 soup = BeautifulSoup(response.text, 'html.parser') # 查找小说正文所在的 div 标签 content_div = soup.find('div', {'id': 'novelcontent'}) if not content_div: raise ValueError("未找到小说内容区域") paragraphs = content_div.find_all('p') # 获取所有的 p 标签 novel_text = '\n'.join([para.get_text(strip=True) for para in paragraphs]) # 提取纯文本拼接 return novel_text except Exception as e: print(f"发生错误: {e}") return None if __name__ == "__main__": url = input("请输入起点小说章节的 URL 地址: ") text = fetch_novel_content(url) if text: with open("novel_chapter.txt", "w", encoding="utf-8") as file: file.write(text) print("小说内容已成功保存到 novel_chapter.txt 文件中!") ``` 此代码实现了以下功能: 1. 发送 HTTP 请求访问指定的小说章节页面[^1]。 2. 解析 HTML 页面中的 `<div>` 标签及其子节点 `<p>` 的内容[^2]。 3. 将提取的小说正文保存本地文件。 --- #### 注意事项 1. 起点中文网可能具有反爬机制,频繁请求可能会触发 IP 屏蔽。建议设置合理的延时或使用代理池。 2. 需要尊重网站的服务条款和版权规定,在合法范围内使用爬虫工具。 3. 如果目标网页结构发生变化,则需调整解析逻辑以适配新的 DOM 结构。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值