前言:
爬取《斗破苍穹》全文小说
目标:
- 将《斗破苍穹》全文小说爬取下来
- 保存在一txt文本文件中
- 使用正则表达式匹配相应内容
本文为整理代码,梳理思路,验证代码有效性——2019.12.8
环境:
Python3(Anaconda3)
PyCharm
Chrome浏览器
主要模块:
re
requests
time
1.
分析欲要爬取网页的网址及其结构,打开Chrome开发者工具,如下图我们分析得出http://www.doupoxs.com/doupocangqiong/1.html
这里的数字1即为小说章节数,那么我们可以通过fomat的方式对小说章节链接进行遍历
通过最后一个li标签或者网页最后的章节可知,这里有1646章,那么我们的表达式为urls = ['http://www.doupoxs.com/doupocangqiong/{}.html'.format(str(i)) for i in range(1, 1647)]
2.
用正则表达式匹配获取小说内容
分析第一章的网页结构可以知道小说内容均在标签<p>
内,即我们的正则表达式为contents = re.findall('<p>(.*?)</p>', html, re.S)
3.
将小说内容保存到一文本文件中
保存过程比较简单,“将大象装进冰箱”三步
- “打开冰箱”
# 新建TXT文档,追加的方式
f = open('doupo.txt', 'a+')
- “将大象装进去”
for content in contents:
new_con = str(content).replace('</p>', '').replace('<p>', '')
f.write(new_con+'\n') # 正则获取数据写入TXT文件中
f.write("---------------------------------\n" # 分割线
"---------------------------------\n"
"---------------------------------\n")
- “关上冰箱”
f.close() # 关闭TXT文件
A.数据截图
B.完整代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 导入相应的库文件
import requests
import re
import time
# 加入请求头
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
# 定义获取信息的函数
def get_info(url):
res = requests.get(url, headers=headers)
html = res.content.decode('utf-8')
print(url, res.status_code)
if res.status_code == 200: # 判断请求码是否为200
contents = re.findall('<p>(.*?)</p>', html, re.S)
for content in contents:
new_con = str(content).replace('</p>', '').replace('<p>', '')
f.write(new_con+'\n') # 正则获取数据写入TXT文件中
f.write("---------------------------------\n" # 分割线
"---------------------------------\n"
"---------------------------------\n")
# 程序主入口
if __name__ == '__main__':
# 构造多页URL
urls = ['http://www.doupoxs.com/doupocangqiong/{}.html'.format(str(i)) for i in range(1, 1647)]
# 新建TXT文档,追加的方式
f = open('doupo.txt', 'a+')
for url in urls:
get_info(url) # 循环调用get_info()函数
time.sleep(1) # 睡眠1秒
f.close() # 关闭TXT文件