새소식

IT/Python

1일차 - 크롤링

  • -
728x90
반응형

프로젝트 진행 전에 우선 크롤링 하는 방법을 배우고 싶어서 오토코더 유튜브 보고 학습했다

🔗링크

 

진짜 자세하게 알려주셔서 좋다

 

 

라이브러리 불러오기

from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import NoSuchElementException
import time

# 엑셀로 추출
from openpyxl import Workbook

 

⭐ 사이트에 내가 로봇이 아님을 알려줘야 한다 

UserAgent = '구글에 UserAgent치면 현재 컴퓨터 정보 나옴' # 크롤링할 때 로봇이 아님을 알려줌
    options.add_argument('user-agent=' + UserAgent)

 

첫 번째 try 문 : 페이지를 순환하면서 끝 페이지까지 돔

for 문 : 제품 안에 태그를 판단

두 번째 try 문 : 제품에 해당하는 정보가 있는지 확인 함

# 크롤링
    driver.get(url='https://www.coupang.com/np/categories/194276?page=' + str(i))
    time.sleep(5)
    try: # 페이지의 순환
        product = driver.find_element(By.ID, 'productList')
        lis = product.find_elements(By.CLASS_NAME, 'baby-product')
        print('*' * 50 + ' ' + str(i) + 'Page Start!' + ' ' + '*' * 50)

        for li in lis: # 제품을 먼저 태그 안으로 접근을 함
            try: # 제품에 대한 정보가 있는지 확인 함
                product = li.find_element(By.CLASS_NAME, 'name').text
                price = li.find_element(By.CLASS_NAME, 'price-value').text
                delivery = li.find_element(By.CLASS_NAME, 'delivery').text
                url = li.find_element(By.CLASS_NAME, 'baby-product-link').get_attribute('href')
    
                print('Product:' + product)
                print('Price:' + price)
                print('Delivery:' + delivery)
                print('URL:' + url)

                ws.append([product, price, delivery, url])
    
            except Exception:
                pass

        print('*' * 50 + ' ' + str(i) + 'Page End!' + ' ' + '*' * 50)
        time.sleep(5)
        i += 1 # 다음 페이지로 넘어감
        driver.quit()

 

 

전체 소스코드

from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import NoSuchElementException
import time

# 엑셀로 추출
from openpyxl import Workbook

wb = Workbook()
ws = wb.create_sheet('식품')
wb.remove_sheet(wb['Sheet'])
ws.append(['이름', '가격', '배송기한', '상세URL'])

i = 17

while True:
    options = webdriver.ChromeOptions()
    # options.add_argument('--headless') # 작동 과정은 안보여주고 내부적으로 크롤링 진행
    UserAgent = '각자 UserAgent 넣으면 됨' # 크롤링할 때 로봇이 아님을 알려줌
    options.add_argument('user-agent=' + UserAgent)

    # 크롬 드라이브를 직접 호출 후 다운
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

    # 크롤링
    driver.get(url='https://www.coupang.com/np/categories/194276?page=' + str(i))
    time.sleep(5)
    try: # 페이지의 순환
        product = driver.find_element(By.ID, 'productList')
        lis = product.find_elements(By.CLASS_NAME, 'baby-product')
        print('*' * 50 + ' ' + str(i) + 'Page Start!' + ' ' + '*' * 50)

        for li in lis: # 제품을 먼저 태그 안으로 접근을 함
            try: # 제품에 대한 정보가 있는지 확인 함
                product = li.find_element(By.CLASS_NAME, 'name').text
                price = li.find_element(By.CLASS_NAME, 'price-value').text
                delivery = li.find_element(By.CLASS_NAME, 'delivery').text
                url = li.find_element(By.CLASS_NAME, 'baby-product-link').get_attribute('href')
    
                print('Product:' + product)
                print('Price:' + price)
                print('Delivery:' + delivery)
                print('URL:' + url)

                ws.append([product, price, delivery, url])
    
            except Exception:
                pass

        print('*' * 50 + ' ' + str(i) + 'Page End!' + ' ' + '*' * 50)
        time.sleep(5)
        i += 1 # 다음 페이지로 넘어감
        driver.quit()

    except NoSuchElementException: # 카테고리 리스트가 없다고 판단이되면 예외처리
        wb.save('C:/Autocoder/Coupang_Product_Grocery_all.xlsx')
        wb.close()
        exit(0)
728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.