import time
import requests
from lxml import etree
class dl_five():
# 发送请求
def get_url(self):
res = requests.get(self.url,headers=self.headers).text
return res
# 对数据进行解析
def parse_url(self,res):
data = etree.HTML(res)
datas = data.xpath('/html/body/div[4]/dl[1]/dd') # 获取到目录列表
for i in datas:
chapter = i.xpath('./a/text()')[0] # 获取目录名称
content = i.xpath('./a/@href')[0] # 获取内容地址
url_content = f'https://www.bbiquge.net/book/84680/{content}' # 获取内容网页的url
res_cont = requests.get(url_content,headers=self.headers) # 对内容的网页发送请求
res_cont.encoding = 'gbk' # 设置解析编码
cont_data = etree.HTML(res_cont.text) # 对网页进行解析
shengrou = cont_data.xpath("//*[@id='content']/text()") # 获取到内容
shurou = "".join(shengrou).replace("\xa0\xa0\xa0\xa0","\n") # 内容有大量空白\xa0,对空白进行处理,并换行
self.save_data(chapter,shurou) # 对获取到的内容进行保存
# 保存为txt文本文档
def save_data(self,chapter,shurou):
cun = r'D:\python\pycharm项目总包\爬虫班课程\学习后实战\Dragon\chapter\{}.txt'.format(chapter) # 文件存储路径
with open(cun,'w',encoding='utf-8')as f: # 设置保存地址以及文件名,写入模式和编码
f.write(shurou) # 写入文本
print(f"{chapter}-->下载完成") #控制台进度条
def main(self):
start = time.time()
# for y in range(1,20):
self.url = f'https://www.bbiquge.net/book/84680/index_{1}.html' #
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}
res = self.get_url()
self.parse_url(res)
end = time.time()
print(f'耗时:{end - start}')
if __name__ == '__main__':
l = dl_five()
l.main()
我电脑目前没有装显卡,用的核显
cpu: i5-12400
内存:金士顿 DDR4 16GB*1
硬盘:西部数据 SN570 蓝盘 1TB
主板:华硕 H610M-A D4
跟踪一下主要慢的地方在哪里?哪个地方消耗的资源多。