python爬取网站小说,保存到TXT文件

python爬取网站小说,保存到TXT文件


概述,首先获得某一章的html代码,然后用正则表达式过滤出章节名称和章节内容,保存到TXT中。本程序只保存了一本小说。

import json
import requests, random
from requests.exceptions import RequestException
import re
import time

def get_one_page(url):
	#请求头
	headers ={
		'User-Agent':'Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/52.0.2743.116 Safari/537.36'
	}
	
	#打印当前时间
	print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) )
	response = requests.get(url, headers = headers)
	#response = requests.get(url,proxies=http,timeout=3)
	print(response.status_code)
	if response.status_code == 200:
		return response.content.decode('utf-8')
	return None
#找到所有章节的链接
#chcp 65001 设置控制台编码
def parse_one_page(html):

	#正则表达式
	pattern = re.compile(
		'<div id="book_text">(.*?)</div>',re.S
	)
	#对文本进行筛选
	items = re.findall(pattern,html)
	
	print(items)
	for item in items:
		print(item)
		yield{
				'index':item
			}
#筛选出章节名称
def parse_one_page_head(html):
	#print(html)
	#正则表达式
	pattern = re.compile(
		'<h1>(.*)</h1>',re.S
	)
	#对文本进行筛选
	items = re.findall(pattern,html)
	
	
	for item in items:
		print(item)
		yield{
				'index':item
			}
			
#将结果保存到文本文档中	
def write_to_file(content):
	with open('huanleyingxiong.txt','a',encoding='utf-8') as f:
		f.write(json.dumps(content,ensure_ascii=False)+'\n')
	
def main(offset):
	url = 'http://www.bequgew.com/99647/'+str(offset)+'.html'
	html = get_one_page(url)
	#首先筛选出章节
	for item in parse_one_page_head(html):
		print(item)
		write_to_file(item)
	
	#筛选出段落
	for item in parse_one_page(html):
		print(item)
		write_to_file(item)
	
if __name__ == '__main__':
	#从第一章到最后一章
	for i in range(32668145,32668266):
		print(i)
		main(i)
		#每10秒访问一次
		time.sleep(5)
		


推广:本群目前25人,目标50人。男女比例平衡,群主定期发红包,大家谈谈幸福,谈谈梦想,谈谈兴趣,欢迎北漂的河北老乡加群。
在这里插入图片描述
推广:读书网站 http://www.greendoubook.cn/read/home.action

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值