twoice

很多时候想看小说但是在网页上找不到资源,即使找到了资源也没有提供下载,小说当然是下载下来用手机看才爽快啦!

于是程序员的思维出来了,不能下载我就直接用爬虫把各个章节爬下来,存入一个txt文件中,这样,一部小说就爬下来啦。

这一次我爬的书为《黑客》,一本网络小说,相信很多人都看过吧,看看他的代码吧。

代码见如下:

import re
import urllib.request
import time

#
root = \'http://www.biquge.com.tw/3_3542/\'
# 伪造浏览器
headers = {\'User-Agent\': \'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \' \
                         \'AppleWebKit/537.36 (KHTML, like Gecko)\'
                         \' Chrome/62.0.3202.62 Safari/537.36\'}

req = urllib.request.Request(url=root, headers=headers)

with urllib.request.urlopen(req, timeout=1) as response:
    # 大部分的涉及小说的网页都有charset=\'gbk\',所以使用gbk编码
    htmls = response.read().decode(\'gbk\')

# 匹配所有目录<a href="/3_3542/2020025.html">HK002 上天给了一个做好人的机会</a>
dir_req = re.compile(r\'<a href="/3_3542/(\d+?.html)">\')
dirs = dir_req.findall(htmls)

# 创建文件流,将各个章节读入内存
with open(\'黑客.txt\', \'w\') as f:
    for dir in dirs:
        # 组合链接地址,即各个章节的地址
        url = root + dir
        # 有的时候访问某个网页会一直得不到响应,程序就会卡到那里,我让他0.6秒后自动超时而抛出异常
        while True:
            try:
                request = urllib.request.Request(url=url, headers=headers)
                with urllib.request.urlopen(request, timeout=0.6) as response:
                    html = response.read().decode(\'gbk\')
                    break
            except:
                # 对于抓取到的异常,我让程序停止1.1秒,再循环重新访问这个链接,一旦访问成功,退出循环
                time.sleep(1.1)
                
        # 匹配文章标题
        title_req = re.compile(r\'<h1>(.+?)</h1>\')
        # 匹配文章内容,内容中有换行,所以使flags=re.S
        content_req = re.compile(r\'<div id="content">(.+?)</div>\',re.S,)
        # 拿到标题
        title = title_req.findall(html)[0]
        # 拿到内容
        content_test = content_req.findall(html)[0]
        # 对内容中的html元素杂质进行替换
        strc = content_test.replace(\'&nbsp;\', \' \')
        content = strc.replace(\'<br />\', \'\n\')
        print(\'抓取章节>\' + title)
        f.write(title + \'\n\')
        f.write(content + \'\n\n\')

就这样,一本小说就下载下来啦!!!

运行情况见图:

 

有的时候服务器会因为大量访问而认为你是个机器人就封了你的IP,可以加个随机数,让程序随机停止不同的时间。

如果下载太慢,可以使用多线程,一起下载多个章节

 

分类:

技术点:

相关文章:

  • 2021-11-28
  • 2022-01-16
  • 2022-12-23
  • 2021-11-01
  • 2021-12-14
猜你喜欢
  • 2021-08-30
  • 2021-11-04
  • 2021-10-12
  • 2021-08-30
  • 2022-02-24
  • 2022-01-01
  • 2022-01-01
相关资源
相似解决方案