小言_互联网的博客

Python爬取全书网小说

270人阅读  评论(0)

爬取全书网小说教程:
将使用到第三方库的安装 requests 安装方法:pip install requests
目标网站:http://www.quanshuwang.com/
步骤:
1、打开一本小说获取该小说对应的url
2、通过该小说的url获取到各个章节的列表
3、再通过该小说的url打开各章节的源代码
4、通过源代码获取各个章节的内容
5、下载该内容
目标小说:

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
# @Time : 2019/10/9 13:35 
# @Author : 小J
# @File : 全书网小说首页爬取.py 
# @Software: PyCharm
import re
import requests     #安装第三方库方法:pip install requests
#定义第一个函数获取该网站的源代码
def get_novel_list():
    # 请求目标网站
    response = requests.get('http://www.quanshuwang.com/')
    # 转码‘gbk’代表着中国的一种编码格式,转码是看网站的源代码设定的是什么码
    response.encoding = 'gbk'
    #源代码
    html = response.text
    #通过正则表达式来每部小说的url
    reg = r'<li><a target="_blank" href="(.*?)" title=".*?" class="msgBorder">'
    # print(re.findall(reg,html))
    return re.findall(reg,html)

#定义第二个函数获取每本小说对应的源代码
def get_chapter_list(novel_url):   #使用正则匹配到对应的url链接
    response = requests.get(novel_url)
    response.encoding = 'gbk'
    html = response.text
    # print(html)
    #使用正则来匹配每本小说开始阅读的url  ()在正则中可以表示打印
    reg = r'<a href="(.*?)" class="reader" title=".*?">开始阅读</a>'
    # print(re.findall(reg,html)[0])   #这里为什么使用[0]是因为对应的列表元素为0,为了把url取出来
    #定义一个变量来接收url方便第二次使用正则
    chap_list_url = re.findall(reg,html)[0]
    response = requests.get(chap_list_url)
    response.encoding = 'gbk'
    html = response.text
    # print(html)
    #通知正则来匹配不同章节对应的内容
    reg = r'<li><a href="(.*?)" title=".*?">(.*?)</a></li>'
    # print(re.findall(reg,html))
    return re.findall(reg,html)


#定义第三个函数来获取小说内容
def get_chapter_count(chapter_url):   #调用小说章节对应的url
    response = requests.get(chapter_url)
    response.encoding = 'gbk'
    html = response.text
    #通过正则来匹配对应每本小说url的内容
    #注意:为什么要在()加\ 第一个 在匹配的过程中()是有特殊意义的所有我们在进行一个转义
    # 第二个 匹配多行内容我们需要用re.S
    reg = r'style5\(\);</script>(.*?)<script type="text/javascript">style6\(\)'
    response = requests.get(chapter_url)
    response.encoding = 'gbk'
    html = response.text
    # print(re.findall(reg,html,re.S)[0])
    return re.findall(reg,html,re.S)[0]




#把小说从列表取出来
for novel_url in get_novel_list():
    #从列表拿取出来
    for i in get_chapter_list(novel_url):
        chapter_url = i[0]   #定义一个变量来储存url链接
        chapter_name = i[1]    #定义一个变量来储存对应url的名字
        # print(chapter_novel,chapter_name)
        chapter_count = get_chapter_count(chapter_url)
        fn = open(chapter_name+'.html','w')
        fn.write(chapter_count)
        fn.close()
        break
    break    #使用break意义是拿一本小说举例
    # print(novel_url)

转载:https://blog.csdn.net/qq_37662827/article/details/102458855
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场