5. 크롤링 데이터 다루기 > 5-2. Spider 수정하기

Spider 수정하기

Item을 만들었으니 이제 spider가 추출한 데이터를 Item에 저장해 줄 차례입니다. Item에 데이터를 저장하는 방법은 다음과 같습니다.

💡 st11_all.py

  1. from <프로젝트 이름>.items import <Item 이름>

  2. 객체 = <Item 이름>()
    객체명은 사용자 자유. 본 교안에서는 item으로 생성

  3. parse 함수에

    1. 객체['필드 이름'] = 추출한 데이터
    2. yield 객체

무슨 소리일까요? 🙄

st11_all.py를 수정하면서 이해해 봅시다.

#st11_all.py
# 11번가 베스트 카테고리 상품명 크롤링

import scrapy
from st11.items import St11Item 혹은 Title    # (1) from <프로젝트 이름>.items import <Item 이름>

class St11AllSpider(scrapy.Spider):
    name = 'st11_all'
    allowed_domains = ['www.11st.co.kr/browsing/BestSeller.tmall?method=getBestSellerMain']
    start_urls = ['http://www.11st.co.kr/browsing/BestSeller.tmall?method=getBestSellerMain']
        
    def parse(self, response):
        # print(response.text)
                # 상품명이 담긴 css 선택자 경로들의 공통 부분을 입력
        # titles의 css 선택자 경로가 아래처럼 입력된 이유를 반드시 고민해 볼 것
                titles = response.css('div#bestPrdList div.viewtype.catal_ty ul li div a div.pname p::text').getall()
                for t in titles:         # t에 상품명 데이터 저장
                item = St11Item()    # (2) 객체 = <Item 이름>()
              item['title'] = t    # (3-a) 객체['필드 이름'] = 추출한 데이터
              yield item           # (3-b) yield 객체
마지막으로 업데이트 된 날짜:
2022년 9월 24일