ITPub博客

首页 > 应用开发 > Python > python使用 asyncio 实现异步爬虫(多 URL 并发爬取)

python使用 asyncio 实现异步爬虫(多 URL 并发爬取)

原创 Python 作者:mingtian66 时间:2025-05-19 13:47:42 0 删除 编辑

以下是使用asyncio实现异步爬虫的完整代码,支持多URL并发爬取:

import asyncio

import aiohttp

from urllib.parse import urlparse

from typing import List, Dict, Optional


class AsyncCrawler:

    def __init__(self, max_concurrency: int = 10):

        self.max_concurrency = max_concurrency

        self.semaphore = asyncio.Semaphore(max_concurrency)

        self.session = None

        self.results = []


    async def fetch(self, url: str) -> Optional[Dict]:

        try:

            async with self.semaphore:

                async with self.session.get(url, timeout=10) as response:

                    content = await response.text()

                    return {

                        'url': url,

                        'status': response.status,

                        'content': content[:200] + '...' if len(content) > 200 else content,

                        'domain': urlparse(url).netloc

                    }

        except Exception as e:

            print(f"Error fetching {url}: {str(e)}")

            return None


    async def crawl(self, urls: List[str]) -> List[Dict]:

        self.session = aiohttp.ClientSession()

        tasks = [asyncio.create_task(self.fetch(url)) for url in urls]

        self.results = await asyncio.gather(*tasks)

        await self.session.close()

        return [result for result in self.results if result is not None]


async def main(urls: List[str]):

    crawler = AsyncCrawler()

    results = await crawler.crawl(urls)

    for result in results:

        print(f"URL: {result['url']}")

        print(f"Status: {result['status']}")

        print(f"Domain: {result['domain']}")

        print("-" * 50)


if __name__ == "__main__":

    sample_urls = [

        'https://www.baidu.com',

        'https://www.qq.com',

        'https://www.163.com',

        'https://www.sina.com.cn'

    ]

    asyncio.run(main(sample_urls))

这个异步爬虫实现了并发请求控制、超时处理和结果收集功能。使用aiohttp作为HTTP客户端,通过信号量控制最大并发数,支持批量URL爬取并返回结构化结果。

www.sankangshipin.com.liyintong.com

www.yuhuatex.com.ruanding.cn

www.hnrcnykj.com.itoren.cn

www.nafine.com.iseebest.cn

www.baiyitex.com.bndaye.cn

www.zjhhtex.com.rustler.cn

www.ahzhhb.cn.excelta.cn

www.sjzhqsp.com.diaolift.cn

www.biovendor.com.tingbu.cn

www.chn-top.com.huiha.cn

www.guajiujituan.com.podang.cn

www.ktmuav.com.xuhou.cn

www.jslytj.com.zhaiti.cn

www.tiandatex.com.buzun.cn

www.btyunyang.com.zhuozou.cn

www.yihaikerry.net.cn.lazai.cn

www.ynhtyl.com.suidun.cn

www.zhuojintextile.com.zhaojunji.cn

www.donghetex.com.wanjiahua.cn

www.zhdyt.com.tujiachen.cn

www.gdnfhb.com.cn.anhetong.cn

www.shuituohb.com.tihujiu.cn

www.feiyou.com.cn.huatoutou.cn

www.jjsc.com.lvdate.cn

www.jinlihongtex.com.fuenbu.cn

www.tjspjt.com.namahu.cn

www.chinasthc.com.xuewenzi.cn

www.365tfood.com.baisuijie.cn

www.china-haixing.com.wanyuecun.cn

www.lnzssp.com.hetongmei.cn

www.ctctex.com.qianyiduo.cn

www.a-fontane.com.cn.hexiangru.cn

www.ztdrill.com.qiyuehong.cn

www.taoshipapers.com.ledatong.cn

www.zjjxjt.com.liubawan.cn

www.changyitex.com.kemensen.cn

www.ah3hjt.com.ximaguohe.cn

www.ltjaz.com.rehuang.cn

www.yijyl.com.liyintong.com

www.sctyyl.com.yawanmei.cn

www.tianshunjixie.com.biaolele.cn

www.seazon-tex.com.shenhebu.cn

www.hanmey.com.cn.itoren.cn

www.fjnfseed.com.iseebest.cn

www.sinochemsh.com.rustler.cn

www.027hyx.com.excelta.cn

www.sztp.com.diaolift.cn

www.vipoon.net.bxhqw.cn

www.tfmm.com.pudiweng.cn

www.bornyarn.com.tingbu.cn

www.c-textilep.com.ouhei.cn

www.jm-toyoink.com.zouliu.cn

www.zbnykj.com.zhaiti.cn

www.capitaleco-pro.com.wadiao.cn

www.trhbkj.com.hunjun.cn

www.novatexasia.com.lazai.cn

www.dpzy.net.suidun.cn

www.hkpinjian.com.tujiachen.cn

www.yiwu-food.com.anhetong.cn

www.3m.com.cn.tihujiu.cn

www.lyfh.com.huatoutou.cn

www.yafangtissue.com.xiaolaige.cn

www.jinguan.com.cn.lvdate.cn

www.xmeastocean.com.soubianlu.cn

www.deyitex.com.fuenbu.cn

www.raiseeptc.com.zouyizou.cn

www.htjx819.com.dadudu.cn

www.tsbenwu.com.lazhuyong.cn

www.bjyutao.com.aizishu.cn

www.chemchi.com.wanyuecun.cn

www.ahmyhb.com.hetongmei.cn

www.btndhb.com.mofaya.cn

www.xadyz.com.ledatong.cn

www.tmfj.com.ebuyun.cn

www.water-ky.com.gayijiu.cn

www.lbtyyl.com.liqinge.cn

www.yonglibelt.com.hexiaolia.cn

www.jsqitai.com.yunyuewei.cn

www.comfast.cn.kemensen.cn

www.tceptech.com.ximaguohe.cn

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3084668/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2024-08-07

  • 博文量
    589
  • 访问量
    602807