파이썬 다나와 크롤링 제품 정보 모으기

반응형

파이썬 스크립트로 다나와 크롤링 하여 제품 정보를 모아보도록 하겠습니다. 파이썬 스크립트를 쓰고 스트림릿으로 올려서 쉽게 웹페이지에서 조회를 하면 쉽게 페이지 정보를 모을 수 있습니다.

 

[주의] 해당 스크립트는 공부를 위한 학습 목적이므로 불법으로 사이트 정보를 모으거나 이용하는 행위는 불법 행동이 될 수 있습니다.

 

파이썬 다나와 크롤링 제품 정보 모으기

파이썬 다나와 크롤링 제품 정보 모으기

이 스크립트는 Streamlit을 이용해 웹페이지를 통해 제품 정보를 검색하고, 결과를 크롤링하여 보여주는 애플리케이션을 구현한 것입니다. 스크립트의 주요 동작은 아래와 같습니다:

 

1. 필요한 모듈 임포트

import streamlit as st
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import time

 

Streamlit: 웹 애플리케이션을 쉽게 만들 수 있는 프레임워크.

requests: 웹페이지에 HTTP 요청을 보내는 라이브러리.

BeautifulSoup: HTML 및 XML 데이터를 파싱하는 라이브러리.

pandas: 데이터 처리 및 분석을 위한 라이브러리.

re, time: 정규 표현식과 시간 관련 모듈.

 

2. get_page_content() 함수

def get_page_content(search_query, page_num):
    url = f"https://search.danawa.com/dsearch.php?query={search_query}&page={page_num}"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    return BeautifulSoup(response.content, 'html.parser')

 

URL 생성: 검색어와 페이지 번호를 기반으로 danawa.com의 검색 결과 페이지 URL을 생성합니다.

HTTP 요청: requests를 이용해 해당 페이지의 HTML을 요청합니다.

BeautifulSoup 파싱: 받은 HTML을 BeautifulSoup 객체로 변환하여 HTML 구조를 쉽게 탐색할 수 있도록 합니다.

 

 

3. crawl_product_info() 함수

def crawl_product_info(search_query):
    product_list = []
    # 페이지 수 자동 계산
    soup = get_page_content(search_query, 1)
    max_pages = int(soup.select_one('div.paging_number_wrap').find_all('a')[-1]['data-page'])

 

페이지 수 자동 계산: 첫 페이지를 가져와서 페이지네이션 정보를 확인하고, 최대 페이지 수를 계산합니다.

    # 각 페이지에서 제품 정보 크롤링
    for page_num in range(1, max_pages + 1):
        st.session_state.progress_bar.progress(page_num / max_pages)  # 진행률 표시
        soup = get_page_content(search_query, page_num)
        products = soup.select('li.prod_item')

진행률 표시: 각 페이지를 크롤링할 때마다 진행률 바를 업데이트합니다.

제품 정보 탐색: 각 페이지에서 li.prod_item 요소를 찾아서 제품 목록을 가져옵니다.

 

        for product in products:
            try:
                # 업체명과 제품명 가져오기
                name_tag = product.select_one('p.prod_name a')
                full_name = name_tag.text.strip() if name_tag else '정보 없음'
                업체명 = full_name.split()[0]  # 공백 전까지 업체명 추출
                제품명 = ' '.join(full_name.split()[1:])  # 첫 공백 이후 제품명 추출

 

업체명과 제품명: p.prod_name에서 제품명을 추출하고, 첫 단어는 업체명으로, 나머지는 제품명으로 저장합니다.

                # 가격, 이미지, 링크, 추가 정보 등 가져오기
                price_tag = product.select_one('p.price_sect a strong')
                가격 = price_tag.text.strip() if price_tag else '정보 없음'

                img_tag = product.select_one('div.thumb_image a img')
                이미지_URL = img_tag['src'] if img_tag else '정보 없음'

                link_tag = product.select_one('div.thumb_image a')
                링크 = link_tag['href'] if link_tag else '정보 없음'

                추가정보_tag = product.select_one('div.spec_list')
                추가정보 = 추가정보_tag.text.strip() if 추가정보_tag else '정보 없음'

                등록월_tag = product.select_one('div.prod_sub_meta dl.meta_item.mt_date dd')
                등록월 = 등록월_tag.text.strip() if 등록월_tag else '정보 없음'

                평점_tag = product.select_one('div.star-single span.text__score')
                평점 = 평점_tag.text.strip() if 평점_tag else '정보 없음'

                리뷰수_tag = product.select_one('div.text__review span.text__number')
                리뷰수 = 리뷰수_tag.text.strip() if 리뷰수_tag else '정보 없음'

가격, 이미지, 링크: 각 요소에서 제품의 가격, 이미지 URL, 구매 링크를 가져옵니다.

추가 정보, 등록월, 평점, 리뷰수: 제품의 부가 정보, 등록 월, 사용자 평점, 리뷰 수를 추출합니다.

아래 스크립트는 전체 스크립트입니다. 

import streamlit as st
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import time

# 페이지 컨텐츠를 받아오는 함수
def get_page_content(search_query, page_num):
    url = f"https://search.danawa.com/dsearch.php?query={search_query}&page={page_num}"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    return BeautifulSoup(response.content, 'html.parser')

# 제품 정보 크롤링 함수
def crawl_product_info(search_query):
    product_list = []
    # 페이지 수 자동 계산
    soup = get_page_content(search_query, 1)
    max_pages = int(soup.select_one('div.paging_number_wrap').find_all('a')[-1]['data-page'])

    # 각 페이지에서 제품 정보 크롤링
    for page_num in range(1, max_pages + 1):
        st.session_state.progress_bar.progress(page_num / max_pages)  # 진행률 표시
        soup = get_page_content(search_query, page_num)
        products = soup.select('li.prod_item')

        for product in products:
            try:
                # 업체명과 제품명 가져오기
                name_tag = product.select_one('p.prod_name a')
                full_name = name_tag.text.strip() if name_tag else '정보 없음'
                업체명 = full_name.split()[0]  # 공백 전까지 업체명 추출
                제품명 = ' '.join(full_name.split()[1:])  # 첫 공백 이후 제품명 추출

                # 가격 가져오기
                price_tag = product.select_one('p.price_sect a strong')
                가격 = price_tag.text.strip() if price_tag else '정보 없음'

                # 이미지 URL 가져오기
                img_tag = product.select_one('div.thumb_image a img')
                이미지_URL = img_tag['src'] if img_tag else '정보 없음'

                # 링크 가져오기
                link_tag = product.select_one('div.thumb_image a')
                링크 = link_tag['href'] if link_tag else '정보 없음'

                # 추가 정보 가져오기
                추가정보_tag = product.select_one('div.spec_list')
                추가정보 = 추가정보_tag.text.strip() if 추가정보_tag else '정보 없음'

                # 등록월 가져오기
                등록월_tag = product.select_one('div.prod_sub_meta dl.meta_item.mt_date dd')
                등록월 = 등록월_tag.text.strip() if 등록월_tag else '정보 없음'

                # 평점 가져오기
                평점_tag = product.select_one('div.star-single span.text__score')
                평점 = 평점_tag.text.strip() if 평점_tag else '정보 없음'

                # 리뷰 수 가져오기
                리뷰수_tag = product.select_one('div.text__review span.text__number')
                리뷰수 = 리뷰수_tag.text.strip() if 리뷰수_tag else '정보 없음'

                # 데이터 저장
                product_list.append({
                    '업체명': 업체명,
                    '제품명': 제품명,
                    '추가정보': 추가정보,
                    '가격': 가격,
                    '이미지': 이미지_URL,
                    '링크': 링크,
                    '평점': 평점,
                    '리뷰수': 리뷰수,
                    '등록월': 등록월
                })

            except Exception as e:
                print(f"Error processing product: {e}")

    return product_list

# Streamlit 애플리케이션 설정
st.set_page_config(layout="wide")

# 왼쪽 옵션 패널 만들기
with st.sidebar:
    st.title("검색 옵션")
    search_query = st.text_input("검색어 입력", "노트북")
    search_button = st.button("검색")
    # 진행률 바 초기화
    if 'progress_bar' not in st.session_state:
        st.session_state.progress_bar = st.progress(0)

# 검색 버튼이 눌렸을 때
if search_button:
    st.write(f"'{search_query}' 검색 결과:")
    
    # 크롤링 시작
    product_list = crawl_product_info(search_query)
    
    # 결과를 데이터프레임으로 변환 후 출력
    df = pd.DataFrame(product_list)
    st.dataframe(df)

    # CSV 파일 다운로드 버튼
    csv = df.to_csv(index=False, encoding='utf-8-sig')
    st.download_button(
        label="CSV 다운로드",
        data=csv,
        file_name=f'{search_query}_검색결과.csv',
        mime='text/csv'
    )

 

파이썬 다나와 크롤링 제품 정보 모으기 - 스트림릿

이 스크립트는 Streamlit을 이용해 웹페이지를 통해 제품 정보를 검색하고, 결과를 크롤링하여 보여주는 애플리케이션을 위해 코드를 업로드 합니다. 아래 코드도 공유 드릴게요

미확인 478311.crdownload
0.00MB

 

반응형

blue