爬取小说
#导入模块 爬虫:requests 和 正则:re
import requests
import re
#输入网址
url=‘http://www.shuquge.com/txt/5809/index.html’
response=requests.get(url,)
response.encoding=‘utf-8’ # 定义编码格式(或用gbk)
#print(response.text)
#小说名 例:《元尊》
title=“元尊”
f=open("%s.txt"%title,“w”,encoding=‘utf-8’)
#print(response.text)
print("----------------------------------------------------------------------------------------------------------------------------------")
print("----------------------------------------------------------------------------------------------------------------------------------")
#目标小说的目录代码
html=response.text
#d1=re.search(r’
《元尊》正文 (. ?)元尊相关推荐:’,html,re.S).group(1)d1=re.search(r’ 《元尊》正文 (.?) 元尊相关推荐:’,html,re.S).group(1)
print(d1)
#mulu1=re.search(r’(正文)?(.?)’,d1)
mulu1=re.findall(r’(正文 )?(.?)<’,d1)
print(mulu1)
#访问每一章 下载
for i in mulu1:
chapter_title = i[-1]
chapter_url = ‘http://www.shuquge.com/txt/5809/’ + i[0]
print(chapter_url,chapter_title)
# # # 下载章节内容
chapter_response = requests.get(chapter_url)
chapter_response.encoding = ‘UTF-8’
chapter_html = chapter_response.text
# print(chapter_html)
chapter_content=re.search(r'<body id="wrapper"> (.*?)All Rights Reserved.',chapter_html,re.S)[0]
# chapter_content=chapter_content[0]
# print(chapter_content)
# #清洗数据
chapter_content = chapter_content.replace(' ','')
chapter_content = chapter_content.replace('<br/>', '')
chapter_content = chapter_content.replace(' ', '')
# # # 保存
print(chapter_content)
f.write(chapter_title)
f.write(chapter_content)