[python] aiohttp를 사용하여 비동기적으로 웹 크롤러 결과를 이메일로 전송하기

이번 글에서는 Python의 aiohttp 라이브러리를 사용하여 비동기적으로 웹 크롤러 결과를 이메일로 전송하는 방법을 알아보겠습니다.

목차

aiohttp란?

aiohttp는 Python에서 비동기적인 HTTP 요청을 처리하기 위한 라이브러리입니다. 이 라이브러리를 사용하면 비동기적으로 웹 서버에 요청을 보내고 응답을 처리할 수 있습니다. 비동기적인 요청을 사용하면 다수의 요청을 동시에 처리할 수 있어 성능 향상을 이룰 수 있습니다.

이메일 보내기

이메일을 전송하기 위해서는 smtplib 라이브러리를 사용할 수 있습니다. 이 라이브러리를 통해 SMTP 서버에 접속하여 이메일을 전송할 수 있습니다.

import smtplib

def send_email(subject, body, email_to):
    email_from = "your_email@example.com"
    smtp_server = "smtp.example.com"
    smtp_port = 587
    smtp_username = "your_username"
    smtp_password = "your_password"
    
    msg = f"Subject: {subject}\n\n{body}"
    
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.sendmail(email_from, email_to, msg)
    server.quit()

이 함수를 사용하면 주어진 제목과 내용으로 이메일을 보낼 수 있습니다.

웹 크롤러 구현하기

이제 aiohttp를 사용하여 웹 크롤러를 구현해 보겠습니다. 아래는 간단한 예제 코드입니다.

import aiohttp
import asyncio

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

async def main():
    urls = [
        "https://www.example.com/page1",
        "https://www.example.com/page2",
        "https://www.example.com/page3"
    ]

    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            task = asyncio.ensure_future(fetch(session, url))
            tasks.append(task)

        responses = await asyncio.gather(*tasks)
        for response in responses:
            # 웹 크롤링 결과 처리
            print(response)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

이 예제 코드는 세 개의 URL에서 동시에 요청을 보내고 응답을 받은 후에 결과를 출력합니다.

결과 이메일로 전송하기

지금까지 구현한 웹 크롤러의 결과를 이메일로 전송해보겠습니다. 아래 코드를 main 함수에 추가합니다.

    # 웹 크롤링 결과 처리
    for response in responses:
        # 이메일 전송
        subject = "웹 크롤링 결과"
        body = response
        email_to = "recipient@example.com"

        send_email(subject, body, email_to)

위 코드를 추가하면 웹 크롤링 결과를 이메일로 전송합니다. 제목, 내용, 수신자 이메일 주소는 필요에 맞게 수정해야 합니다.

결론

Python의 aiohttp 라이브러리를 사용하여 비동기적으로 웹 크롤러를 구현하고, smtplib 라이브러리를 사용하여 이메일로 결과를 전송하는 방법을 알아보았습니다. 이를 응용하면 다양한 웹 크롤링 및 데이터 처리 작업에서 비동기적으로 작업을 수행하고 결과를 효율적으로 전송할 수 있습니다.

참고: aiohttp 공식 문서