๐ท๏ธ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev
title: "Scrapy Spider์์ Scrapling ํ์ฑ ์ฌ์ฉํ๊ธฐ" description: "Scrapy ์๋ต์ Scrapling์ผ๋ก ๋ณํํ๊ฑฐ๋ ์ฝ๋ฐฑ์ ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ถ๊ฐํ์ธ์. ๊ธฐ์กด Scrapy ํฌ๋กค๋ฌ๋ฅผ ์ ์งํ๋ฉด์ Scrapling ์ ํ์์ ์ ์ํ ํ์ฑ์ ์ฌ์ฉํ ์ ์์ต๋๋ค."
Scrapy์ Scrapling ํตํฉํ๊ธฐ {#integrating-scrapling-into-scrapy}
๊ธฐ์กด Scrapy ํ๋ก์ ํธ๋ฅผ ๋ค์ ์์ฑํ์ง ์๊ณ ๋ Scrapling์ ํ์ฑ API๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค. Scrapy ํตํฉ ๊ธฐ๋ฅ์ Spider ์ฝ๋ฐฑ ์์์ Scrapy ์๋ต์ Scrapling Response ๊ฐ์ฒด๋ก ๋ณํํฉ๋๋ค. ํฌ๋กค๋ง์ ๊ณ์ Scrapy๊ฐ ๋ด๋นํ๊ณ , ํ์ฑ์ Scrapling์ด ๋ด๋นํฉ๋๋ค.
!!! note "์ค์น"
์ด ๊ธฐ๋ฅ์ ๊ธฐ๋ณธ Scrapling ์ค์น(`pip install scrapling`)๋ก ์ฌ์ฉํ ์ ์์ผ๋ฉฐ ์ถ๊ฐ ์์กด์ฑ ๊ทธ๋ฃน์ ํ์ํ์ง ์์ต๋๋ค. Scrapy๋ง ์ค์น๋์ด ์์ผ๋ฉด ๋ฉ๋๋ค. ๊ธฐ์กด Scrapy ํ๋ก์ ํธ๋ผ๋ฉด ์ด๋ฏธ ์ค์น๋์ด ์์ต๋๋ค.
์ฌ์ฉ๋ฒ {#usage}
Spider ์ฝ๋ฐฑ์ scrapling_response ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ๋ถ์ด๋ฉด, ์ ๋ฌ๋ฐ๋ response ์ธ์๊ฐ Scrapling์ Response๊ฐ ๋ฉ๋๋ค.
import scrapy
from scrapling.integrations.scrapy import scrapling_response
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com"]
@scrapling_response
def parse(self, response): # `response` is now a Scrapling Response
first_quote = response.find_by_text("The world as we have created it", partial=True)
for quote in [first_quote, *first_quote.find_similar()]:
card = quote.parent
yield {
"text": quote.get_all_text(strip=True),
"author": card.find("small", class_="author").text,
"tags": [tag.text for tag in card.find_all("a", class_="tag")],
}
next_page = response.css("li.next a::attr(href)").get()
if next_page:
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
์ด ๋ฐ์ฝ๋ ์ดํฐ๋ Scrapy๊ฐ ์ง์ํ๋ ๋ชจ๋ ์ฝ๋ฐฑ ํํ์์ ์๋ํฉ๋๋ค. ์ผ๋ฐ ํจ์, ์ ๋๋ ์ดํฐ, ์ฝ๋ฃจํด, ๋น๋๊ธฐ ์ ๋๋ ์ดํฐ๋ฅผ ์ง์ํฉ๋๋ค. ๋ํผ๋ ์ฝ๋ฐฑ์ ํํ, ์ด๋ฆ, docstring์ ์ ์งํ๋ฏ๋ก Scrapy์ ์ฝ๋ฐฑ ๊ฒ์ฌ์ contract ๊ธฐ๋ฅ๋ ๊ณ์ ์๋ํฉ๋๋ค.
๋ฐ์ฝ๋ ์ดํฐ์ Selector ์ค์ ์ ์ ๋ฌํ ์๋ ์์ต๋๋ค. ์ด ์ค์ ์ ์์ฑ๋๋ Response์ ์ ๋ฌ๋ฉ๋๋ค.
@scrapling_response(adaptive=True, keep_comments=True)
def parse_product(self, response):
...
๋ฏธ๋ค์จ์ด๋ ํ์ดํ๋ผ์ธ์ฒ๋ผ ์ฝ๋ฐฑ ๋ฐ์์ Scrapy ์๋ต์ ๊ฐ์ง๊ณ ์๋ค๋ฉด ๋ณํ ํจ์๋ฅผ ์ง์ ์ฌ์ฉํ์ธ์.
from scrapling.integrations.scrapy import convert_response
scrapling_response = convert_response(scrapy_response, keep_comments=False)
์ฐธ๊ณ ์ฌํญ {#notes}
- ๋ค์ ํ์ด์ง๋ฅผ ์์ฒญํ ๋๋ ์ ์์ ์ฒ๋ผ
scrapy.Request(response.urljoin(href))๋ฅผ yieldํ์ธ์. Scrapling์Response.follow()๋ Scrapling Spider ์์คํ ์ฉ ์์ฒญ์ ๋ง๋ค๋ฏ๋ก Scrapy์์ ์ฒ๋ฆฌํ ์ ์์ต๋๋ค. - ์๋ต์
meta๋์ ๋๋ฆฌ๋ ์๊ฒ ๋ณต์ฌํ๋ฏ๋ก ๋ค๋ฅธ ๋ฏธ๋ค์จ์ด๊ฐ ์ ์ฅํ ๊ฐ์ฒด์๋ ๊ณ์ ์ ๊ทผํ ์ ์์ต๋๋ค. ์๋ฅผ ๋ค์ดscrapy-playwright๋ฅผ ์ฌ์ฉํ๋ฉด ํ์ด์ง๋ ์ฌ์ ํresponse.meta["playwright_page"]์ ์์ต๋๋ค. - ์๋ณธ
Set-Cookieํค๋์์ ์ฟ ํค๋ฅผ ํ์ฑํด ์๋ต์cookies๋์ ๋๋ฆฌ์ ๋ฃ์ต๋๋ค.