Scrapfly Scrape Website 도구

Scrapfly Scrape Website 도구 (ScrapflyScrapeWebsiteTool)

CrewAI의 ScrapflyScrapeWebsiteTool은 Scrapfly의 웹 스크래핑 API를 활용해 웹사이트에서 콘텐츠를 추출하는 도구예요. 헤드리스 브라우저 지원, 프록시, 안티봇 우회 기능으로 고급 웹 스크래핑을 제공하며, raw HTML·markdown·일반 텍스트 등 다양한 형식으로 웹 페이지 데이터를 추출할 수 있어요.

출처: 문서

본문

ScrapflyScrapeWebsiteTool은 Scrapfly의 웹 스크래핑 API를 활용해 웹사이트에서 콘텐츠를 추출하도록 설계되었습니다. 이 도구는 헤드리스 브라우저 지원, 프록시, 안티봇 우회 기능을 갖춘 고급 웹 스크래핑 능력을 제공하며, raw HTML·markdown·일반 텍스트를 포함한 다양한 형식으로 웹 페이지 데이터를 추출할 수 있어 다양한 웹 스크래핑 태스크에 적합합니다.

설치 (Installation)

이 도구를 사용하려면 Scrapfly SDK를 설치해야 합니다.

uv add scrapfly-sdk

scrapfly.io/register에 가입해 Scrapfly API 키를 얻어야 합니다.

시작하는 방법 (Steps to Get Started)

ScrapflyScrapeWebsiteTool을 효과적으로 사용하려면 다음 단계를 따르세요.

  1. 의존성 설치: 위 명령으로 Scrapfly SDK를 설치하세요.
  2. API 키 얻기: Scrapfly에 가입해 API 키를 받으세요.
  3. 도구 초기화: API 키로 도구 인스턴스를 생성하세요.
  4. 스크래핑 파라미터 설정: 필요에 따라 스크래핑 파라미터를 커스터마이즈하세요.

예시 (Example)

다음 예시는 ScrapflyScrapeWebsiteTool을 사용해 웹사이트에서 콘텐츠를 추출하는 방법을 보여줍니다.

from crewai import Agent, Task, Crew
from crewai_tools import ScrapflyScrapeWebsiteTool

# 도구 초기화
scrape_tool = ScrapflyScrapeWebsiteTool(api_key="your_scrapfly_api_key")

# 이 도구를 사용하는 에이전트 정의
web_scraper_agent = Agent(
    role="Web Scraper",
    goal="Extract information from websites",
    backstory="An expert in web scraping who can extract content from any website.",
    tools=[scrape_tool],
    verbose=True,
)

# 웹사이트에서 콘텐츠를 추출하는 예시 태스크
scrape_task = Task(
    description="Extract the main content from the product page at https://web-scraping.dev/products and summarize the available products.",
    expected_output="A summary of the products available on the website.",
    agent=web_scraper_agent,
)

# 크루 생성 및 실행
crew = Crew(agents=[web_scraper_agent], tasks=[scrape_task])
result = crew.kickoff()

스크래핑 파라미터를 커스터마이즈할 수도 있습니다.

# 커스텀 스크래핑 파라미터 예시
web_scraper_agent = Agent(
    role="Web Scraper",
    goal="Extract information from websites with custom parameters",
    backstory="An expert in web scraping who can extract content from any website.",
    tools=[scrape_tool],
    verbose=True,
)

# 에이전트는 다음과 같은 파라미터로 도구를 사용합니다:
# url="https://web-scraping.dev/products"
# scrape_format="markdown"
# ignore_scrape_failures=True
# scrape_config={
#     "asp": True,  # Cloudflare 같은 스크래핑 차단 솔루션 우회
#     "render_js": True,  # 클라우드 헤드리스 브라우저로 JavaScript 렌더링 활성화
#     "proxy_pool": "public_residential_pool",  # 프록시 풀 선택
#     "country": "us",  # 프록시 위치 선택
#     "auto_scroll": True,  # 페이지 자동 스크롤
# }

scrape_task = Task(
    description="Extract the main content from the product page at https://web-scraping.dev/products using advanced scraping options including JavaScript rendering and proxy settings.",
    expected_output="A detailed summary of the products with all available information.",
    agent=web_scraper_agent,
)

파라미터 (Parameters)

ScrapflyScrapeWebsiteTool은 다음 파라미터를 받습니다.

초기화 파라미터 (Initialization Parameters)

  • api_key: 필수. 사용자의 Scrapfly API 키.

실행 파라미터 (Run Parameters)

  • url: 필수. 스크래핑할 웹사이트의 URL.
  • scrape_format: 선택. 웹 페이지 콘텐츠를 추출할 형식. 옵션은 "raw"(HTML), "markdown", "text". 기본값은 "markdown".
  • scrape_config: 선택. 추가 Scrapfly 스크래핑 설정 옵션을 담은 딕셔너리.
  • ignore_scrape_failures: 선택. 스크래핑 중 실패를 무시할지 여부. True로 설정하면 스크래핑 실패 시 예외를 발생시키는 대신 None을 반환합니다.

Scrapfly 설정 옵션 (Scrapfly Configuration Options)

scrape_config 파라미터로 다음 옵션을 사용해 스크래핑 동작을 커스터마이즈할 수 있습니다.

  • asp: 안티스크래핑 보호 우회 활성화.
  • render_js: 클라우드 헤드리스 브라우저로 JavaScript 렌더링 활성화.
  • proxy_pool: 프록시 풀 선택 (예: "public_residential_pool", "datacenter").
  • country: 프록시 위치 선택 (예: "us", "uk").
  • auto_scroll: lazy-loaded 콘텐츠를 로드하기 위해 페이지를 자동 스크롤.
  • js: 헤드리스 브라우저가 실행할 커스텀 JavaScript 코드.

전체 설정 옵션 목록은 Scrapfly API 문서를 참고하세요.

사용법 (Usage)

ScrapflyScrapeWebsiteTool을 에이전트와 함께 사용할 때, 에이전트는 스크래핑할 웹사이트의 URL을 제공해야 하며 선택적으로 형식과 추가 설정 옵션을 지정할 수 있습니다.

# 에이전트와 도구를 사용하는 예시
web_scraper_agent = Agent(
    role="Web Scraper",
    goal="Extract information from websites",
    backstory="An expert in web scraping who can extract content from any website.",
    tools=[scrape_tool],
    verbose=True,
)

# 에이전트를 위한 태스크 생성
scrape_task = Task(
    description="Extract the main content from example.com in markdown format.",
    expected_output="The main content of example.com in markdown format.",
    agent=web_scraper_agent,
)

# 태스크 실행
crew = Crew(agents=[web_scraper_agent], tasks=[scrape_task])
result = crew.kickoff()

커스텀 설정을 사용한 더 고급 사용법:

# 더 구체적인 지침이 있는 태스크 생성
advanced_scrape_task = Task(
    description="""
    Extract content from example.com with the following requirements:
    - Convert the content to plain text format
    - Enable JavaScript rendering
    - Use a US-based proxy
    - Handle any scraping failures gracefully
    """,
    expected_output="The extracted content from example.com",
    agent=web_scraper_agent,
)

에러 처리 (Error Handling)

기본적으로 ScrapflyScrapeWebsiteTool은 스크래핑 실패 시 예외를 발생시킵니다. 에이전트에 ignore_scrape_failures 파라미터를 지정해 실패를 우아하게 처리하도록 지시할 수 있어요.

# 에이전트가 오류를 처리하도록 지시하는 태스크 생성
error_handling_task = Task(
    description="""
    Extract content from a potentially problematic website and make sure to handle any
    scraping failures gracefully by setting ignore_scrape_failures to True.
    """,
    expected_output="Either the extracted content or a graceful error message",
    agent=web_scraper_agent,
)

구현 세부 사항 (Implementation Details)

ScrapflyScrapeWebsiteTool은 Scrapfly SDK를 사용해 Scrapfly API와 상호작용합니다.

class ScrapflyScrapeWebsiteTool(BaseTool):
    name: str = "Scrapfly web scraping API tool"
    description: str = (
        "Scrape a webpage url using Scrapfly and return its content as markdown or text"
    )

    # Implementation details...

    def _run(
        self,
        url: str,
        scrape_format: str = "markdown",
        scrape_config: Optional[Dict[str, Any]] = None,
        ignore_scrape_failures: Optional[bool] = None,
    ):
        from scrapfly import ScrapeApiResponse, ScrapeConfig

        scrape_config = scrape_config if scrape_config is not None else {}
        try:
            response: ScrapeApiResponse = self.scrapfly.scrape(
                ScrapeConfig(url, format=scrape_format, **scrape_config)
            )
            return response.scrape_result["content"]
        except Exception as e:
            if ignore_scrape_failures:
                logger.error(f"Error fetching data from {url}, exception: {e}")
                return None
            else:
                raise e

결론 (Conclusion)

ScrapflyScrapeWebsiteTool은 Scrapfly의 고급 웹 스크래핑 기능으로 웹사이트에서 콘텐츠를 추출하는 강력한 방법을 제공합니다. 헤드리스 브라우저 지원, 프록시, 안티봇 우회 같은 기능으로 복잡한 웹사이트를 처리하고 다양한 형식으로 콘텐츠를 추출할 수 있어요. 신뢰할 수 있는 웹 스크래핑이 필요한 데이터 추출, 콘텐츠 모니터링, 리서치 태스크에 특히 유용합니다.

더 알아보기 (Learn more)