이번 포스트에서는 aiohttp
라이브러리를 사용하여 비동기적으로 웹 크롤러 결과를 수집하고, MongoDB에 저장하는 방법에 대해 알아보겠습니다.
목차
aiohttp란?
aiohttp
는 Python에서 비동기 웹 요청을 처리하기 위한 라이브러리입니다. 이 라이브러리를 사용하면 비동기적으로 여러 웹 요청을 처리할 수 있으며, 크롤링과 같은 작업에 특히 유용합니다.
MongoDB란?
MongoDB
는 문서 지향적 NoSQL 데이터베이스로, JSON 형식으로 데이터를 저장하고 처리할 수 있습니다. 비정형 데이터의 처리에 용이하며, 대규모 데이터 처리에 뛰어난 성능을 보여줍니다.
aiohttp를 통한 비동기 웹 크롤링
먼저 aiohttp
패키지를 설치합니다.
pip install aiohttp
이제 aiohttp
를 사용하여 웹 페이지를 비동기적으로 요청하는 예제 코드를 작성해보겠습니다.
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'https://www.example.com')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
fetch
함수는 웹 요청을 수행하고, main
함수는 비동기적으로 웹 요청을 처리하고 결과를 출력합니다.
Asyncio와 함께 사용하기
aiohttp
를 사용하려면 asyncio
와 함께 사용해야 합니다. asyncio
는 비동기 프로그래밍을 위한 라이브러리로, 이벤트 루프를 통해 비동기 작업을 관리합니다.
결과를 MongoDB에 저장하기
이제 크롤링한 결과를 MongoDB에 저장하는 방법을 알아보겠습니다. 먼저 pymongo
패키지를 설치합니다.
pip install pymongo
다음으로, MongoDB에 연결 및 데이터 삽입을 위한 코드를 작성합니다.
import aiohttp
import asyncio
from pymongo import MongoClient
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def save_to_mongodb(html):
client = MongoClient('mongodb://localhost:27017/')
db = client['example_db']
collection = db['pages']
document = {'html': html}
collection.insert_one(document)
print('Saved to MongoDB')
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'https://www.example.com')
await save_to_mongodb(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
save_to_mongodb
함수에서는 pymongo
를 사용하여 MongoDB에 결과를 저장합니다. 이 예제에서는 example_db
라는 데이터베이스에 pages
라는 컬렉션에 저장하고 있습니다.
마치며
이제 aiohttp
를 사용하여 비동기적으로 웹 크롤러 결과를 수집하는 방법과, pymongo
를 사용하여 MongoDB에 저장하는 방법에 대해 알아보았습니다. 이를 활용하여 효율적인 데이터 처리를 할 수 있습니다.