Skip to content
CrewAI 文档版本 跟随上游 源快照 1c6ea675 更新于 2026-10-18

Selenium 抓取器

SeleniumScrapingTool 旨在使用 Selenium 提取并读取指定网站的内容。

SeleniumScrapingTool

NOTE

该工具目前仍在开发中。随着我们不断完善其能力,用户可能会遇到意外行为。 你的反馈对我们做出改进非常宝贵。

描述

SeleniumScrapingTool 专为高效 Web 抓取任务而设计。 它允许通过使用 CSS 选择器定位特定元素,从网页中精确提取内容。 其设计满足广泛的抓取需求,可灵活处理任何提供的网站 URL。

安装

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

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

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

示例

以下示例演示如何将 SeleniumScrapingTool 与 CrewAI 智能体一起使用:

python
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()

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

python
# 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 智能体集成:

python
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 来自动化浏览器交互:

python
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,则添加 cookie
  5. 根据 CSS 选择器提取内容
  6. 将提取的内容以文本或 HTML 形式返回
  7. 关闭浏览器实例

处理动态内容

SeleniumScrapingTool 在抓取通过 JavaScript 加载动态内容的网站时尤为有用。通过使用真实浏览器实例,它可以:

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

你可以调整 wait_time 参数,以确保在提取前所有动态内容都已加载完成。

结论

SeleniumScrapingTool 提供了一种通过浏览器自动化从网站提取内容的强大方式。通过让智能体像真实用户一样与网站交互,它使得抓取那些用更简单方法难以或无法提取的动态内容成为可能。该工具特别适用于涉及 JavaScript 渲染内容的现代 Web 应用的研究、数据收集和监控任务。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。