python(7) 네이버 쇼핑 크롤링 (json data)

hyukstory 혁스토리·2020년 8월 25일
0

python

목록 보기
12/35

크롤링 단계

  1. title 출력
  2. 가격 출력
  3. url 정보
  4. dictionary 로 자료 생성
  5. json type file 로 저장

json 타입으로 저장하는 법

import json
file = open("./products.json","w")
file.write(json.dumps(products))
file.close()

네이버 쇼핑 크롤링

from bs4 import BeautifulSoup
import requests
import json


file = open("./naver.json", "w")

url = "https://search.shopping.naver.com/search/all?query=%EA%B1%B4%EC%A1%B0%EA%B8%B0&cat_id=&frm=NVSHATC"
html = requests.get(url)
soup = BeautifulSoup(html.text, 'lxml')
cnt = len(soup.find_all('div', class_='basicList_title__3P9Q7'))

for i in range(0,cnt) :
    naver = {}
    metadata = soup.find_all('div', class_='basicList_title__3P9Q7')[i]
    title = metadata.a.get('title')
    print("<제품명> : ", title)               # title
    
    price = soup.find_all('span', class_='price_num__2WUXn')[i].text
    print("<가격> : ", price)                # 가격
    
    url = metadata.a.get('href')
    print("<url> : ", url)                  # url
         
    print("===================================================")
    
    naver = {'제품명' : title , '가격' : price, 'url' : url }
    file.write(json.dumps(naver))

file.close()
profile
문돌이의 고군분투 개발 공부

1개의 댓글

comment-user-thumbnail
2021년 6월 30일

위에 코드를 보고 공부중 입니다. 리뷰수와 구매건수도 가져오고 싶어서 코드를 추가하려는데 리뷰와 구매건수의 경우 태그와 코드가 동일합니다.

review = soup.find_all('em', class_='basicList_num__1yXM9')[i].text
print("<리뷰> : ", review)  # review

sales = soup.find_all('em', class_='basicList_num__1yXM9')[i].text
print("<구매건수> : ", sales)  # sales

div태그의 basicList_etc_box__1Jzg6 속성 아래에 리뷰가 1번째, 구매건수 2번째, 등록일 3번째.... 순으로 있는 것 같은데 다른 정보들도 가져오려면 어떻게 수정해야할까요?

답글 달기