Akashic Records

Scrapy, A multi-page website into An Excel file 본문

Web Crawling for Beginners

Scrapy, A multi-page website into An Excel file

Andrew's Akashic Records 2024. 5. 16. 15:33
728x90

Here is the image depicting a programmer's desktop environment with Python code using the Scrapy framework. The setting is designed to reflect a productive and tech-oriented atmosphere. You can view the image above.

 

여러 페이지로 구성된 웹사이트에서 크롤링된 데이터를 Excel 파일로 저장하도록 Scrapy 스파이더를 수정하기 위해 pandas 라이브러리를 사용하여 데이터 프레임을 처리하고 이를 .xlsx 파일로 저장합니다. 이전에 제공된 다중 페이지 크롤러 예제를 조정하여 데이터를 Excel 파일에 저장하는 방법은 다음과 같습니다.

 

필수 Libraries 설치하기

시작하기 전에 필요한 Python 라이브러리가 설치되어 있는지 확인해야 합니다. 아직 설치하지 않았다면 pip를 사용하여 설치할 수 있습니다.

pip install scrapy pandas openpyxl

openpyxl is needed as it is a dependency for writing Excel files with pandas.

 

1단계: 새 Scrapy 프로젝트 생성

먼저, Scrapy 프로젝트 안에서 작업하고 있는지 확인해야 합니다. 새 프로젝트를 설정하려면 터미널이나 커맨드 프롬프트를 열고 다음 명령어를 실행하세요:

scrapy startproject myproject

myproject를 프로젝트의 이름으로 바꾸세요. 이 명령어는 필요한 설정 파일이 있는 새 디렉토리를 생성합니다.

 

2단계: 스파이더 생성

새로 생성된 프로젝트 디렉토리로 이동하세요:

cd myproject

프로젝트 디렉토리 내부에서 스파이더를 생성하세요. 예를 들어, 스파이더 코드를 myproject/spiders/ 디렉토리 안에 excel_multipage.py로 저장하세요. 

 

3단계: 스파이더 정의

Here’s how to modify your Scrapy spider:

import scrapy
import pandas as pd


class MultiPageExcelSpider(scrapy.Spider):
    name = 'excel_multipage'
    start_urls = ['http://quotes.toscrape.com']

    def __init__(self):
        # Initialize a list to store crawled data
        self.items = []

    def parse(self, response):
        # Extract data and add it to the list
        for item in response.css('div.quote'):
            self.items.append({
                'text': item.css('span.text::text').get(),
                'author': item.css('span small::text').get()
            })

        # Follow the pagination link
        next_page = response.css('a.next-page::attr(href)').get()
        if next_page:
            yield response.follow(next_page, self.parse)
        else:
            # When done, save data to an Excel file
            self.save_to_excel()

    def save_to_excel(self):
        # Convert list to DataFrame
        df = pd.DataFrame(self.items)
        # Save DataFrame to Excel file
        df.to_excel('output.xlsx', index=False)

 

코드설명

  • Initialization: A new method __init__ is added to initialize a list that will store the data dictionaries extracted from each page.
  • Data Collection: In the parse method, instead of yielding the items immediately, they are added to the list self.items.
  • Saving to Excel: Once the crawling is finished (i.e., when there are no more pagination links to follow), the save_to_excel method is called.
    • This method converts the list of items into a pandas DataFrame.
    • Then, it saves the DataFrame into an Excel file named output.xlsx using the to_excel method. The index=False parameter prevents pandas from writing row numbers.

4단계: 스파이더 실행

스파이더 설정이 완료되면, Scrapy 프로젝트 디렉토리의 루트에 있을 때 스파이더를 실행하세요:

scrapy crawl excel_multipage
728x90
Comments