뽐뿌 핫딜 데이터 크롤링/ csv파일 뽑기 코드 리뷰

2024. 2. 1. 17:54Data Science/Study 자료

사용된 라이브러리

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import pandas as pd
import time
import random

상세 코드

def page1_crawling(driver):
    titles = []
    urls = []
    start_num = 9
    end_num = 47
    for i in range(start_num, end_num + 1, 2):
        title_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font'
        titles.append(driver.find_element(By.CSS_SELECTOR, title_css_path).text)
        
        url_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a'
        urls.append(driver.find_element(By.CSS_SELECTOR, url_css_path).get_attribute('href'))

    return pd.DataFrame({"title": titles, "urls": urls})

def other_crawling(driver):
    titles = []
    urls = []
    start_num = 6
    end_num = 44
    #revolution_main_table > tbody > tr:nth-child(6) > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font
    #revolution_main_table > tbody > tr:nth-child(8) > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font
    #revolution_main_table > tbody > tr:nth-child(44) > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font
    for i in range(start_num, end_num + 1, 2):
        title_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font'
        titles.append(driver.find_element(By.CSS_SELECTOR, title_css_path).text)
        
        url_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a'
        urls.append(driver.find_element(By.CSS_SELECTOR, url_css_path).get_attribute('href'))

    return pd.DataFrame({"title": titles, "urls": urls})

def main():
    driver = webdriver.Chrome(service= Service(ChromeDriverManager().install()))
    URL='https://www.nate.com/?f=bi'
    driver.get(url=URL)

    URL = 'https://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu&page=1&divpage=85'
    driver.get(url=URL)
    df = page1_crawling(driver)
    for i in range(2, 10):
        URL = 'https://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu&page='+ str(i) + '&divpage=85'
        print(URL)
        driver.get(url=URL)
        df = pd.concat([df, other_crawling(driver)], ignore_index=True)
        time.sleep(random.uniform(2, 5))   # 2 ~ 5초 무작위로 설정
        
    df.to_csv("핫딜.csv", index=False)
    driver.quit()
    
if __name__ == "__main__":
    main()​

리뷰

1페이지 함수

def page1_crawling(driver):
    titles = []
    urls = []
    start_num = 9 # 1페이지의 첫번째 게시물의 tr:nth-child 이 9부터 시작함
    end_num = 47 # 마지막게시물까지 홀수로 2씩증가 하면서 tr:nth-child번호가 바뀜 
    
    #위 규칙을 반복문을 통해 구현
    
    for i in range(start_num, end_num + 1, 2):
        # CSS 선택자를 사용하여 제목 요소 식별
        title_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font'
        
        #해당 게시글 제목
        titles.append(driver.find_element(By.CSS_SELECTOR, title_css_path).text)
        #Selenium을 사용하여 웹 페이지에서 특정 CSS 선택자를 사용하여 요소를 찾고
        #해당 요소의 텍스트 값을 추출하여 리스트에 추가하는 코드


        # CSS 선택자를 사용하여 URL 요소 식별
        #해당 게시글 링크
        url_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a'
        urls.append(driver.find_element(By.CSS_SELECTOR, url_css_path).get_attribute('href'))

    return pd.DataFrame({"title": titles, "urls": urls})
    #데이터 프레임으로 리턴

 

나머지 페이지 함수 

def other_crawling(driver):
    titles = []
    urls = []
    start_num = 6 # 2페이지부터는 6으로 시작 
    end_num = 44 #마지막 게시물 44로 끝남 
    
    #아래 내용은 위코드와 동일한 구조
    for i in range(start_num, end_num + 1, 2):
        # CSS 선택자를 사용하여 제목 요소 식별
        title_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a > font'
        titles.append(driver.find_element(By.CSS_SELECTOR, title_css_path).text)
        
        # CSS 선택자를 사용하여 URL 요소 식별
        url_css_path = '#revolution_main_table > tbody > tr:nth-child(' + str(i) + ') > td:nth-child(3) > table > tbody > tr > td:nth-child(2) > div > a'
        urls.append(driver.find_element(By.CSS_SELECTOR, url_css_path).get_attribute('href'))

    return pd.DataFrame({"title": titles, "urls": urls})
def main():
    # ChromeDriverManager를 사용하여 Chrome 브라우저 실행
    driver = webdriver.Chrome(service= Service(ChromeDriverManager().install()))

    #  뽐뿌 첫페이지 크롤링
    URL = 'https://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu&page=1&divpage=85'
    driver.get(url=URL)
    df = page1_crawling(driver)

    # 나머지 페이지 크롤링
    for i in range(2, 10):
        URL = 'https://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu&page='+ str(i) + '&divpage=85'
        print(URL)
        driver.get(url=URL)
        df = pd.concat([df, other_crawling(driver)], ignore_index=True)
        time.sleep(random.uniform(2, 5))   # 2 ~ 5초 무작위로 설정
        
    # DataFrame을 CSV 파일로 저장
    df.to_csv("핫딜.csv", index=False)
    driver.quit()

if __name__ == "__main__":
    main()