Scrapy 스파이더 구축
Scrapy 프로젝트를 만들고 스파이더를 작성하며 링크를 자동으로 따라갑니다.
Scrapy 스파이더 구축은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
Scrapy란 무엇입니까
Scrapy는 비동기 크롤링, 항목 파이프라인, 미들웨어, 내보내기 기능을 기본으로 제공하는 종합 웹 스크래핑 프레임워크입니다.
# pip install scrapy
# Create a project:
# scrapy startproject myspider
# myspider/
# scrapy.cfg
# myspider/
# settings.py
# spiders/
# quotes_spider.pySpider 만들기
scrapy.Spider를 상속하고 name과 start_urls를 설정한 다음 parse()를 구현합니다.
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com"]
def parse(self, response):
for quote in response.css("div.quote"):
yield {
"text": quote.css("span.text::text").get(),
"author": quote.css("small.author::text").get(),
}CSS 및 XPath 선택자
response.css("selector") 또는 response.xpath("//xpath")를 사용해 데이터를 추출합니다. .get()은 첫 번째 일치 항목을 반환하고 .getall()은 모든 항목을 반환합니다.
def parse(self, response):
# CSS:
titles = response.css("h2.title::text").getall()
# XPath:
links = response.xpath("//a/@href").getall()
yield {"titles": titles, "links": links}링크 따라가기
링크를 따라가 다음 페이지를 파싱하려면 scrapy.Request를 yield합니다.
import scrapy
class Spider(scrapy.Spider):
name = "crawler"
start_urls = ["https://quotes.toscrape.com"]
def parse(self, response):
for quote in response.css("div.quote"):
yield {"text": quote.css("span.text::text").get()}
next_page = response.css("li.next a::attr(href)").get()
if next_page:
yield response.follow(next_page, self.parse)항목과 ItemLoaders
스크랩한 데이터를 구조화하려면 Item 클래스를 정의하고, 필드를 정리하고 변환하려면 ItemLoader를 사용합니다.
import scrapy
class ProductItem(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field()
url = scrapy.Field()
def parse(self, response):
item = ProductItem()
item["name"] = response.css("h1::text").get(strip=True)
item["price"] = response.css(".price::text").re_first(r"[\d.]+")
item["url"] = response.url
yield itemSpider 실행하기
프로젝트 디렉터리에서 실행합니다. JSON, CSV 또는 사용자 지정 파이프라인으로 내보낼 수 있습니다.
# Run and print to console:
# scrapy crawl quotes
# Save to JSON:
# scrapy crawl quotes -o quotes.json
# Save to CSV:
# scrapy crawl quotes -o quotes.csv
# Scrapy shell for interactive testing:
# scrapy shell "https://quotes.toscrape.com"설정: 다운로드 지연과 동시 요청 수
서버에 과부하를 주지 않도록 지연 시간을 추가하고 동시에 처리하는 요청 수를 제한합니다.
# settings.py
DOWNLOAD_DELAY = 1 # 1 second between requests
CONCURRENT_REQUESTS = 8 # max 8 at a time
CONCURRENT_REQUESTS_PER_DOMAIN = 2
ROBOTSTXT_OBEY = True # respect robots.txt미들웨어
미들웨어는 요청과 응답을 가로챕니다. 사용자 에이전트 순환, 재시도, 쿠키 처리에는 기본 제공 미들웨어를 사용합니다.
# settings.py
DOWNLOADER_MIDDLEWARES = {
"scrapy.downloadermiddlewares.retry.RetryMiddleware": 550,
"scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,
"myspider.middlewares.RotateUserAgentMiddleware": 400,
}항목 파이프라인
파이프라인은 스크래핑 후 항목을 처리합니다. 데이터를 정리하고 검증하며 중복을 제거한 뒤 데이터베이스에 저장합니다.
# pipelines.py
class CleanPipeline:
def process_item(self, item, spider):
item["name"] = item["name"].strip()
return item
class DBPipeline:
def open_spider(self, spider):
self.conn = connect_db()
def process_item(self, item, spider):
self.conn.insert(dict(item))
return item로그인 처리
Scrapy의 FormRequest를 사용해 로그인 양식을 제출하고 세션 쿠키를 유지합니다.
import scrapy
class AuthSpider(scrapy.Spider):
name = "auth"
login_url = "https://example.com/login"
def start_requests(self):
yield scrapy.Request(self.login_url, self.login)
def login(self, response):
yield scrapy.FormRequest.from_response(
response,
formdata={"user": "me", "pass": "secret"},
callback=self.parse
)JS 페이지용 scrapy-playwright
scrapy-playwright 플러그인은 Playwright를 Scrapy에 통합하여 JavaScript로 렌더링되는 페이지를 처리합니다.
# pip install scrapy-playwright
# playwright install
# settings.py:
# DOWNLOAD_HANDLERS = {
# "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
# "https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
# }
# In spider:
# yield scrapy.Request(url, meta={"playwright": True})빠른 확인
Scrapy Spider에서 response.follow(href, callback)은 무엇을 합니까?
복습
Scrapy Spider는 scrapy.Spider를 상속하고 start_urls를 선언한 뒤 parse()에서 항목이나 추가 요청을 yield합니다. CSS/XPath 선택자를 사용하고, DOWNLOAD_DELAY로 요청 사이에 충분한 지연을 두며, 파이프라인으로 데이터를 저장합니다.
자주 묻는 질문
“Scrapy 스파이더 구축” 강의는 무료인가요?
네 — “Scrapy 스파이더 구축” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Scrapy 스파이더 구축”에서 뭘 배우나요?
Scrapy 프로젝트를 만들고 스파이더를 작성하며 링크를 자동으로 따라갑니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Python Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“Scrapy 스파이더 구축” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.