Python爬虫-爬取小说-下载小说

陈占占
• 阅读 1460

一、创建文件夹

(1)、创建指定文件夹
# 判断文件夹是否存在,不存在则创建
def Judge_folder():
    folder = "novel"
    if not os.path.exists(folder):
        print("文件不存在,已创建!")
        os.mkdir(folder)
    else:
        print("文件夹已存在!")

二、获取小说网址,解析需要信息

思路:进入小说书库的网址----->获取每本小说的网址----->获取每本小说下载的网址
(1)、进入小说书库的网址,解析网页,获取对应的数据信息

Python爬虫-爬取小说-下载小说

def Url_parsing():
    # 定义数组
    int_href = []
    # 页数
    for i in range(1):
        str_value = str(i+1)
        # url-网址https://m.txt80.com/all/index_3.html
        if i + 1 > 1:
            url = "https://m.txt80.com/all/index_" + str_value + ".html"
        else:
            url = "https://m.txt80.com/all/index.html"
        # 浏览器类型-搜狗
        Search_engine = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
        # 发送请求,获取网址HTML,转为text
        Type_conversion = requests.get(url=url, headers=Search_engine, timeout=None).text.encode('iso-8859-1').decode(
            'utf-8')
        # 定义BeautifulSoup,解析网址HTML
        bs = BeautifulSoup(Type_conversion, 'html.parser')
        # 获取指定div
        scope_div = bs.find('ul', attrs={'class': 'imgtextlist'})
        if scope_div is not None:
            # print(scope_div)
            # 获取class为pic的a标签
            scope_div_a = scope_div.findAll("a", attrs={'class': 'pic'})
            # print(scope_div_a)
            # 循环打印a标签
            for int_i in scope_div_a:
                # 获取a标签对应的数据,拼接添加到数组中
                int_href.append("https://m.txt80.com/" + int_i.get("href"))
    # 返回获取到小说网址的信息
    return int_href
(2)、进入每本小说的页面中,解析对应的数据信息

Python爬虫-爬取小说-下载小说

​​def Url_parsing1():
    # https://www.txt80.com/
    int_href1 = []
    # 循环获取Url_parsing的值(返回每本小说的网址)
    for city in Url_parsing():
        url = city
        # 浏览器类型-搜狗
        Search_engine1 = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
        # 发送请求,获取网址HTML,转为text
        Type_conversion = requests.get(url=url, headers=Search_engine1, timeout=None).text.encode('iso-8859-1').decode(
            'utf-8')
        # 定义BeautifulSoup,解析网址HTML
        bs = BeautifulSoup(Type_conversion, 'html.parser')
        # 获取指定div
        scope_div = bs.find('a', attrs={'class': 'bdbtn greenBtn'})
        # print(scope_div.get("href"))
        # 获取指定div中的所有a标签
        int_href1.append("https://m.txt80.com/" + scope_div.get("href"))
    # 返回int_href1数组
    return int_href1
(3)、进入每本小说的下载页面,解析对应的数据信息

Python爬虫-爬取小说-下载小说

​​def Url_parsing2():
    for city in Url_parsing1():
        url = city
        # 浏览器类型-搜狗
        Search_engine = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
        # 发送请求,获取网址HTML,转为text
        Type_conversion = requests.get(url=url, headers=Search_engine, timeout=None).text.encode("utf-8").decode("utf-8")
        # 定义BeautifulSoup,解析网址HTML
        bs = BeautifulSoup(Type_conversion, 'html.parser')
        # 获取指定div
        scope_div = bs.find('a', attrs={'class': 'bdbtn downbtn'})
        # print(scope_div)
        requests_href = scope_div.get("href")
        requests_title = scope_div.get("title")[0:-7]
        # print(requests_href, requests_title)

三、下载小说

(1)、循环下载小说
# 定义要下载的内容
        download = requests.get(requests_href)
        # 循环打开文件创建jpg
        with open("novel/" + requests_title + ".txt", mode="wb") as f:
            f.write(download.content)
            print(requests_title + "-----下载完成!")

四、附上完整代码

import os
import time
import requests
from bs4 import BeautifulSoup


# 判断文件夹是否存在,不存在则创建
def Judge_folder():
    folder = "novel"
    if not os.path.exists(folder):
        print("文件不存在,已创建!")
        os.mkdir(folder)
    else:
        print("文件夹已存在!")


def Url_parsing():
    # 定义数组
    int_href = []
    # 页数
    for i in range(1):
        str_value = str(i+1)
        # url-网址https://m.txt80.com/all/index_3.html
        if i + 1 > 1:
            url = "https://m.txt80.com/all/index_" + str_value + ".html"
        else:
            url = "https://m.txt80.com/all/index.html"
        # 浏览器类型-搜狗
        Search_engine = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
        # 发送请求,获取网址HTML,转为text
        Type_conversion = requests.get(url=url, headers=Search_engine, timeout=None).text.encode('iso-8859-1').decode(
            'utf-8')
        # 定义BeautifulSoup,解析网址HTML
        bs = BeautifulSoup(Type_conversion, 'html.parser')
        # 获取指定div
        scope_div = bs.find('ul', attrs={'class': 'imgtextlist'})
        if scope_div is not None:
            # print(scope_div)
            # 获取class为pic的a标签
            scope_div_a = scope_div.findAll("a", attrs={'class': 'pic'})
            # print(scope_div_a)
            # 循环打印a标签
            for int_i in scope_div_a:
                # 获取a标签对应的数据,拼接添加到数组中
                int_href.append("https://m.txt80.com/" + int_i.get("href"))
    # 返回获取到小说网址的信息
    return int_href


def Url_parsing1():
    # https://www.txt80.com/
    int_href1 = []
    # 循环获取Url_parsing的值(返回每本小说的网址)
    for city in Url_parsing():
        url = city
        # 浏览器类型-搜狗
        Search_engine1 = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
        # 发送请求,获取网址HTML,转为text
        Type_conversion = requests.get(url=url, headers=Search_engine1, timeout=None).text.encode('iso-8859-1').decode(
            'utf-8')
        # 定义BeautifulSoup,解析网址HTML
        bs = BeautifulSoup(Type_conversion, 'html.parser')
        # 获取指定div
        scope_div = bs.find('a', attrs={'class': 'bdbtn greenBtn'})
        # print(scope_div.get("href"))
        # 获取指定div中的所有a标签
        int_href1.append("https://m.txt80.com/" + scope_div.get("href"))
    # 返回int_href1数组
    return int_href1


def Url_parsing2():
    for city in Url_parsing1():
        url = city
        # 浏览器类型-搜狗
        Search_engine = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
        # 发送请求,获取网址HTML,转为text
        Type_conversion = requests.get(url=url, headers=Search_engine, timeout=None).text.encode("utf-8").decode("utf-8")
        # 定义BeautifulSoup,解析网址HTML
        bs = BeautifulSoup(Type_conversion, 'html.parser')
        # 获取指定div
        scope_div = bs.find('a', attrs={'class': 'bdbtn downbtn'})
        # print(scope_div)
        requests_href = scope_div.get("href")
        requests_title = scope_div.get("title")[0:-7]
        # print(requests_href, requests_title)
        # 定义要下载的内容
        download = requests.get(requests_href)
        # 循环打开文件创建jpg
        with open("novel/" + requests_title + ".txt", mode="wb") as f:
            f.write(download.content)
            print(requests_title + "-----下载完成!")


def Exception_error():
    Judge_folder()
    try:
        Url_parsing2()
    except KeyboardInterrupt:
        print('\n程序已终止. . . . .')
    print('结束!')


def Time():
    # 记录程序开始运行时间
    start_time = time.time()
    s = 0
    Exception_error()
    # 记录程序结束运行时间
    end_time = time.time()
    ts = end_time - start_time
    dt = time.strftime("%M分%S秒", time.localtime(ts))
    print(dt)
    return s


def Start():
    Time()


if __name__ == '__main__':
    Start()

Python爬虫-爬取小说-下载小说

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
2年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
ES6 新增的数组的方法
给定一个数组letlist\//wu:武力zhi:智力{id:1,name:'张飞',wu:97,zhi:10},{id:2,name:'诸葛亮',wu:55,zhi:99},{id:3,name:'赵云',wu:97,zhi:66},{id:4,na
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这