鱼C论坛

 找回密码
 立即注册
查看: 2133|回复: 6

[作品展示] 异步爬取小说信息

[复制链接]
发表于 2019-3-8 12:54:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

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

x
本帖最后由 _谪仙 于 2020-2-25 12:42 编辑


异步抓取
代码地址: https://github.com/Crowded-Conditions/Crawlers/tree/master/Novel-qidian

  1. import aiohttp
  2. import asyncio
  3. from aiohttp.client_exceptions import ClientConnectorError, ClientError
  4. from asyncio import TimeoutError
  5. import aiofiles
  6. from tqdm import tqdm
  7. from re import compile, findall
  8. from fake_useragent import UserAgent
  9. import time

  10. # 异步抓取起点中文网的小说信息


  11. class Novels(object):
  12.     def __init__(self):
  13.         # 小说的初始界面, max_page = 4018
  14.         self.inital_url = 'https://www.qidian.com/finish?page={}'
  15.         self.browser = UserAgent()
  16.         self.headers = {
  17.             'Host': 'www.qidian.com',
  18.             'Accept-Language': 'zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7',
  19.             'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  20.             'User-Agent': self.browser.chrome,
  21.         }

  22.     async def crawl(self, url: str):
  23.         conn = aiohttp.TCPConnector(limit=200)
  24.         async with aiohttp.ClientSession(connector=conn) as session:
  25.             try:
  26.                 async with session.get(url, headers=self.headers, timeout=20) as response:
  27.                     if response.status == 200:
  28.                         return await response.text()
  29.                     else:
  30.                         raise ValueError(f'返回状态码错误<{response.status}>')
  31.             except (ClientConnectorError, ClientError, TimeoutError) as error:
  32.                 raise ConnectionError('连接失败')

  33.     async def paser_html(self, page: int, pbar):
  34.         try:
  35.             content = await self.crawl(self.inital_url.format(page))
  36.         except (ValueError, ConnectionError) as error:
  37.             print(f'起点中文网: 抓取第{page}页失败<{error}>')
  38.         else:
  39.             pattern = compile('li.*?<h4><a href="(.*?)".*?>(.*?)<.*?class="name".*?>(.*?)<.*?/em>'
  40.                             '<a.*?>(.*?)</a><i>.*?</i><a.*?>(.*?)<.*?</li>')
  41.             for result in findall(pattern, content):
  42.                 link, book, author, *style = result
  43.                 info = f'书名: {book}\n作者: {author}\n类型{"-".join(style)}\n链接: {"https:" + link}\n'
  44.                 async with aiofiles.open('起点中文网.', 'a+', encoding='utf-8') as fp:
  45.                     await fp.write('*'*40 + '\n')
  46.                     await fp.write(str(info))
  47.             pbar.update(1)
  48.         #await asyncio.sleep(2)

  49.     def run(self, max_page: int=1, step: int=300):
  50.         with tqdm(total=max_page, unit_scale=True, desc='起点中文网') as pbar:
  51.             for count in range(1, max_page+1, step):
  52.                 start = count
  53.                 end = min(count + step, max_page)
  54.                 tasks = [self.paser_html(num, pbar) for num in range(start, end)]
  55.                 loop = asyncio.get_event_loop()
  56.                 loop.run_until_complete(asyncio.wait(tasks))
  57.             time.sleep(15)


  58. if __name__ == '__main__':
  59.     max_page = 4018
  60.     start = Novels()
  61.     start.run(max_page)
复制代码





Ps:该资源已删除
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-3-11 14:53:39 | 显示全部楼层
谢谢分享
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-4-7 18:57:00 | 显示全部楼层
666
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-4-8 10:23:10 | 显示全部楼层
1
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-1-10 23:19:46 | 显示全部楼层
天秀
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-1-28 11:12:47 | 显示全部楼层
999
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-21 23:43:21 | 显示全部楼层
666
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-2 18:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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