查看: 620|回复: 1

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

[复制链接]
累计签到:253 天
连续签到:1 天

1849

主题

353

回帖

1万

积分

域主

名望
0
星币
3480
星辰
6
好评
73

鼎力支持奖欢乐天使奖灌水天才奖幸运猪我是土豪在线大神

发表于 2022-12-10 11:00:00 | 显示全部楼层 |阅读模式

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

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

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

  6. headers = {
  7.     '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",
  8.     'Referer': 'http://www.biqugse.com',
  9.     "Accept-Encoding": "gzip, deflate"
  10. }

  11. async def get_content(xs_url, name):
  12.     async with aiohttp.ClientSession() as session:
  13.         async with session.get(xs_url, headers=headers) as resp:
  14.             response = await resp.content.read()
  15.             soup = BeautifulSoup(response, "html.parser")
  16.             content = soup.find("div", id="content")
  17.             data = content.text.split()
  18.             data = "\r\n".join(data)
  19.             async with aiofiles.open(f"novel/{name}.txt", mode="a", encoding="utf-8") as f:
  20.                 await f.write(data)
  21.             print(f"已经下载{name}")



  22. async def main(url):
  23.     resp = requests.get(url)

  24.     soup = BeautifulSoup(resp.text, "html.parser").find("div", attrs={"id": "list"}).find_all("dd")[9:]

  25.     tasks = []
  26.     print("开始创建异步任务")
  27.     for i in soup:
  28.         xs_url = url.rstrip("/25802/") + i.find("a").get("href")
  29.         name = i.find("a").text
  30.         print(xs_url,name)
  31.         tasks.append(asyncio.create_task(get_content(xs_url, name),name=name))
  32.     await asyncio.wait(tasks)

  33.     print("结束异步任务")


  34. if __name__ == '__main__':
  35.     print("开始执行")

  36.     main_url = "http://www.biqugse.com/25802/"
  37.     loop = asyncio.get_event_loop()
  38.     loop.run_until_complete(main(main_url))
复制代码

我发的破/解游戏的解压密码都是XDGAME
有任何问题私信版主可爱喵不要私信我,我比较少上线,可爱喵每天都会回复私信
回复

使用道具 举报

累计签到:97 天
连续签到:1 天

0

主题

86

回帖

406

积分

星光

名望
0
星币
304
星辰
0
好评
0

在线大神鼎力支持奖幸运猪灌水天才奖

发表于 2022-12-10 13:35:19 | 显示全部楼层
6
默认签名:偏爱是我家,发展靠大家! 社区反馈邮箱Mail To:service@pai.al或paijishu@outlook.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

偏爱技术社区-偏爱技术吧-源码-科学刀-我爱辅助-娱乐网-游戏源码

Powered by Discuz! X3.5

GMT+8, 2024-3-28 20:03 , Processed in 0.081699 second(s), 37 queries .

快速回复 返回顶部 返回列表