爬虫-小说下载

爬虫——小说下载

我终于爬完了这部小说,4367章,直接上代码

import requests
import re
import time
import random
from fake_useragent import UserAgent

def gethtml(url, headers):
    i = 0
    while i < 3:
        try:
            html = requests.get(url, headers=headers, timeout=30)
            return html
        except requests.exceptions.RequestException:
            i += 1


# from bs4 import BeautifulSoup as bes

# print('OK')

# headers = {
#     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
#     'Accept-Encoding': 'gzip, deflate',
#     'Accept-Language': 'zh-CN,zh;q=0.9',
#     'Cache-Control': 'max-age=0',
#     'Connection': 'keep-alive',
#     'Cookie': '_abcde_qweasd=0; _abcde_qweasd=0; Hm_lvt_169609146ffe5972484b0957bd1b46d6=1582254080; bdshare_firstime=1582254080195; Hm_lpvt_169609146ffe5972484b0957bd1b46d6=1582254147',
#     'Host': 'www.xbiquge.la',
#     'Upgrade-Insecure-Requests': '1',
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
# }
ua = UserAgent()
headers = {'User-Agent': ua.random}

# print(headers(1))
# exit()
url = 'http://www.xbiquge.la/0/445/'
resp = requests.get(url, headers=headers)
resp.encoding = 'utf-8'
# 目标小说主页源码
html = resp.text
# 小说名字

title = re.findall(r'<h1>(.*?)</h1>', html)[-1]
# print(title)
# exit()
# print(html)
# 获取每章信息
dl = re.findall(r'<dl>.*?</dl>', html, re.S)[0]
# print(dl)
# exit()
chapter_info_list = re.findall(r'<dd><a href=\'(.*?)\' >(.*?)</a></dd>', dl)
# print(chapter_info_list[0])
# exit()
# 新建文件,保存文件
fb = open('%s.txt' % title, 'w', encoding='utf-8')
# 每章节,分别下载
time_count = 0
for chapter_info in chapter_info_list:
    headers = {'User-Agent': ua.random}
    time_count = time_count + 1
    time.sleep(random.choice([0.5, 1, 1.5, 2]))
    # chapter_title = chapter_info[1]
    # chapter_url = chapter_info[0]
    chapter_url, chapter_title = chapter_info
    chapter_url = "http://www.xbiquge.la/%s" % chapter_url
    # print(chapter_url, chapter_title)
    # 下载章节内容
    chapter_response = gethtml(chapter_url, headers)
    chapter_response.encoding = 'utf-8'
    chapter_html = chapter_response.text
    # print(chapter_html)
    chapter_content = re.findall(r'<div id="content">(.*?)<script>read3\(\);</script>', chapter_html, re.S)
    # print(chapter_content)
    # 清洗数据
    # exit()
    chapter_content_str = " ".join(chapter_content)
    # print(chapter_content_str[:])
    # 数据清洗
    chapter_content_str = chapter_content_str.replace(' ', '')
    chapter_content_str = chapter_content_str.replace('\r<br />', '')
    chapter_content_str = chapter_content_str.replace('&nbsp;', '')
    chapter_content_str = chapter_content_str.replace('<br/>', '')
    # print(chapter_content_str)
    # exit()
    fb.write(chapter_title)
    fb.write(chapter_content_str)
    fb.write('\n')
    Str = '%s, %s, %s ' % (chapter_url, chapter_title, time_count)
    print(Str)
    # exit()

相较于第一次,添加了超时响应重连,添加随机的headers

# 超时重连
def gethtml(url, headers):
    i = 0
    while i < 3:
        try:
            html = requests.get(url, headers=headers, timeout=30)
            return html
        except requests.exceptions.RequestException:
            i += 1

随机的header使用了fake_useragent库。
中间有些小插曲,但断断续续是爬完了,不得不说 需要一个好网络

### 使用 Python 编写下载小说爬虫 要实现一个能够下载小说爬虫程序,可以按照以下方式构建完整的解决方案。以下是具体的技术细节以及代码示例。 #### 技术栈 为了完成此任务,需要用到以下几个核心工具和技术: - **Requests**: 发起 HTTP 请求并获取目标网页的内容。 - **BeautifulSoup (BS4)**: 解析 HTML 文档结构,提取所需的信息。 - 文件操作模块 (`open`): 将抓取的小说内容保存至本地文件。 --- #### 实现过程详解 ##### 1. 获取目标网站的页面源码 通过 `requests.get()` 方法发起 GET 请求,获取目标网页的 HTML 数据。需要注意的是,在发送请求时最好设置 User-Agent 头部信息,模拟浏览器行为以避免被服务器拒绝访问[^2]。 ```python import requests from bs4 import BeautifulSoup 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' } url = "https://example-novel-site.com" response = requests.get(url, headers=headers) if response.status_code == 200: html_content = response.text else: raise Exception(f"Failed to load page {url}, status code: {response.status_code}") ``` ##### 2. 提取章节列表及其链接 利用 Beautiful Soup 对 HTML 进行解析,找到所有的章节标题和对应的 URL 链接。通常情况下,这些信息会嵌套在 `<a>` 标签或者特定的容器标签中[^4]。 ```python soup = BeautifulSoup(html_content, 'html.parser') chapter_list = [] for a_tag in soup.select('div.chapter-list a'): chapter_title = a_tag.text.strip() chapter_url = a_tag['href'] full_chapter_url = f"https://example-novel-site.com{chapter_url}" # 补全相对路径 chapter_list.append((chapter_title, full_chapter_url)) ``` ##### 3. 下载单个章节的内容 对于每个章节的详细页面,重复上述步骤中的第一步,即再次调用 `requests.get()` 来加载该页面,并从中抽取正文部分。假设正文字体位于某个具有唯一类名的选择器下,则可以通过 BS4 的 `.select_one()` 或者 `.find()` 函数定位到它[^3]。 ```python def fetch_chapter_content(chapter_url): resp = requests.get(chapter_url, headers=headers) if resp.status_code != 200: return None ch_soup = BeautifulSoup(resp.text, 'html.parser') content_div = ch_soup.find('div', class_='content') # 假设这是存放文章主体的地方 paragraphs = [p.text.strip() for p in content_div.find_all('p')] return '\n'.join(paragraphs) ``` ##### 4. 存储所有章节到单一文件 最后一步就是遍历之前收集好的章节清单,依次读入它们的文字资料再逐条追加记录进同一个电子书籍文档里去。 ```python output_file = 'novel.txt' with open(output_file, mode='w', encoding='utf-8') as file_obj: for title, url in chapter_list[:10]: # 只处理前十个作为演示用途 print(f'Processing Chapter "{title}"...') try: text = fetch_chapter_content(url) if not text: continue file_obj.write(title + "\n\n") file_obj.write(text + "\n\n---\n\n") except Exception as e: print(f"Error processing chapter '{title}':", str(e)) print("All chapters have been saved successfully!") ``` --- #### 注意事项 尽管上面给出了一种通用的方法论框架指导如何创建自己的简易型网络文学作品采集脚本;但在实际应用过程中还需要考虑更多因素比如反爬机制规避策略、异常情况妥善处置等方面的问题[^1]^。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值