一个简单的爬虫项目(爬取小说)

  • 目录
    1.工具介绍
    2.详细代码介绍
    3.完整代码
    4.结果呈现

1.工具介绍
1.1我们所需要用到第三方库
requests #爬虫所需要的最基本的第三方库
re #正则表达式
1.2安装的方式

pip install requests
pip install re

1.3导入第三方库的方式

import requests
import re

2.详细代码介绍
首先请求我们要访问的页面的url(这里是随机选择的笔趣阁的一本小说爬取)

url = 'http://www.biquge.info/10_10582/'

使用get方法请求数据对象,并给他一个响应参数

response = requests.get(url)

因为爬取的字体可能会发生乱码,所以我们在这里设置一下(这里的字体编译不一定要加上,如果下面请求文本的时候发生乱码就可以加上,或者直接设置为utf-8编码。)

response.encoding = response.apparent_encoding

设置一个参数接受我们请求响应的对象的文本内容

html_data = response.text

这里使用正则表达式(此处的 (.*?) 算是正则表达式里面的一个万能提取公式)提取我们的小说章节下的url以及标题,并构建一个列表

result_list = re.findall('<dd><a href="(.*?)" title=".*">.*</a></dd>', html_data)
top_10 = result_list[1:11]

在列表里面循环打印出每个章节的小标题以及获取到章节下的文本内容并打印输出

for top in top_10:
    all_url = 'http://www.biquge.info/10_10582/' + top

    response_2 = requests.get(all_url)
    response_2.encoding = response_2.apparent_encoding
    html_data_2 = response_2.text
    title = re.findall('<h1>(.*?)</h1>', html_data_2, re.S)[0]
    contend = re.findall('<div id="content"><!--go-->(.*?)</div>', html_data_2, re.S)[0]
    print(title, contend)

最后在当前目录下直接创建一个文件夹并以章节命名

 with open('三寸人间\\' + title + '.txt', mode='w', encoding='utf-8') as f:
        f.write(contend.replace('&nbsp;', '').replace('<br/>', '\n'))
        print('正在下载:', title)

3.完整代码

import requests
import re

url = 'http://www.biquge.info/10_10582/'

response = requests.get(url)
response.encoding = response.apparent_encoding
html_data = response.text

result_list = re.findall('<dd><a href="(.*?)" title=".*">.*</a></dd>', html_data)


top_10 = result_list[1:11]

for top in top_10:
    all_url = 'http://www.biquge.info/10_10582/' + top

    response_2 = requests.get(all_url)
    response_2.encoding = response_2.apparent_encoding
    html_data_2 = response_2.text

    title = re.findall('<h1>(.*?)</h1>', html_data_2, re.S)[0]
    contend = re.findall('<div id="content"><!--go-->(.*?)</div>', html_data_2, re.S)[0]
    print(title, contend)

    with open('三寸人间\\' + title + '.txt', mode='w', encoding='utf-8') as f:
        f.write(contend.replace('&nbsp;', '').replace('<br/>', '\n'))
        print('正在下载:', title)

4.结果呈现
在这里插入图片描述

  • 5
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鎮後生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值