#下载一个网页
import requests
import re
url = 'https://www.biquge5200.cc/14_14621/'
#模拟浏览器发送http请求
response = requests.get(url)
#编码方式response.encoding = 'utf-8',如果下载下来的网页内容有中文乱码现象就需要加上这一句话
#网页源码
html = response.text
#[0]取列表下第0个元素.
#eg:title的输出结果为:['斗神狂飙无弹窗_斗神狂飙最新章节列表_斗神狂飙5200_笔趣阁']
#加上[0],就把这里面索引为0的内容提取出来了,斗神狂飙无弹窗_斗神狂飙最新章节列表_斗神狂飙5200_笔趣阁
title = re.findall(r'
', html)[0]
#新建一个文件夹,保存小说内容
fb = open('%s.txt' % title, 'w', encoding='utf-8')
#获取每一章的信息(标题,章节,url).*? (这个 . 代表匹配任意字符,但是不匹配不可见字符,比如换行)
# 添加上re.S后,意味着 . 可以匹配不可见字符,[0]取列表下第0个元素
dl = re.findall(r'
.*?
', html, re.S)[0]
chapter_info_list = re.findall(r'
(.*?)
', dl)
#循环每一个章节,分别下载
for chapter_info in chapter_info_list:
try:
chapter_title = chapter_info[1]
chapter_url = chapter_info[0]
# 下载章节内容
chapter_response = requests.get(chapter_url)
chapter_html = chapter_response.text
# 取出章节内容,用正则表达式,写进记事本里
chapter_content = re.findall(r'
(.*?)
', chapter_html, re.S)[0]
#清洗数据,但是replace用不了,未完待续,来个大神救我一下。。。。
#chapter_content = chapter_content.replace(' ','')
# chapter_content = chapter_content.replace(' ', '')
# chapter_content = chapter_content.replace('', '')
#下面的代码也不能用,它给我的每个字都添加了单引号和逗号,不解
#chapter_content = [item.replace(' ', '') for item in chapter_content]
#chapter_content = [item.replace('', '') for item in chapter_content]
#数据持久化
fb.write(chapter_title)
fb.write(chapter_content)
fb.write('\n')
except IndexError:
pass
#bug:list index out of range
#失败原因:爬虫在做xpath时候匹配到空值
#解决方法:加上try.....except 错误机制跳过dd空值
学习python第二天、、爬虫第二天、、这个简单的爬虫,还有数据清洗那一块有问题,找个有缘的朋友悄咪咪的tell me 一下?在此万分感谢!
chapter_content = chapter_content.replace(' ','')这个问题还是没有解决,但是我用BeautifulSoup解决了数据清洗!请看用Python3写一个简单的爬小说的爬虫(下)https://blog.csdn.net/LiebeZQ/article/details/98189065