记录一下第一个简单的爬虫(爬取整个小说)

import requests
import re # 正则表达式
#下载一个网页
url = ‘https://www.qb5200.tw/xiaoshuo/63/63058/’
#模拟浏览器发送http请求
response = requests.get(url)
#编码格式
response.encoding = ‘gbk’
html = response.text
#获取小说名
title = re.findall(r’xx(.?)xx’,html)[0]#xx为正侧匹配内容
#新建一个小说文本
fb = open(’%s.txt’%title,‘w’,encoding = ‘utf-8’)
#获取每一章的信息(章节,url)
dl = re.findall(r’正文卷(.
?)’,html,re.S)[0]#re.S匹配空字符
chapter_info_list = re.findall(r’xx(.?)xx’,dl)
#循环每一章
for chapter_info in chapter_info_list:
#获取章节url和目录
chapter_url,chapter_title = chapter_info
#章节完整的url
chapter_url = ‘https://www.qb5200.tw%s’%chapter_url
#下载章节内容
chapter_response = requests.get(chapter_url)
chapter_response.encoding = ‘gbk’
chapter_content = chapter_response.text
content = re.findall(r’xx(.
?)xx’,chapter_content)[0]
#清洗数据,list没有replace属性
content = content.replace(’ ‘,’’)#例如把里面的空格替换成空
#持久化
fb.write(chapter_title)
fb.write(content)
fb.write(’\n’)
print(chapter_url)
fb.close

你可能感兴趣的:(记录一下第一个简单的爬虫(爬取整个小说))