본문 바로가기
Research/Data scraping

Scrapy_단순 스크래핑 및 결과 파일 저장하기

by RIEM 2023. 4. 18.

Scrapy로 audible을 스크래핑 해보자.

스파이더 생성

$ scrapy genspider audible www.audible.com/search

이미 설치해둔 scrapy 프레임워크 디렉터리 내에서 스파이더를 생성해야 한다. 프레임워크 디렉터리는 공식 문서를 참고하면 된다.

worldometers는 이전 프로젝트의 스파이더다. 그 옆에 audible.py 스파이더가 잘 생성되었다.

import scrapy


class AudibleSpider(scrapy.Spider):
    name = "audible"
    # root page
    allowed_domains = ["www.audible.com"]
    # add http + s
    start_urls = ["https://www.audible.com/"]

    def parse(self, response):
        pass

도메인은 루트 주소로 바꿔주고, url은 http+s로 수정해준다.

XPath 정보 수집

크롤링할 li의 xpath 주소를 알아낸다.

Scrapy code 짜기

import scrapy


class AudibleSpider(scrapy.Spider):
    name = "audible"
    # root page
    allowed_domains = ["www.audible.com"]
    # add http + s
    start_urls = ["https://www.audible.com/search"]

    def parse(self, response):
        # all the book lists(20)
        product_container = response.xpath('//div[@class="adbl-impression-container "]//li[contains(@class, "productListItem")]')

        for product in product_container:

            book_title = product.xpath('//h3[contains(@class, "bc-heading")]/a/text()').get()
            # getall in case of multiple author's'
            book_author = product.xpath('//li[contains(@class, "authorLabel")]/span/a/text()').getall()
            book_length = product.xpath('//li[contains(@class, "runtimeLabel")]/span/text()').get()

            print('book_title: ', book_title)
            print('book_author: ', book_author)
            print('book_length: ', book_length)

            yield {
                'title': book_title,
                'author': book_author,
                'length': book_length
            }

 

결과

$ scrapy crawl audible -o audible_onepage.csv

Good.

'Research > Data scraping' 카테고리의 다른 글

scrapy_실행 명령어 및 결과 JSON 저장  (0) 2023.04.18

댓글