1、查看网页源代码,获取标题、章节页链接
url = 'https://www.bqg99.com/book/109323/'
list_html = requests.get(url=url,headers=headers)
# print(list_html.text)
lis = re.findall('<dd><a href ="(.*?)">(.*?)</a></dd>',list_html.text) #提取所有章节页
title = re.findall('<h1>(.*?)</h1>',list_html.text)[0] ##这个要查看网页源代码,获取书名
2、构造章节详情页
emptylist = []
for li in lis:
herf_list = 'https://www.bqg99.com' + li[0]
# print(chapter,herf_list)
emptylist.append(herf_list)
3、获取章节标题及内容,并处理相关数据
for herf in emptylist:
req = requests.get(url=herf,headers=headers)
# print(req.text)
chapter = re.findall('<h1 class="wap_none">(.*?)</h1>',req.text)[0]
#re.S 使匹配包括换行在内的所有字符
data = re.findall('<div class="Readarea ReadAjax_content">(.*?)<p class="readinline"><a(.*?)</a></p></div>',req.text,re.S)[0]
# print(data[0])
text = data[0] #取data元组里面的第一个内容,也就是小说正文
text = text.replace('<br /><br />','\n') #用\n换行符替换
text = text.replace('请收藏本站:https://www.bqg99.com。笔趣阁手机版:https://m.bqg99.com ','') #处理掉不要的数据
4、判断文件夹是否存在,保存数据
filename = r'小说02/'
# 判断文件filename是否已经存在,不存在则创建
if not os.path.exists(filename):
os.mkdir(filename)
with open(filename + title + '.txt', 'a',encoding='utf-8') as f:
f.write(f'{chapter}\n{text}') #先写入章节,换行后写入小说正文
print(f'{chapter} 下载完成!') #提示下载成功的提示语
5、代码
import requests
import re
import os
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
url = 'https://www.bqg99.com/book/109323/'
list_html = requests.get(url=url,headers=headers)
# print(list_html.text)
lis = re.findall('<dd><a href ="(.*?)">(.*?)</a></dd>',list_html.text) #提取所有章节页
title = re.findall('<h1>(.*?)</h1>',list_html.text)[0] ##这个要查看网页源代码,获取书名
emptylist = []
for li in lis:
herf_list = 'https://www.bqg99.com' + li[0]
# print(chapter,herf_list)
emptylist.append(herf_list)
# print(emptylist)
for herf in emptylist:
req = requests.get(url=herf,headers=headers)
# print(req.text)
chapter = re.findall('<h1 class="wap_none">(.*?)</h1>',req.text)[0]
#re.S 使匹配包括换行在内的所有字符
data = re.findall('<div class="Readarea ReadAjax_content">(.*?)<p class="readinline"><a(.*?)</a></p></div>',req.text,re.S)[0]
# print(data[0])
text = data[0] #取data元组里面的第一个内容,也就是小说正文
text = text.replace('<br /><br />','\n') #用\n换行符替换
text = text.replace('请收藏本站:https://www.bqg99.com。笔趣阁手机版:https://m.bqg99.com ','') #处理掉不要的数据
# print(f'{text}')
filename = r'小说02/'
# 判断文件filename是否已经存在,不存在则创建
if not os.path.exists(filename):
os.mkdir(filename)
with open(filename + title + '.txt', 'a',encoding='utf-8') as f:
f.write(f'{chapter}\n{text}') #先写入章节,换行后写入小说正文
print(f'{chapter} 下载完成!') #提示下载成功的提示语
6、总结
a.注意数据的提取方式