IT/Python

[Python] 쇼핑몰 이미지 크롤링

잿호 2023. 9. 14. 20:06

- 이미지 크롤링 -

 

설계

1. 웹사이트의 이미지를 크롤링한다.

2. 이미지는 dongwon 폴더를 생성하여 저장한다.

3. 이미지 파일의 이름은 이미지 저장 주소의 마지막 값으로 저장된다.

 


코드

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import urllib.request
import os
driver = webdriver.Chrome()

url = 'https://www.dongwonmall.com/index.do'
driver.get(url)
time.sleep(3)

driver.find_element(By.XPATH,'//*[@id="searchTermTop"]').send_keys('선물세트')
driver.find_element(By.XPATH,'//*[@id="searchTermTop"]').send_keys(Keys.ENTER)
time.sleep(3)
list_count = len(driver.find_elements(By.XPATH,'//*[@id="productlist"]/ul/li'))
# print(list_count)
prod_list = []
for i in range(1, list_count+1):
    img_path = driver.find_element(By.XPATH, '//*[@id="productlist"]/ul/li['+str(i)+']/div[1]/a/span[1]/img').get_attribute('src')
    if not os.path.exists('dongwon'):
        os.mkdir('dongwon')
    file_path = img_path.split('/')
    file_name = file_path[len(file_path)-1]
    urllib.request.urlretrieve(img_path, 'dongwon/'+file_name)
    title = driver.find_element(By.XPATH,'//*[@id="productlist"]/ul/li['+str(i)+']/div[1]/a/span[3]/strong').text                                  
    items = driver.find_element(By.XPATH,'//*[@id="productlist"]/ul/li['+str(i)+']/div[1]/a/span[3]/span').text
    try:
        sale_pct = driver.find_element(By.XPATH,'//*[@id="productlist"]/ul/li['+str(i)+']/div[2]/div[2]/span[3]/em').text
    except:
        sale_pct = '0%'
    price = driver.find_element(By.XPATH,'//*[@id="productlist"]/ul/li['+str(i)+']/div[2]/div[2]/span[2]/span/em').text    
    sale_pct = float(sale_pct.replace('%', ''))/100
    price = int(price.replace(',',''))
    print(title, items, sale_pct, price)
    prod_list.append([title, items, sale_pct, price, img_path])
    
print('저장 완료')

 

 


실행

 

01234
- 실행 과정 -

 

 


마무리

동원참치 광고 아닙니다

 

 

반응형

'IT > Python' 카테고리의 다른 글

[Python] 틱택토 게임 (Tic-Tac-Toe)  (44) 2023.09.17
[Python] 포커 족보 검색기  (47) 2023.09.15
[Python] 대통령 연설문 크롤링  (0) 2023.09.13
[Python] 사람인 취업공고 엑셀정리  (31) 2023.09.11
[Python] 바이오리듬  (30) 2023.09.10