강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

JH님의 프로필 이미지
JH

작성한 질문수

네이버 스마트스토어 상품 정보 크롤링 질문입니다.

작성

·

519

0

import os
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from openpyxl import Workbook
import time

# 크롬 옵션 설정
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--incognito')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36')
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--ignore-ssl-errors')

# WebDriver 설정
service = Service(executable_path="C:/Users/User/Desktop/python/chromedriver.exe")
driver = webdriver.Chrome(service=service, options=chrome_options)

# 엑셀 파일 생성 및 시트 설정
wb = Workbook()
ws = wb.active
ws.title = "상품정보"
ws.append(['브랜드명', '상품명', '정가', '판매가', '상품 링크', '이미지 링크'])

# AHC 브랜드스토어 페이지로 이동
driver.get("https://brand.naver.com/ahcshop/best?cp=1")
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'li')))  # 페이지 로딩 대기

# HTML 파싱
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

# 상품 정보 추출
products = soup.select('li')

for product in products:
    try:
        # 브랜드명
        brand = "AHC"
        
        # 상품명
        name = product.select_one('div.PI9k_4E2vZ > strong.ViNuD_2kZl').text if product.select_one('div.PI9k_4E2vZ > strong.ViNuD_2kZl') else 'N/A'
        
        # 정가
        original_price = product.select_one('del > span.LGJCRfhDKi').text if product.select_one('del > span.LGJCRfhDKi') else 'N/A'

        # 판매가
        sale_price = product.select_one('strong > span.LGJCRfhDKi').text if product.select_one('strong > span.LGJCRfhDKi') else 'N/A'

        # 상품 링크
        product_link = "https://brand.naver.com" + product.select_one('a')['href'] if product.select_one('a') else 'N/A'

        # 이미지 링크
        image_link = product.select_one('div > img')['src'] if product.select_one('div > img') else 'N/A'

        # 엑셀에 추가
        ws.append([brand, name, original_price, sale_price, product_link, image_link])

    except Exception as e:
        print(f"오류 발생: {e}")

# WebDriver 종료
driver.quit()

# 엑셀 저장 경로
excel_file_path = os.path.join(os.path.dirname(__file__), "네이버_상품목록.xlsx")
wb.save(excel_file_path)
wb.close()

# 결과 및 로그 저장
log_file_path = os.path.join(os.path.dirname(__file__), f"scraping_log_{time.strftime('%Y%m%d_%H%M%S')}.txt")
with open(log_file_path, 'w', encoding='utf-8') as log_file:
    log_file.write(f"스크래핑 완료: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
    log_file.write(f"엑셀 파일 저장 위치: {excel_file_path}\n")

print(f"엑셀 파일 저장 완료: {excel_file_path}")
print(f"로그 파일 저장 완료: {log_file_path}")

 

이 코드를 통해 AHC 브랜드 스마트스토어 베스트 페이지에 있는 상품 정보들을 가져오려고하는데요

크롬드라이버 통해 실행하면서 해보려고하니까 차단되버리고 백그라운드 작업으로 하려다보니까 데이터를 못가져오는데 어떻게 해야될지 모르겠습니다 도와주세요 ㅠㅠ

답변

답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!
JH님의 프로필 이미지
JH

작성한 질문수

질문하기