11번가 크롤링
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(options=chrome_options)
--headless 모드는 브라우저를 눈에 보이지 않게 실행합니다. 즉, 백그라운드에서만 작동해 사람이 보는 브라우저 창이 뜨지 않습니다.결론: 프로그램이 직접 브라우저를 실행하고, 사람 대신 웹사이트에서 정보를 가져오도록 준비하는 단계입니다.
driver.get('https://www.11st.co.kr/browsing/BestSeller.tmall?method=getBestSellerMain&xfrom=main^gnb')
driver.get(URL)은 브라우저를 해당 URL로 이동시키는 명령입니다.결론: Selenium이 브라우저를 열고, 우리가 크롤링하고 싶은 웹페이지에 도착하게 합니다.
SCROLL_PAUSE_SEC = 1
last_height = driver.execute_script('return document.body.scrollHeight')
while True:
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(SCROLL_PAUSE_SEC)
new_height = driver.execute_script('return document.body.scrollHeight')
if new_height == last_height:
break
last_height = new_height
driver.execute_script('window.scrollTo(...)'): 스크롤을 아래로 내립니다.time.sleep(SCROLL_PAUSE_SEC): 데이터를 로드할 시간을 줍니다.결론: 페이지에 보이지 않는 상품 데이터를 불러오기 위해 "스크롤 다운" 과정을 추가한 겁니다.
lists = driver.find_element(By.ID, 'bestPrdList').find_element(By.CLASS_NAME, 'viewtype')
bestlist = lists.find_elements(By.TAG_NAME, 'li')
for item in bestlist:
rank = item.find_element(By.CLASS_NAME, 'best').text
product_name = item.find_element(By.CLASS_NAME, 'pname').find_element(By.TAG_NAME, 'p').text
price = item.find_element(By.CLASS_NAME, 'sale_price').text
product_url = item.find_element(By.CLASS_NAME, 'box_pd.ranking_pd').find_element(By.TAG_NAME, 'a').get_attribute('href')
image_url = item.find_element(By.CLASS_NAME, 'img_plot').find_element(By.TAG_NAME, 'img').get_attribute('src')
<li> 태그로 나열되어 있습니다.find_element(By.ID, ...)는 특정 ID를 가진 HTML 요소를 찾습니다.find_elements(By.TAG_NAME, ...)는 다수의 태그를 리스트로 가져옵니다..text는 HTML 요소 안의 텍스트 데이터를 가져옵니다..get_attribute('href')나 .get_attribute('src')는 링크(URL) 같은 속성 값을 가져옵니다.결론: 상품 이름, 가격, 순위, 이미지 등 필요한 데이터를 하나씩 뽑아오기 위한 작업입니다.
all_data.append({
"Rank": rank,
"Product Name": product_name,
"Price": price,
"Product URL": product_url,
"Image URL": image_url
})
Rank: 순위Product Name: 상품명Price: 가격Product URL: 상품 링크Image URL: 이미지 링크all_data)에 추가합니다.결론: 수집한 정보를 정리해서 나중에 활용하기 쉽게 저장합니다.
df = pd.DataFrame(all_data)
df.to_csv('./11st_best_sellers.csv', index=False, encoding='utf-8')
pandas)의 데이터프레임은 행/열로 데이터를 다루기 쉽게 만들어줍니다.결론: 데이터를 구조화하고 파일로 저장해 나중에 분석하거나 확인할 수 있도록 합니다.