文档API参考📓教程🧑‍🍳食谱🤝集成💜 Discord🎨 Studio
API 参考

Fetchers (获取器)

从一系列URL抓取内容并返回提取的内容流列表。

模块 link_content

LinkContentFetcher

抓取和提取URL内容。

它支持多种内容类型,在失败时重试,并自动为失败的Web请求轮换用户代理。在管道中将其用作数据抓取步骤。

您可能需要将LinkContentFetcher的输出转换为文档列表。使用HTMLToDocument转换器来完成此操作。

使用示例

from haystack.components.fetchers.link_content import LinkContentFetcher

fetcher = LinkContentFetcher()
streams = fetcher.run(urls=["https://www.google.com"])["streams"]

assert len(streams) == 1
assert streams[0].meta == {'content_type': 'text/html', 'url': 'https://www.google.com'}
assert streams[0].data

异步使用

import asyncio
from haystack.components.fetchers import LinkContentFetcher

async def fetch_async():
    fetcher = LinkContentFetcher()
    result = await fetcher.run_async(urls=["https://www.google.com"])
    return result["streams"]

streams = asyncio.run(fetch_async())

LinkContentFetcher.__init__

def __init__(raise_on_failure: bool = True,
             user_agents: Optional[list[str]] = None,
             retry_attempts: int = 2,
             timeout: int = 3,
             http2: bool = False,
             client_kwargs: Optional[dict] = None,
             request_headers: Optional[dict[str, str]] = None)

Initializes the component.

参数:

  • raise_on_failure:如果True,则在抓取单个URL失败时会引发异常。对于多个URL,它会记录错误并返回成功抓取的内容。
  • user_agents:抓取内容的用户代理。如果None,则使用默认用户代理。
  • retry_attempts: 重试获取 URL 内容的次数。
  • timeout: 请求的超时时间(秒)。
  • http2:是否为请求启用HTTP/2支持。默认为False。需要安装'h2'包(通过pip install httpx[http2]).
  • client_kwargs:传递给httpx客户端的其他关键字参数。如果None,则使用默认值。

LinkContentFetcher.__del__

def __del__()

在组件被删除时清理资源。

关闭同步和异步HTTP客户端,以防止资源泄漏。

LinkContentFetcher.run

@component.output_types(streams=list[ByteStream])
def run(urls: list[str])

从一系列URL抓取内容并返回提取的内容流列表。

每个内容流是一个ByteStream对象,其中包含提取的内容作为二进制数据。返回列表中的每个ByteStream对象对应单个URL的内容。每个流的内容类型存储在ByteStream对象的元数据中,键为"content_type"。抓取内容的URL存储在元数据中,键为"url"。

参数:

  • urls:要从中抓取内容的URL列表。

引发:

  • Exception:如果提供的URL列表只包含一个URL,并且raise_on_failure设置为True,则在内容检索过程中发生错误时将引发异常。在所有其他情况下,任何检索错误都会被记录下来,并返回成功检索到的ByteStream对象列表。

返回值:

ByteStream对象,表示提取的内容。

LinkContentFetcher.run_async

@component.output_types(streams=list[ByteStream])
async def run_async(urls: list[str])

异步从URL列表中抓取内容,并返回提取的内容流列表。

这是具有相同参数和返回值的run方法。

参数:

  • urls:要从中抓取内容的URL列表。

返回值:

ByteStream对象,表示提取的内容。