IT类作者联盟程序员

5分钟带你用Python爬完《剑来》小说(附完整代码)

2019-07-09  本文已影响8人  不学无术丶

思路:

step 1 :请求《剑来》小说站点,获取两个东西

step 1 对应代码中的get_url()函数,该函数还包括用于加速爬虫的多线程代码,经多次测试,爬完整本小说645章,大概需要5分钟
(最后一次测试总计用时:288.94552659988403s,具体时长视网络状况而定)

step 2 :遍历(for循环)step 1 得到的所有链接,同样获取两个东西

step 2 对应代码中的download()函数,该函数需要两个参数:一个是step 1 得到的小说章节链接url;一个是step 1创建的文件夹名称name

工具:Pycharm 用到的第三方库有:requests、pyquery、threading、os、time(非必需,用于记录程序运行总时间)

# -*- coding: UTF-8 -*-
import requests
from pyquery import PyQuery as pq
import threading
import time
import os


# 简单的防反爬处理:修改请求头内容
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
           'Cookie': 'Hm_lvt_acb6f2bc2dcbdaa4ceeed2289f1d0283=1562677085,1562680745,1562916025; Hm_lpvt_acb6f2bc2dcbdaa4ceeed2289f1d0283=1562922723',
           'Host': 'www.jianlaixiaoshuo.com',
           'Referer': 'http://www.jianlaixiaoshuo.com/',
           }


def get_url():
    response = requests.get("http://www.jianlaixiaoshuo.com/", headers=headers)
    response.encoding = response.apparent_encoding  # 防止响应体出现乱码
    html = pq(response.text)
    name = html('body > div:nth-child(2) > div > div > div > h1 > a').text()  # 获取小说名称
    if os.path.exists(name) == False:              # 在Python程序同目录下,以小说名称创建文件夹
        os.mkdir(name)
    links = html('body > div:nth-child(2) > div > dl > dd > a')  # 获取每章小说的链接地址
    # 构造多线程,加速爬虫
    threads = []   # 多线程列表
    for link in links.items():
        url = 'http://www.jianlaixiaoshuo.com' + link.attr.href  # 拼接出完整链接
        t = threading.Thread(target=download, args=(url, name))  # 每个链接设置一个线程
        threads.append(t)                                        # 将创建的线程依次加入到多线程列表
    for i in threads:
        i.start()  # 启动线程
    for i in threads:
        i.join()   # 阻塞当前上下文环境的线程,直到调用此方法的线程终止


def download(url, name):
    #  获取每章小说的标题和内容
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding  # 防止响应体出现乱码
    html = pq(response.text)
    title = html('#BookCon > h1').text()  # 章节名称
    content = html('#BookText').text()    # 章节内容
    file_name = name + '\\' + title + '.txt'  # 以章节名称创建.txt文件,分章节保存小说内容
    print('正在保存小说文件:' + file_name)  # 提示爬取进度
    with open(file_name, "w", encoding='utf-8') as f:
        f.write(content)


def main():    # 主函数
    start_time = time.time()  # 程序开始运行的时间
    get_url()
    print("总计用时:%s" % (time.time()-start_time))


if __name__ == '__main__':
   main()
上一篇 下一篇

猜你喜欢

热点阅读