웹링크 10초마다 한번씩 체크해서 새 게시물 등록되면 이메일로 알림해주는 코드야. 



import requests

from bs4 import BeautifulSoup

import time

import smtplib

from email.mime.text import MIMEText

import winsound

import logging


# Configure logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


# URLs to monitor

urls = [

    "https://www.sejong.go.kr/prog/contractBid/contract/sub02_01/list.do",

    "https://www.alio.go.kr/occasional/bidList.do",

    "https://gall.dcinside.com/mgallery/board/lists?id=thesingularity",

    "https://stackoverflow.com/questions",

]


# Email configuration

smtp_server = "smtp.office365.com"

smtp_port = 587

email_address = "이메일@outlook.com"

email_password = "비번"

email_addressto = "이메일@gmail.com"


# Initialize last post IDs

last_post_ids = {}


def print_status():

    logging.info("Program is still running...")


def check_new_post(url, soup):

    try:

        if "sejong.go.kr" in url:

            # Extract the post ID from the table cell with class "subject bold" and data-cell-header="공고명"

            first_post = soup.select_one('td.subject.bold[data-cell-header="공고명"]')

            if first_post:

                post_id = first_post.text.strip()

                logging.info(f"Extracted post ID {post_id} for URL {url}")

                return post_id

        elif "alio.go.kr" in url:

            first_post = soup.select_one("div.bidList ul li:first-child a")

            if first_post:

                post_id = first_post["href"]

                logging.info(f"Extracted post ID {post_id} for URL {url}")

                return post_id

        elif "gall.dcinside.com" in url:

            # Extract the post ID from the table cell with class "gall_tit ub-word"

            first_post = soup.select_one('td.gall_tit.ub-word a')

            if first_post:

                post_id = first_post["href"]

                logging.info(f"Extracted post ID {post_id} for URL {url}")

                return post_id

        elif "stackoverflow.com" in url:

            first_post = soup.select_one("div.question-summary a.question-hyperlink")

            if first_post:

                post_id = first_post["href"]

                logging.info(f"Extracted post ID {post_id} for URL {url}")

                return post_id

    except Exception as e:

        logging.error(f"Error checking new post for URL {url}: {e}")

    return None




while True:

    for url in urls:

        try:

            response = requests.get(url)

            response.raise_for_status()

            soup = BeautifulSoup(response.text, "html.parser")

            post_id = check_new_post(url, soup)


            if post_id:

                logging.info(f"Detected post ID {post_id} for URL {url}")

                if url not in last_post_ids or last_post_ids[url] != post_id:

                    last_post_ids[url] = post_id

                    msg = MIMEText(f"New post detected. URL: {url}, Post ID: {post_id}")

                    msg["Subject"] = "New Post Alert"

                    msg["From"] = email_address

                    msg["To"] = email_addressto


                    with smtplib.SMTP(smtp_server, smtp_port) as server:

                        server.starttls()

                        server.login(email_address, email_password)

                        server.send_message(msg)


                    winsound.PlaySound("SystemHand", winsound.SND_ALIAS)

                    logging.info(f"Email sent for new post ID {post_id} on URL {url}")

            else:

                logging.info(f"No new post detected for URL {url}")


        except requests.RequestException as e:

            logging.error(f"Network error while accessing URL {url}: {e}")

        except Exception as e:

            logging.error(f"Unexpected error: {e}")


    time.sleep(10)  # Check interval of 10 seconds

    print_status()