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)
该工具执行以下步骤:
- 创建一个无头 Chrome 浏览器实例
- 导航到指定的 URL
- 等待指定的时间以允许页面加载
- 如果提供了 cookie,则添加它们
- 根据 CSS 选择器提取内容
- 以文本或 HTML 形式返回提取的内容
- 关闭浏览器实例
处理动态内容
SeleniumScrapingTool 对于抓取具有通过 JavaScript 加载的动态内容的网站特别有用。通过使用真实的浏览器实例,它可以:
- 在页面上执行 JavaScript
- 等待动态内容加载
- 如果需要,与元素进行交互
- 提取通过简单 HTTP 请求无法获得的内容
您可以调整 wait_time 参数,以确保在提取之前所有动态内容都已加载。
SeleniumScrapingTool 提供了一种强大的方法,通过浏览器自动化从网站提取内容。它使代理能够像真实用户一样与网站互动,从而方便地抓取使用简单方法难以或无法提取的动态内容。该工具对于涉及使用 JavaScript 渲染内容的现代 Web 应用程序的研究、数据收集和监控任务特别有用。