python爬虫抓取小说

我这里是使用的requests模块和re(正则)模块
可以模仿浏览器正常访问网页返回网页源码的方式,通过正则获取到小说的名字,以及每个章节名称和对应的网页链接,并将小说正文截取出来,写入到文本中,具体代码实现如下:

# 导入requests模块
import requests
# 导入re(正则)模块
import re


def getNonelByUrl(url):
    response = requests.get(url)  # 模拟浏览器发送http请求
    response.encoding = response.apparent_encoding  # 获取浏览器编码并设置
    HTML = response.text  # 获取网页内容
    title = re.findall(r'<h2>(.*?)</h2>', HTML)[0]  # 获取小说的名字
    print(title)
    dl = re.findall(r'<dl>.*?</dl>', HTML, re.S)[0]  # 获取每一章的信息(章节,url)
    chapter_info_list = re.findall(r'<a href="(.*?)">(.*?)<', dl)  # 提取 url、章节信息
    # print(chapter_info_list)
    return (title, chapter_info_list)


def novel_download(url, list, fb):
    for chapter_info in list:
        chapter_url, chapter_title = chapter_info
        chapter_url = url + chapter_url  # 地址拼接
        # print(chapter_url, chapter_title)

        # 下载章节内容
        chapter_response = requests.get(chapter_url)
        chapter_response.encoding = chapter_response.apparent_encoding  # 设置编码
        # 进行特殊符号转换
        chapter_HTML = chapter_response.text.replace('\u3000', '').replace('&nbsp;', '') \
            .replace('&lt;', '').replace('br/&gt;', '').replace('&amp;', '').replace('lt;', '') \
            .replace('gt;', '').replace('<br />', '').replace("\r", "").replace("\n", "")

        # print(chapter_HTML)
        # text = re.findall(r'<div class="centent">(.*?)</div>', chapter_HTML, re.S)
        # print(text)
        # 提取章节内容
        chapter_content = re.compile('.*?<div class="centent">(.*?)</div>', re.S)
        # print(chapter_content)
        maintext = re.findall(chapter_content, chapter_HTML)
        # print(maintext)
        # break
        # 数据持久化
        fb.write('\n')
        fb.write(chapter_title)
        fb.write('\n')
        fb.write(maintext[0])
        # print(chapter_url)


def main():
    url = 'https://ww.sangwu8.com/book/13/13962/'
    chapterlist = getNonelByUrl(url)
    print(chapterlist[0])
    print(chapterlist[1])
    textbook = open('%s.txt' % chapterlist[0], 'w', encoding='utf-8')  # 新建一个文件,保存小说内容
    novel_download(url, chapterlist[1], textbook)


main()


执行截图如下:
可以按照章节写入文本中
image

最终输出文本结果:
image

image

posted @ 2023-07-15 19:33  kyween  阅读(507)  评论(0)    收藏  举报