python异步协程爬虫报错:【aiohttp.client_exceptions:ServerDisconnectedError:Server disconnected】的初步解决办法

文章讨论了在使用Python的aiohttp库进行异步HTTP请求时遇到的网络错误,如ClientOSError和ServerDisconnectedError。作者分析这些错误可能由于每个任务创建独立的session导致,并提出了优化方案——在主函数中创建单个ClientSession实例,复用session以减少资源消耗。这种方法提高了代码效率并减少了错误发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初始代码:

async def myRequest(data):
    url = data['url']
    header = data['header']
    country = data['country']
    category = data['category']
    async with aiohttp.ClientSession(headers = header) as session:
        async with await session.get(url = url) as resp:
            html = await resp.read()
            today = str(datetime.date.today())
            filePath = '%s.xlsx'%(category)
            absPath = os.path.join(dir, today, country, filePath)
            print(absPath, 3333)
            f = open(absPath, 'wb')
            f.write(html)
            f.close()

def main():
    tasks = []
	for url in urls:
		c= myRequest(requestDataList, headers)
		task = asyncio.ensure_future(c)
		tasks.append(task)
	loop = asyncio.get_event_loop()
	loop.run_until_complete(asyncio.wait(tasks))

if __name__ == '__main__':
	main()
async def download_page(url):
	async with aiohttp.ClientSession() as session:
		async with session.get(url) as resp:
			await result = resp.text()

async def main(urls):
	tasks = []	
	for url in urls:
		tasks.append(asyncio.create_task(download_page(url)))  # 我的python版本为3.9.6
	await asyncio.await(tasks)

if __name__ == '__main__':
	urls = [ url1, url2, …… ]
	asyncio.run(main(urls))

这是最基本的一个异步协程框架,在数据量不大的情况下,可以基本满足要求,但是,数据量稍大一些,就会把报错,我收集到的报错信息有以下几种:

  • aiohttp.client_exceptions.ClientOSError: [WinError 64] 指定的网络名不再可用。
    Task exception was never retrieved

  • aiohttp.client_exceptions.ClientOSError: [WinError 121] 信号灯超时时间已到
    Task exception was never retrieved

  • aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
    Task exception was never retrieved

解决思路:

上述报错比较大的问题是在于每一个任务都创建了一个session,当创建过多session时就会报错。

解决办法:

尝试只创建一个session

import asyncio
import aiohttp

async def download_page(url,session):
	async with session.get(url) as resp:
		result = await resp.content.read()
		print(result)

async def main(urls):
	tasks = []	
	async with aiohttp.ClientSession() as session:  # 将创建session,放在main函数中,同时,需要注意将session作为变量传入download_page函数中
		for url in urls:
			tasks.append(asyncio.create_task(download_page(url,session)))
			# 我的python版本为3.9.6,python版本3.8及以上,如果需要创建异步任务,需要通过asyncio.creat_task()创建,否则虽然可以正常运行,但是会出警告信息
		await asyncio.wait(tasks)

if __name__ == '__main__':
	urls = [ url1, url2, …… ]
	asyncio.run(main(urls))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西门一刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值