-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
파이썬 코루틴 사용하기 - aiohttp로 crawling시에 ssl error 발생
22.10.06 01:50 작성 조회수 1.68k
4
질문은 아니고, 에러가 발생하는 부분이 있어 나중에 문제를 겪고 있으신 분들에게 도움이 될 것 같아 남깁니다.
위 링크에 있는 코드 입니다.
# 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