[과제 알림이] selenium 크롤링

overwell24·2024년 3월 6일

과제 알림이

목록 보기
1/6
post-thumbnail

셀레니움 버전별 사용 방법 정리

셀레니움 버전별 사용방법이 달라 초반에 고생을 겪어서 버전별 사용법을 정리 해봤다.

셀레니움 3

driver.find_element_by_class_name("")
driver.find_element_by_id("")
driver.find_element_by_css_selector("")
driver.find_element_by_name("")
driver.find_element_by_tag_name("")
driver.find_element_by_xpath("")
driver.find_element_by_link_text("")
driver.find_element_by_partial_link_text("")
# 복수형 find_elements_by

설레니움 4

driver.find_element(By.CLASS_NAME, "")
driver.find_element(By.ID, "")
driver.find_element(By.CSS_SELECTOR, "")
driver.find_element(By.NAME, "")
driver.find_element(By.TAG_NAME, "")
driver.find_element(By.XPATH, "")
driver.find_element(By.LINK_TEXT, "")
driver.find_element(By.PARTIAL_LINK_TEXT, "")
# 복수형 find_elements

크롤링

크롤링 기능을 scraper.py로 분리하여 모듈화했다.
id/passwd와 같은 민감한 정보를 config.py로 모듈화 했다

config.py

# config.py
# 로그인 정보
class TodoConfig:
    user_id = ""
    user_pw = ""

scraper.py

# scraper.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
from bs4 import BeautifulSoup
from config import TodoConfig


class Scraper:

    def __init__(self) -> None:
        pass

    def get_todo_list(self):
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

        driver.get("https://cyber.inhatc.ac.kr/index.jsp")

        # 팝업 창 처리
        main = driver.window_handles
        for i in main:
            if i != main[0]:
                driver.switch_to.window(i)
                driver.close()
        driver.switch_to.window(main[0])

        # frame 이동으로 NoSuchElementException 오류 해결
        driver.switch_to.frame(driver.find_element(
            By.XPATH, "/html/frameset/frame"))
        # driver.find_element(By.XPATH, '//*[@id="imagePop"]/div[1]/div[1]/a[1]').click()
        driver.execute_script('setImgCookie()')

        # 아이디와 비밀번호
        user_id = TodoConfig.user_id
        user_passwd = TodoConfig.user_pw

        # 아이디 입력란 찾기 및 입력
        id_input = driver.find_element(By.XPATH, '//*[@id="id"]')
        id_input.clear()
        id_input.send_keys(user_id)

        # 비번 입력란 찾기 및 입력
        pw_input = driver.find_element(By.XPATH, '//*[@id="pw"]')
        pw_input.clear()
        pw_input.send_keys(user_passwd)

        login_button = driver.find_element(
            By.XPATH, '//*[@id="loginForm"]/fieldset/p/a')
        login_button.click()

        # 할일 목록 요청
        driver.execute_script('viewTodayList()')
        time.sleep(2)

        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')

        li_list = soup.find_all(
            'li', {'style': 'float: none; list-style: none; position: relative; width: 220px;'})

        data = []
        sorted_data = {}
        todo_lsit = ""

        for li in li_list:
            text = li.get_text(strip=True, separator='    ')
            data = text.split("    ")

            # 첫 번째 요소를 기준으로 그룹화
            deadline = "[" + data[1].strip() + "]"
            if deadline not in sorted_data:
                sorted_data[deadline] = []

            data[3] = ' '.join(data[3].split(" ")[1:])
            del data[2]
            del data[1]
            sorted_data[deadline].append(data)

        # 결과 출력
        for key, value in sorted_data.items():
            key += "\n"
            todo_lsit += key

            value_string = "\n".join([" ".join(item) for item in value])
            value_string += "\n"
            todo_lsit += value_string

        todo_lsit = todo_lsit.rstrip('\n')
        return todo_lsit

0개의 댓글