• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

파이썬 코루틴 사용하기 - aiohttp로 crawling시에 ssl error 발생

22.10.06 01:50 작성 조회수 1.68k

4

질문은 아니고, 에러가 발생하는 부분이 있어 나중에 문제를 겪고 있으신 분들에게 도움이 될 것 같아 남깁니다.

https://github.com/amamov/teaching-async-python/blob/main/1-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%BD%94%EB%A3%A8%ED%8B%B4%EA%B3%BC-%EB%B9%84%EB%8F%99%EA%B8%B0-%ED%95%A8%EC%88%98/04-2-coroutine-fetcher.py

위 링크에 있는 코드 입니다.

 # https://docs.aiohttp.org/en/stable/
# pip install aiohttp~=3.7.3


import aiohttp
import time
import asyncio


async def fetcher(session, url):
    async with session.get(url) as response:
        return await response.text()


async def main():
    urls = ["https://naver.com", "https://google.com", "https://instagram.com"] * 10

    async with aiohttp.ClientSession() as session:
        result = await asyncio.gather(*[fetcher(session, url) for url in urls])
        print(result)


if __name__ == "__main__":
    start = time.time()
    asyncio.run(main())
    end = time.time()
    print(end - start)  # 4.8

해당 코드 실행 시 다음의 ssl 에러가 발생합니다. 왜 그런지는 모르겠지만, requests에서는 ssl 에러가 발생하지 않는데 aiohttp에서는 발생합니다.

[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]

https://github.com/aio-libs/aiohttp/issues/955

에서 확인한 방법을 적용하면 쉽게 해결이 가능합니다.

 

ssl 검증 과정을 코드 상에서 false 처리하면 됩니다.

async with aiohttp.ClientSession(
        connector=aiohttp.TCPConnector(ssl=False)
    ) as session:

 

전체코드는 다음과 같습니다.

import aiohttp
import time
import asyncio


async def fetcher(session, url):
    async with session.get(url) as response:
        return await response.text()


async def main():
    urls = ["https://naver.com", "https://google.com", "https://instagram.com"] * 10

    async with aiohttp.ClientSession(
        connector=aiohttp.TCPConnector(ssl=False)
    ) as session:
        result = await asyncio.gather(*[fetcher(session, url) for url in urls])
        print(result)


if __name__ == "__main__":
    start = time.time()
    asyncio.run(main())
    end = time.time()
    print(end - start)

 

답변 2

·

답변을 작성해보세요.

0

정민신님의 프로필

정민신

2023.02.15

좋은 글 감사합니다! 덕분에 해결했습니당 ^-^

0

윤서준님의 프로필

윤서준

2022.10.31

정보 공유 감사합니다 :)