Scrape Element From Website 도구

Scrape Element From Website 도구 (ScrapeElementFromWebsiteTool)

CrewAI의 ScrapeElementFromWebsiteTool은 CSS 선택자를 사용해 웹사이트에서 특정 요소를 추출하도록 설계된 도구예요. 웹 페이지의 특정 부분만 필요할 때 원하는 콘텐츠를 정확히 추출할 수 있어 데이터 추출 태스크에 유용하답니다. 모든 요청은 CrewAI의 SSRF-safe HTTP 헬퍼를 통해 이루어집니다.

출처: 문서

본문

ScrapeElementFromWebsiteTool은 CSS 선택자를 사용해 웹사이트에서 특정 요소를 추출하도록 설계되었습니다. 이 도구를 사용하면 CrewAI 에이전트가 웹 페이지에서 타겟 콘텐츠를 스크래핑할 수 있어, 웹 페이지의 특정 부분만 필요할 때 데이터 추출 태스크에 유용해요. 요청은 CrewAI의 SSRF-safe HTTP 헬퍼를 통해 이루어지며, 요청된 URL과 모든 리다이렉트 홉이 비공개·예약 대역(클라우드 메타데이터 포함)에 대해 검사되고, TCP 연결은 해당 검사를 통과한 IP에 고정됩니다.

설치 (Installation)

이 도구를 사용하려면 필요한 의존성을 설치해야 합니다.

uv add requests beautifulsoup4

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

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

  1. 의존성 설치: 위 명령으로 필요한 패키지를 설치하세요.
  2. CSS 선택자 파악: 웹사이트에서 추출할 요소의 CSS 선택자를 결정하세요.
  3. 도구 초기화: 필요한 파라미터로 도구 인스턴스를 생성하세요.

예시 (Example)

다음 예시는 ScrapeElementFromWebsiteTool을 사용해 웹사이트에서 특정 요소를 추출하는 방법을 보여줍니다.

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

# 도구 초기화
scrape_tool = ScrapeElementFromWebsiteTool()

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

# 뉴스 웹사이트에서 헤드라인을 추출하는 예시 태스크
scrape_task = Task(
    description="Extract the main headlines from the CNN homepage. Use the CSS selector '.headline' to target the headline elements.",
    expected_output="A list of the main headlines from CNN.",
    agent=web_scraper_agent,
)

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

미리 정의된 파라미터로 도구를 초기화할 수도 있습니다.

# 미리 정의된 파라미터로 도구 초기화
scrape_tool = ScrapeElementFromWebsiteTool(
    website_url="https://www.example.com",
    css_element=".main-content"
)

파라미터 (Parameters)

ScrapeElementFromWebsiteTool은 초기화 시 다음 파라미터를 받습니다.

  • website_url: 선택. 스크래핑할 웹사이트의 URL. 초기화 시 제공하면 에이전트가 도구를 사용할 때 지정할 필요가 없습니다.
  • css_element: 선택. 추출할 요소의 CSS 선택자. 초기화 시 제공하면 에이전트가 도구를 사용할 때 지정할 필요가 없습니다.
  • cookies: 선택. 요청과 함께 보낼 쿠키를 담은 딕셔너리. 인증이 필요한 웹사이트에서 유용할 수 있어요.

사용법 (Usage)

ScrapeElementFromWebsiteTool을 에이전트와 함께 사용할 때, 에이전트는 다음 파라미터를 제공해야 합니다 (초기화 시 지정하지 않은 경우).

  • website_url: 스크래핑할 웹사이트의 URL.
  • css_element: 추출할 요소의 CSS 선택자.

도구는 CSS 선택자와 일치하는 모든 요소의 텍스트 콘텐츠를 개행 문자로 연결해 반환합니다.

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

# 특정 요소를 추출하는 태스크 생성
extract_task = Task(
    description="""
    Extract all product titles from the featured products section on example.com.
    Use the CSS selector '.product-title' to target the title elements.
    """,
    expected_output="A list of product titles from the website",
    agent=web_scraper_agent,
)

# 크루를 통해 태스크 실행
crew = Crew(agents=[web_scraper_agent], tasks=[extract_task])
result = crew.kickoff()

구현 세부 사항 (Implementation Details)

ScrapeElementFromWebsiteTool은 requests 라이브러리로 웹 페이지를 가져오고 BeautifulSoup로 HTML을 파싱해 지정된 요소를 추출합니다.

class ScrapeElementFromWebsiteTool(BaseTool):
    name: str = "Read a website content"
    description: str = "A tool that can be used to read a website content."

    # Implementation details...

    def _run(self, **kwargs: Any) -> Any:
        website_url = kwargs.get("website_url", self.website_url)
        css_element = kwargs.get("css_element", self.css_element)
        page = requests.get(
            website_url,
            headers=self.headers,
            cookies=self.cookies if self.cookies else {},
        )
        parsed = BeautifulSoup(page.content, "html.parser")
        elements = parsed.select(css_element)
        return "\n".join([element.get_text() for element in elements])

결론 (Conclusion)

ScrapeElementFromWebsiteTool은 CSS 선택자를 사용해 웹사이트에서 특정 요소를 추출하는 강력한 방법을 제공합니다. 에이전트가 필요한 콘텐츠만 정확히 표적으로 삼을 수 있게 해서, 웹 스크래핑 태스크를 더 효율적이고 집중적으로 만들어줘요. 웹 페이지에서 특정 정보를 추출해야 하는 데이터 추출, 콘텐츠 모니터링, 리서치 태스크에 특히 유용합니다.

더 알아보기 (Learn more)