본문 바로가기

코딩

파이썬 웹 스크래핑 level 1 : 쿠팡 쇼핑 - (나도코딩)

나도코딩님 웹 스크래핑 튜토리얼을 보기 시작했다.

다른 웹 스크래핑 강의를 듣다가 유튜브에 올라온 걸 보고 바로 듣기 시작했는데 좋은 느낌이다.

import requests
import re
from bs4 import BeautifulSoup
url = "https://www.coupang.com/np/search?q=%EC%8A%AC%EB%A6%AC%ED%8D%BC&channel=user&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page=1&rocketAll=false&searchIndexingToken="
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"}

res = requests.get(url, headers = headers)
res.raise_for_status()

soup = BeautifulSoup(res.text, "lxml")
lastpage = soup.find("a", {"class":"btn-last disabled"}).get_text()
lastpage = int(lastpage)
for j in range(1, lastpage-1):
    print(f"page {j}")
    url = f"https://www.coupang.com/np/search?q=%EC%8A%AC%EB%A6%AC%ED%8D%BC&channel=user&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page={j}&rocketAll=false&searchIndexingToken=1=4&backgroundColor="
    headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"}

    res = requests.get(url, headers = headers)
    res.raise_for_status()

    soup = BeautifulSoup(res.text, "lxml")
    items = soup.find_all("li", {"class":re.compile("^search-product")})
    for i in items:
        ad_badge = i.find("span", {"class":"ad-badge-text"})
        if ad_badge:
            continue
        #name
        name = i.find("div", {"class":"name"}).get_text()
        #price
        price = i.find("strong", {"class":"price-value"}).get_text()
        price = f"{price}원"    
        
        #rate
        rate = i.find("em", {"class":"rating"})
        if rate:
            rate = rate.get_text()
            rate = float(rate)
            if rate < 4.5:
                continue
        else:
            continue
        
        #rate number
        rnum = i.find("span", {"class":"rating-total-count"}).get_text()
        rnum = int(rnum[1:-1])
        if rnum < 30:
            continue

        if rate and rnum:
            print(name, price, rate, rnum)
    print("-"*100)

쿠팡에는 친절하게도 마지막 페이지를 표시해줘서 그냥 쉽게 변수 lastpage를 구할 수 있었고, 그걸 범위로 하는 for함수를 만들어서 한 아이템에 대한 모든 페이지 정보를 다룰 수 있었다. 만족스럽다 ㅎ_ㅎㅎ 다음에는 이를 활용하여 무신사 스냅샷 중 멋진 것만 골라내는 코드를 써봐야 겠다.