查看: 1771|回复: 1

[其他] python协程爬取笔趣阁小说

[复制链接]
1天累计签到
1天连续签到
初来乍到

3776

主题

11

回帖

3万

积分

总版主

名望
0 点
星币
7582 枚
星辰
0 颗
好评
2 点
发表于 1 小时前 | 显示全部楼层 |阅读模式

注册登录后全站资源免费查看下载

您需要 登录 才可以下载或查看,没有账号?立即注册

×



最近在学习python爬虫的协程部分,所以拿一个小说网站来练手。
首先使用同步爬取抓取小说章节所有的url,然后用异步的方法来保存小说内容。以txt文件保存。
食用方法python环境为 python 3.9
用到的库有requests,BeautifulSoup,asyncio,aiohttp,aiofiles,使用源码要先安装库
遇到的问题小说一共有1400+章节,但是每次爬取都只能爬1200+左右,估计是timeout。
代码贴出

  • import requests
    from bs4 import BeautifulSoup
    import asyncio
    import aiohttp
    import aiofiles
    headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
    'Referer': 'http://www.biqugse.com',
    "Accept-Encoding": "gzip, deflate"
    }
    async def get_content(xs_url, name):
    async with aiohttp.ClientSession() as session:
    async with session.get(xs_url, headers=headers) as resp:
    response = await resp.content.read()
    soup = BeautifulSoup(response, "html.parser")
    content = soup.find("div", id="content")
    data = content.text.split()
    data = "\r\n".join(data)
    async with aiofiles.open(f"novel/{name}.txt", mode="a", encoding="utf-8") as f:
    await f.write(data)
    print(f"已经下载{name}")
    async def main(url):
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text, "html.parser").find("div", attrs={"id": "list"}).find_all("dd")[9:]
    tasks = []
    print("开始创建异步任务")
    for i in soup:
    xs_url = url.rstrip("/25802/") + i.find("a").get("href")
    name = i.find("a").text
    print(xs_url,name)
    tasks.append(asyncio.create_task(get_content(xs_url, name),name=name))
    await asyncio.wait(tasks)
    print("结束异步任务")
    if __name__ == '__main__':
    print("开始执行")
    main_url = "http://www.biqugse.com/25802/"
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(main_url))

复制代码
默认签名:偏爱是我家,发展靠大家! 社区反馈邮箱Mail To:[email protected]
回复

使用道具 举报

1天累计签到
1天连续签到
初来乍到

2

主题

1万

回帖

1万

积分

偏爱AI机器人

名望
0 点
星币
2931 枚
星辰
0 颗
好评
0 点
发表于 1 小时前 | 显示全部楼层
先下为敬,有问题再回来吐槽
默认签名:偏爱是我家,发展靠大家! 社区反馈邮箱Mail To:[email protected]
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注公众号
Archiver|手机版|偏爱技术社区-偏爱技术吧-源码-科学刀-我爱辅助-娱乐网--教开服-游戏源码

相关侵权、举报、投诉及建议等,请发 E-mail:[email protected]

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖
关注公众号
返回顶部