异步爬虫实战——爬取西游记小说

Python异步爬虫基础知识:异步爬虫

使用异步爬取西游记

import json

import requests
import asyncio
import aiohttp  # pip install aiohttp
import aiofiles  # pip install aiofiles


async def getCatalog(url):
    """
    获取小说的章节目录
    :param url: 获取小说的章节目录的URL
    :return: 
    """
    resp = requests.get(url)
    data = resp.json()['data']['novel']
    print(data)
    tasks = []  # 异步任务列表
    # 获取每一个章节的id获取小说内容
    for item in data['items']:
        cid = item['cid']
        title = item['title']
        tasks.append(asyncio.create_task(getChapterContent(title, cid)))
        # break
    await asyncio.wait(tasks)


async def getChapterContent(title, cid):
    """
    根据章节id获取小说内容
    :param title: 章节名称
    :param cid: 章节id
    :return:
    """
    data = {
        'book_id': book_id,
        'cid': book_id + '|' +cid,
        'need_bookinfo': 1
    }
    # 获取章节内容的url
    url = "https://dushu.baidu.com/api/pc/getChapterContent?data=" + json.dumps(data)
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            data = await resp.json()
            print(data)
            # 将章节内容写入文件(异步形式写入)
            async with aiofiles.open(f'西游记/{title}', mode='w', encoding='utf-8') as f:
                await f.write(data['data']['novel']['content'])


if __name__ == '__main__':
    book_id = '4306063500'  # 书本id
    data = {'book_id': book_id}
    # 获取章节目录的URL
    url = 'https://dushu.baidu.com/api/pc/getCatalog?data=' + json.dumps(data)
    asyncio.run(getCatalog(url))

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值