描述

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 应用程序的研究、数据收集和监控任务特别有用。

《DeepSeek高效数据分析:从数据清洗到行业案例》聚焦DeepSeek在数据分析领域的高效应用,是系统讲解其从数据处理到可视化全流程的实用指南。作者结合多年职场实战经验,不仅深入拆解DeepSeek数据分析的核心功能——涵盖数据采集、清洗、预处理、探索分析、建模(回归、聚类、时间序列等)及模型评估,更通过金融量化数据分析、电商平台数据分析等真实行业案例,搭配报告撰写技巧,提供独到见解与落地建议。助力职场人在激烈竞争中凭借先进技能突破瓶颈,实现职业进阶,开启发展新篇。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐