python初探——下小说

听说python现在很火,且有很强大的网络爬虫功能,对我来讲有一点适用,就是用来下载自己喜欢的小说,整理好格式,放到手机里看(如用“掌阅”)。

以前也折腾了一段时间,没搞出来。现在又重拾,这次成功了。

主要是找到一段好例子,简单,不用啥狗屁组件,增加学习成本。其实我只用到很少的功能,我喜欢自己来。其次是找到一个好用的工具JetBrains PyCharm,用 Community 版是免费的。

总结一下:

使用了如下两个库:

requests:用来读网页,扒内容;

re:正则表达式,用来解析html,提取想要的文本。

不叽歪了,贴代码:

import requests
import re

//获取网页内容
url = 'https://www..........'
response = requests.get(url)
response.encoding = 'gbk' //据实际网页来,有的是utf-8
html = response.text
//生成以小说名命名的文件
title = re.findall(r'<h1>(.*?)</h1>', html)[0]
fb = open('%s.txt' % title, 'w', encoding='utf-8') //这里是写到自己的文本文件中,要用uft-8的
# print(html)

//获取目录
menu = re.findall(r'<dd>(.*?)</dd>', html, re.M | re.S) //M 表示多行,S 表示匹配换行符,不加这两参数,是匹配不到大段DOM内容的

# print(menu)

//循环获取每个章节的内容,写入文件
for chapter_info in menu:
chapter_info_list = re.findall(r'<a href="(.*?)" title="(.*?)">.*?</a>', chapter_info)[0]
chapter_url = chapter_info_list[0]
chapter_title = chapter_info_list[1]
if 'http' not in chapter_url:
chapter_url = 'https://www........' + chapter_url
chapter_response = requests.get(chapter_url)
chapter_response.encoding = 'gbk'
chapter_html = chapter_response.text //获取内容页
chapter_content = re.findall(r'<div class="zj_text" id="content1">(.*?)</div>', chapter_html, re.M | re.S)[0] //解析内容页
chapter_content = chapter_content.replace('&nbsp;&nbsp;&nbsp;&nbsp;', ' ') //整理格式
chapter_content = chapter_content.replace('<br>', '\n')
chapter_content = chapter_content.replace('<br />', '\n')
fb.write(chapter_title)
fb.write('\n')
fb.write(chapter_content)
fb.write('\n')
fb.write('\n')

猜你喜欢

转载自www.cnblogs.com/wildorchid/p/9878045.html
今日推荐