# 导入必备的包
# 本文爬取的是顶点小说中的完美世界为列。文中的aa.text,bb.text为自己创建的text文件
import requests
from bs4 import BeautifulSoup # 爬取目标url url = 'https://www.x23us.com/html/42/42377/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3393.4 Safari/537.36'
} # 单独的函数,用于打开bb文件,bb文件用于存章节的url
def open_href():
with open('bb.text', 'r', encoding='utf-8') as f:
a = f.readlines()
f.close()
# 将文件里的所有url读出并以列表的形式返回
return a # 请求目标网址,并返回文本源码
def page_index():
html = requests.get(url, headers=headers)
if html:
return html.text # 将目标网址进行解析,得到所有章节的url
def page_list(html):
if html:
a = []
html_bs4 = BeautifulSoup(html, 'lxml')
html_b = html_bs4.select('.L a')
for i in html_b:
title = i.get_text()
href = url + i.get('href')
data = {
'title': title,
'href': href
}
a.append(data)
return a # 将aa文件打开并将得到的章节内容写进文件里并关闭存档
def text_cun_html(title, html):
if html:
with open('aa.text', 'a+', encoding='utf-8') as f:
f.write(title + '\n' + html + '\n')
f.close()
print('存档成功!!!!')
return 'yes'
else:
None # 将bb文件打开并将写入aa文件相对应的url写进bb文件里并关闭存档
def text_cun_href(href):
if href:
with open('bb.text', 'a+', encoding='utf-8') as f:
f.write(href + '\n')
f.close()
print('href存档成功!!')
return 'ok'
else:
None # 将得到的章节url解析并二次请求获取章节内容
def html_list_index(title, href):
if href:
html = requests.get(url=href, headers=headers)
if html.status_code == 200:
bs = BeautifulSoup(html.text, 'lxml')
bs4 = bs.select('#contents')
for item in bs4:
a = text_cun_html(title, item.get_text())
# 章节内容存档成功返回yes
if a == 'yes':
text_cun_href(href)
else:
None def main():
# 首先获取下bb文件的url列表
number = open_href()
print(number)
html = page_index()
data = page_list(html)
for i in data:
title = i.get('title')
href = i.get('href')
print(href)
# 判断发生异常后,在启动服务时,我们过滤掉已爬取过的url
if href + '\n' not in number:
html_list_index(title, href)
else:
None if __name__ == '__main__':
main() #简单思路实现断点续存,不喜勿喷,欢迎共同讨论

最新文章

  1. 计数器(counter),有序字典(OrderDict),默认字典(defaultdict),可命名元祖(namedtuple),双向队列(deque),单项队列(deuqe.Queue)
  2. Photoshop 融合属性 Unity Shader
  3. 利用smarty call函数实现无限极分类
  4. hihocoder 1043 完全背包
  5. Java笔记(二十五)……其他常用API
  6. 12 hdfs常用文件、目录拷贝操作、删除操作
  7. MySQL 大DML操作建议
  8. Windows 8 动手实验系列教程 实验6:设置和首选项
  9. PHPCMS V9 为今天或几天前文章加new
  10. RT5350的uvc驱动支持yuv格式摄像头成功
  11. vue的组件和生命周期
  12. Linux 定时执行shell脚本命令之crontab
  13. 【BZOJ3233】【tyvj1729】文艺平衡树
  14. Oracle客户端的安装与远程连接配置
  15. Intellij IDEA2017.3永久激活方法
  16. phpmyadmin快速安装
  17. django2.1---中间件
  18. spring-security-4 (2)spring security 基于Java配置的搭建
  19. jquery之超简单的div显示和隐藏特效demo
  20. [pixhawk笔记]6-uORB流程及关键函数解析

热门文章

  1. 【Linux_Shell 脚本编程学习笔记四、监控系统内存并报警企业案例脚本】
  2. Qt foreach关键字用法
  3. fare|gave it away|catch a glimpse |involve|rip|eternalstiff|
  4. 吴裕雄--天生自然HTML学习笔记:HTML 元素
  5. 关于JavaScript中bind、applay、call的区别
  6. ES介绍与实践
  7. Linux下多线程复制文件(C)
  8. 用 Python 读写 Excel 表格
  9. C++学习之旅
  10. python基础-流程控制语句