Python是没有什么不能做的,我想我这样说,应该没有人出来反对吧!
前言
虽然说Python可以爬取小说,但是咱们还是得支持作者的辛苦写作的结果,支持正版!
本篇文章虽然是爬取网络小说,主要还是学习交流为主嘛!
什么是网络爬虫
百度百科解释:网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。
个人看法:当你需要获取大量数据或者批量处理的时候,Python爬虫可以快速做到这些,从而节省你重复劳动时间。比如:微博私信机器人、批量下载美剧、爬取天猫京东网站获取折扣、刷折扣机票、爬取适合的房源、系统管理员的脚本任务等等。
其实这个案例很简单!
就用到了两个模块
requests和re
完整代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import requests
# url1 = 'https://www.ybdu.com/xiaoshuo/2/2531/259845.html'
#Python学习交流群:125240963,群内每天分享干货,包括最新的python企业案例学习资料和零基础入门教程,欢迎各位小伙伴入群学习交流
def get_html(url):
response = requests.get(url)
return response.text
def get_chapter_info(html):
ul = re.findall(r'<ul class="mulu_list">(.*?)</ul>', html, re.S)[0]
chapter_info = re.findall(r'<a href="(.*?)">(.*?)</a>', ul)
return chapter_info
def get_chapter_content(url):
print(url)
response = get_html(url)
content = re.findall(r'<div id="htmlContent" class="contentbox">(.*?)<div class="ad00">', response, re.S)[0]
content = content.replace(' ', '')
content = content.replace('<br />', '')
return content
def main():
url = 'https://www.ybdu.com/xiaoshuo/2/2531/'
html = get_html(url)
title = re.findall(r'<h1>(.*?)全文阅读</h1>', html)[0].strip()
chapter_info = get_chapter_info(html)
with open('%s.txt' % title, 'w', encoding='utf-8')as f:
f.write('%s\n' % title)
for chapter in chapter_info:
f.write('%s' % chapter[1])
content = get_chapter_content(url+chapter[0])
f.write('%s' % content)
if __name__ == '__main__':
main()
运行效果