# 先得到每一页网址
# 通过每一页的网址得到每一章的网址
# 再通过每一章的网址得到网址内容
# 爬光笔趣阁的一部小说——圣虚
# 网址:https://www.bbiquge.net/book/24881/index_1.html
import asyncio
import aiohttp
import aiofiles
import requests
from lxml import etree
def get_href(url1): # 获取网址函数,将获取每一章的网址与每一章的名字弄成一个列表,并返回
hrefs = []
resp = requests.get(url1)
html = etree.HTML(resp.text)
result = html.xpath('/html/body/div[4]/dl/dd')
for m in result:
# print(i)
# 拿到子页面的链接
a = []
href = url.replace(f'index_{i}.html', '') + ''.join(m.xpath('./a/@href'))
# 拿到章节名字
name = ''.join(m.xpath('./a/text()'))
# print(href, name)
a.append(href)
a.append(name)
hrefs.append(a)
return hrefs
async def DownLoad(w, name): # 下载函数,还待完善
async with aiohttp.ClientSession() as session:
async with session.get(w) as resp:
dic = await resp.text()
dic_tree = etree.HTML(dic)
result = '\n'.join(dic_tree.xpath('/html/body/div[3]/div[2]/div[1]/text()'))
comment = result.encode('utf-8')
async with aiofiles.open(f'文本—圣虚/{name}', mode='wb') as f: # 下载到文本——圣虚的目录中
await f.write(comment) # 读取内容是异步的,需要挂起
print(name, '完成')
async def main(): # 主函数
tasks = []
for w in urls:
d = asyncio.create_task(DownLoad(w[0], w[1])) # 3.8以后python必须创建task,不然会报错
tasks.append(d)
await asyncio.wait(tasks)
if __name__ == '__main__': # 运行主线程就执行
for i in range(1, 2): # 这里可以更改需要现在的页数 1—2表示下载第一页
# https://www.bbiquge.net/book/24881/index_1.html 第一页网址
# https://www.bbiquge.net/book/24881/index_2.html 第二页网址
url = f"https://www.bbiquge.net/book/24881/index_{i}.html"
urls = get_href(url)
# print(urls)
asyncio.run(main())
python利用异步协程爬光一部小说,由于是刚刚开始学爬虫,主要是记录一下,代码还是有点问题,但可以运行
最新推荐文章于 2023-11-15 16:58:10 发布