SeleniumScrapingTool

此工具目前正在开发中。随着我们对其功能的完善,用户可能会遇到意外行为。您的反馈对我们的改进至关重要。

描述

SeleniumScrapingTool 专为高效率的网页抓取任务而打造。它允许通过使用 CSS 选择器定位特定元素来精确提取网页内容。其设计满足各种抓取需求,提供了处理任何给定网站 URL 的灵活性。

安装

要使用此工具,您需要安装 CrewAI 工具包和 Selenium

pip install 'crewai[tools]'
uv add selenium webdriver-manager

您还需要在系统上安装 Chrome,因为该工具使用 Chrome WebDriver 进行浏览器自动化。

示例

以下示例演示了如何将 SeleniumScrapingTool 与 CrewAI 代理一起使用

代码
from crewai import Agent, Task, Crew, Process
from crewai_tools import SeleniumScrapingTool

# Initialize the tool
selenium_tool = SeleniumScrapingTool()

# Define an agent that uses the tool
web_scraper_agent = Agent(
    role="Web Scraper",
    goal="Extract information from websites using Selenium",
    backstory="An expert web scraper who can extract content from dynamic websites.",
    tools=[selenium_tool],
    verbose=True,
)

# Example task to scrape content from a website
scrape_task = Task(
    description="Extract the main content from the homepage of example.com. Use the CSS selector 'main' to target the main content area.",
    expected_output="The main content from example.com's homepage.",
    agent=web_scraper_agent,
)

# Create and run the crew
crew = Crew(
    agents=[web_scraper_agent],
    tasks=[scrape_task],
    verbose=True,
    process=Process.sequential,
)
result = crew.kickoff()

您也可以使用预定义的参数初始化工具

代码
# Initialize the tool with predefined parameters
selenium_tool = SeleniumScrapingTool(
    website_url='https://example.com',
    css_element='.main-content',
    wait_time=5
)

# Define an agent that uses the tool
web_scraper_agent = Agent(
    role="Web Scraper",
    goal="Extract information from websites using Selenium",
    backstory="An expert web scraper who can extract content from dynamic websites.",
    tools=[selenium_tool],
    verbose=True,
)

参数

SeleniumScrapingTool 在初始化期间接受以下参数

  • website_url:可选。要抓取的网站 URL。如果在初始化期间提供,则代理在使用工具时无需再指定。
  • css_element:可选。用于提取元素的 CSS 选择器。如果在初始化期间提供,则代理在使用工具时无需再指定。
  • cookie:可选。包含 cookie 信息的字典,用于模拟登录会话以访问受限内容。
  • wait_time:可选。指定抓取前的延迟(秒),以便网站和任何动态内容完全加载。默认为 3 秒。
  • return_html:可选。是否返回 HTML 内容而不是纯文本。默认为 False

将工具与代理一起使用时,代理需要提供以下参数(除非在初始化期间已指定)

  • website_url:必需。要抓取的网站 URL。
  • css_element:必需。用于提取元素的 CSS 选择器。

代理集成示例

以下是关于如何将 SeleniumScrapingTool 与 CrewAI 代理集成的更详细示例

代码
from crewai import Agent, Task, Crew, Process
from crewai_tools import SeleniumScrapingTool

# Initialize the tool
selenium_tool = SeleniumScrapingTool()

# Define an agent that uses the tool
web_scraper_agent = Agent(
    role="Web Scraper",
    goal="Extract and analyze information from dynamic websites",
    backstory="""You are an expert web scraper who specializes in extracting 
    content from dynamic websites that require browser automation. You have 
    extensive knowledge of CSS selectors and can identify the right selectors 
    to target specific content on any website.""",
    tools=[selenium_tool],
    verbose=True,
)

# Create a task for the agent
scrape_task = Task(
    description="""
    Extract the following information from the news website at {website_url}:
    
    1. The headlines of all featured articles (CSS selector: '.headline')
    2. The publication dates of these articles (CSS selector: '.pub-date')
    3. The author names where available (CSS selector: '.author')
    
    Compile this information into a structured format with each article's details grouped together.
    """,
    expected_output="A structured list of articles with their headlines, publication dates, and authors.",
    agent=web_scraper_agent,
)

# Run the task
crew = Crew(
    agents=[web_scraper_agent],
    tasks=[scrape_task],
    verbose=True,
    process=Process.sequential,
)
result = crew.kickoff(inputs={"website_url": "https://news-example.com"})

实现细节

SeleniumScrapingTool 使用 Selenium WebDriver 来自动化浏览器交互

代码
class SeleniumScrapingTool(BaseTool):
    name: str = "Read a website content"
    description: str = "A tool that can be used to read a website content."
    args_schema: Type[BaseModel] = SeleniumScrapingToolSchema
    
    def _run(self, **kwargs: Any) -> Any:
        website_url = kwargs.get("website_url", self.website_url)
        css_element = kwargs.get("css_element", self.css_element)
        return_html = kwargs.get("return_html", self.return_html)
        driver = self._create_driver(website_url, self.cookie, self.wait_time)

        content = self._get_content(driver, css_element, return_html)
        driver.close()

        return "\n".join(content)

该工具执行以下步骤

  1. 创建一个无头 Chrome 浏览器实例
  2. 导航到指定的 URL
  3. 等待指定时间以允许页面加载
  4. 如果提供了 cookie,则添加
  5. 根据 CSS 选择器提取内容
  6. 将提取的内容作为文本或 HTML 返回
  7. 关闭浏览器实例

处理动态内容

SeleniumScrapingTool 对于抓取使用 JavaScript 加载动态内容的网站特别有用。通过使用真实的浏览器实例,它可以

  1. 执行页面上的 JavaScript
  2. 等待动态内容加载
  3. 如果需要,与元素交互
  4. 提取通过简单 HTTP 请求无法获得的内容

您可以调整 wait_time 参数以确保所有动态内容在提取前已加载。

结论

SeleniumScrapingTool 提供了一种使用浏览器自动化从网站提取内容的强大方法。通过使代理能够像真实用户一样与网站交互,它促进了对使用简单方法难以或不可能提取的动态内容的抓取。此工具对于涉及带有 JavaScript 渲染内容的现代 Web 应用的研究、数据收集和监控任务特别有用。