python爬虫爬网络小说

最近闲的蛋疼想看一些爽文

百度到了一篇《超级学生》,在线看了一下还行,但是找了半天txt没找到完整版的

于是只能自己来爬一篇完整版的小说!

小说D版地址:https://www.enwds.com/195/

进第一章,查看源代码,发现小说内容<div id="content"><p>...</p><p>...</p>...</div>里面

爬内容分了两步:先爬<div>...</div>里面的,再爬<p>...</p>里面的。

但是不能只爬一章,还要继续爬,找下一章的链接,在<a id="pager_next" href="..." target="_top" class="next">下一章</a>里面

还要爬标题,在<h1>第...章:...</h1>里面

于是分了四个正则表达式:

  1. story_pattern1 = re.compile(r'<div id="content">(.*?)</div>', re.S)
  2. story_pattern2 = re.compile(r'<p>(.*)</p>', re.S)
  3. next_pattern = re.compile(r'<a id="pager_next" href="(.*?)"', re.S)
  4. title_pattern = re.compile(r'<h1>(.*?)</h1>', re.S)

最后流程是:

  1. 打开链接
  2. 获取html内容
  3. 获取小说内容(粗)
  4. 获取下一章链接
  5. 获取标题
  6. 获取小说内容(细)
  7. 去掉内容html标签
  8. 写入标题
  9. 写入小说内容
  10. 打开下一章链接

这样循环下去,就爬到了一篇小说!

源代码:

import urllib.request
import re

url = 'https://www.enwds.com/195/541422.html'
url_head = 'https://www.enwds.com'
next_url = ['']
file = open(r"D:\route\xxxx.txt", "a+")

while next_url[0] != '/195/':

    temp = urllib.request.urlopen(url)

    content = temp.read().decode('utf-8')

    story_pattern1 = re.compile(r'<div id="content">(.*?)</div>', re.S)
    story_pattern2 = re.compile(r'<p>(.*)</p>', re.S)
    next_pattern = re.compile(r'<a id="pager_next" href="(.*?)"', re.S)
    title_pattern = re.compile(r'<h1>(.*?)</h1>', re.S)

    story_content = re.finditer(story_pattern1, content)

    next_url = re.findall(next_pattern, content)
    url = url_head + next_url[0]
    
    title = re.findall(title_pattern, content)
    file.write(title[0] + '\n\n')
    print(title[0])

    for match in story_content:
        match_content = re.finditer(story_pattern2, match.group())
        for aa in match_content:
            result = re.sub(r'<.*?>', "", aa.group())
            file.write(result + '\n\n')
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值