Python/Crawling

특정 상품 가격 크롤링(+추가 기능)

hihih 2021. 9. 11. 16:28
728x90

추가한 기능

 

- 모든 페이지 크롤링

- 쿠팡 링크 삭제

- 4,000원대에 해당하는 상품 url 출력시키기

 


모든 페이지 크롤링

 

page_num = 1
while True :
    code = requests.get("https://www.coupang.com/np/search?q=%EC%98%A4%EA%B7%B8%EB%9E%98%EB%86%80%EB%9D%BC%ED%8C%9D&channel=recent&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page={}".format(page_num),headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(code.text, "html.parser")
    if len(product) == 0: # 끝 페이지까지 크롤링 모두 완료했다면?
    	break
    # 이하 코드 생략
    page_num += 1

 

모든 페이지를 크롤링 하기 위해 while 구문을 활용했다.

 

 


4,000원대에 해당하는 상품 url 출력시키기

 

url을 출력시키기 위해 요소 검사를 했다.

 

 

링크 주소

 

쿠팡 주소에 해당 url을 붙여 넣으면 상품 상세페이지로 넘어갈 수 있다.

 

 

 

li.search-product 요소 검사

 

 

처음엔 상품명과 가격처럼 메모장을 활용하여 출력시키려고 했다.

그러나 상품명과 일치하는 링크가 출력되지 않고

상품과 가격은 조건에 맞는 일부만 출력되는 것에 반해 링크는 순서대로 출력되었다.

 

메모장에 줄바꿈을 사용하여 url을 저장했는데 특정 행을 출력하는 법을 몰랐다.

그래서 생각한 것이 리스트로 만드는 것이었다.

리스트로 저장을 한 후 순서에 맞는 링크를 뽑아내기로 했다.

 

    full = soup.select("li.search-product")
    aaad = []
    for i in full:
        link = i.select_one("a")
        url = link.attrs["href"]
        aaad.append(url)

 

 

ex)

for문을 돌리면서 a번째 상품명과 가격이 출력되었다면 a번째 링크를 출력시키는 것이다.

그리고 해당 링크는 쿠팡 홈페이지 주소 + 해당 링크를 더해서 출력하게 했다.

(5,000원대는 상품이 일부 존재하고 4,000원대는 흔하지 않기 때문에 4,000원대만 링크가 함께 출력되게 했다.)

 

print(product[a].string + "\n" + price[a].text + "\n")            
print("https://www.coupang.com/"+aaad[a]+ "\n"+"\n")

 

 

최종적으로는 이를 활용해 알림 봇을 만들예정이기 때문에

최종적으로 출력된 부분을 메모장에 저장했다.

 

 


 

전체 코드

 

 

from bs4 import BeautifulSoup
import requests

page_num = 1
f = open("4000.txt", "w")
ff = open("5000.txt", "w")

print("4 ~ 5000원대 제품 크롤링 중")
print()

while True :
    code = requests.get("https://www.coupang.com/np/search?q=%EC%98%A4%EA%B7%B8%EB%9E%98%EB%86%80%EB%9D%BC%ED%8C%9D&channel=recent&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page={}".format(page_num),headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(code.text, "html.parser")
    product = soup.select("div.descriptions-inner > div.name")
    price = soup.select("em.sale > .price-value")
    full = soup.select("li.search-product")

    if len(product) == 0: # 끝 페이지까지 크롤링 모두 완료했다면?
        break

    aaad = []

    for i in full:
        link = i.select_one("a")
        url = link.attrs["href"]
        aaad.append(url)

    for a in range(len(product)):
        try:
            if len(price[a].text) == 5:
                if (price[a].text)[0:1] == "4":
                    f.write(product[a].string + "\n" + price[a].text +"원" + "\n")
                    f.write("https://www.coupang.com/" + aaad[a] + "\n" + "\n")
                    #print(product[a].string + "\n" + price[a].text + "\n")

                if (price[a].text)[0:1] == "5":
                    #print(product[a].string + "\n" + price[a].text + "\n")
                    ff.write(product[a].string + "\n" + price[a].text + "원" + "\n" + "\n")
                    #ff.write("https://www.coupang.com/"+aaad[a]+ "\n"+"\n")
            else:
                pass

        except:
            pass

    page_num += 1

print("4 ~ 5000원대 제품 크롤링 완료")
print()

f = open("4000.txt", "r", encoding='cp949')
rd = f.read()
print("4000원대 상품 : ", rd , "\n")

ff = open("5000.txt", "r", encoding='cp949')
rrd = ff.read()
print("5000원대 상품 : \n" + rrd)
728x90