Closed5

WEBクローリングツールサーベイ(FireCrawl編)

szczytszczyt

Firecrawlとは

Firecrawlとは、WEBサイトに記載されている情報を収集してくれるクローリングと呼ばれるタスクを実行してくれるソフトウェア。
Mendable.ai社が提供している商用サービスであり、ソースコードをOpen-Sourceとして公開している。
https://www.firecrawl.dev
興味深い点は、LLM向けのデータ準備を謳う点だろうか。

簡単に触りたい場合は無料枠(500 credits/month)で十分だが、少し研究用に使用したい場合にはあっという間に枠を使い切ってしまう。
なぜなら、クローリングは複数のWEBサイトを巡回することで情報を収集する技法である。これに対して、APIは1つのWEBページをスクレイピングすると1 credit消費してしまう。
つまり、1つのWEBサイトが50ページで構成されているとすると、クローリングできるWEBサイトは10個程度が限界である。
大体の場合において、WEBページは50ページ程度には収まらない。かといってクローリングする深さを制限すると情報の取り逃がしが発生する。

上記のような理由から、ローカルホストするという選択肢が非常に魅力的である。
以下のGitHubの手順に従い、Firecrawlのローカルホストを試行する。
https://github.com/mendableai/firecrawl/blob/main/SELF_HOST.md

szczytszczyt

Firecrawl導入編

Firecrawl導入はGitHubにあるSELF_HOST.mdの手順に従う。
この手の開発速度が速いサービスにおいて導入手順を詳細に記述したところですぐに陳腐化しそうなので、大まかな手順と引っかかったところだけメモする。

前提条件

  • Gitがインストールされていること
  • Dockerがインストールされていること
  • (Linuxの場合)ポート解放など基本的な操作ができること

導入手順概略

  1. GitHubからソースコードをクローンする
git clone https://github.com/mendableai/firecrawl
  1. 環境設定ファイルをコピーする
cp ./app/api/.env.example ./.env

3.環境変数を指定する

# ===== Required ENVS ======
NUM_WORKERS_PER_QUEUE=8 
PORT=3002
HOST=0.0.0.0
# localhost -> redisに置き換える
REDIS_URL=redis://redis:6379
REDIS_RATE_LIMIT_URL=redis://redis:6379
# コメントアウトする
#PLAYWRIGHT_MICROSERVICE_URL=http://playwright-service:3000/html

## To turn on DB authentication, you need to set up supabase.
# falseに変更する
USE_DB_AUTHENTICATION=false
  1. (Option)環境に応じて変数を指定する
    会社や特殊な環境で使用されている方は、DockerfileにProxyの設定を記入する。
  2. Docker compose buildする
docker compose build
  1. Docker compose upする
docker compose up
  1. Dashboardにアクセスする
    http://0.0.0.0:3002/admin/@/queues

引っかかった箇所

おそらく同じミスをする人間はいないだろうが、環境変数は正確に指定する必要がある。

#これはダメ
USE_DB_AUTHENTICATION=False
# これはOK
USE_DB_AUTHENTICATION=false

次回は基本的な使い方とダッシュボードの使い勝手を確認する。

szczytszczyt

基本的な使い方

詳細は公式ドキュメント(https://docs.firecrawl.dev/introduction )を参照していただくとして、最も基本的な使い方はcurlでクエリを投げる方法。

curl -X POST http://localhost:3002/v0/crawl \
    -H 'Content-Type: application/json' \
    -d '{
      "url": "https://mendable.ai"
    }'

上記のクエリを投げると、私の環境では以下のレスポンスを得られた。

{"jobId":"fd99b599-9d3e-4533-8819-20a79de0a89c"}

これは回答を拒否されたわけではなく、「引き受けました。確認する際にはこのjobIdを参照してください。」という意味。
クローリングは探索に時間がかるため、終了待ちをするのは非現実的であるという判断かと思われる。
DashboardにアクセスすることでJobの進捗を確認することができる。

http://0.0.0.0:3002/admin/@/queues


キューの一つをクリックすることで、ジョブの結果を確認することができる。

szczytszczyt

実践的な使い方

より実践的な使い方としてPythonからクローリングした結果を取得する方法を考える。
最終的にLLMに処理させる場合、Pythonでスクリプトを書けば中間ファイルも不要で実装がスッキリするだろうという見立ての下で進める。

まずは、公式が用意しているライブラリの実装を確認するため、環境構築を進める。

 % python -V
Python 3.11.9
% pip list
Package    Version
---------- -------
pip        24.1.2
setuptools 70.3.0

%pip install firecrawl-py

これでライブラリのインストールが完了した。
しかし、このライブラリはFirecrawlの商用サービスのAPIを叩くように設定されているため、アクセス先のURLを引数などで変更できるか確認する。もし容易に変更できないようであれば、コードを改変して対応する方向で検討する。

手元の環境では、/venv/lib/python3.11.site-packages/firecral/firecrawl.pyにクラスが定義されていた。

class FirecrawlApp:
    """
    Initialize the FirecrawlApp instance.

    Args:
        api_key (Optional[str]): API key for authenticating with the Firecrawl API.
        api_url (Optional[str]): Base URL for the Firecrawl API.
    """
    def __init__(self, api_key: Optional[str] = None, api_url: Optional[str] = None) -> None:
        self.api_key = api_key or os.getenv('FIRECRAWL_API_KEY')
        if self.api_key is None:
            logger.warning("No API key provided")
            raise ValueError('No API key provided')
        else:
            logger.debug("Initialized FirecrawlApp with API key: %s", self.api_key)

        self.api_url = api_url or os.getenv('FIRECRAWL_API_URL', 'https://api.firecrawl.dev')
        if self.api_url != 'https://api.firecrawl.dev':
            logger.debug("Initialized FirecrawlApp with API URL: %s", self.api_url)

コードを見ると、初期化部でapi_urlを引数で渡せるようになっている。素晴らしい。
そこで、サンプルプログラムを改変して、下記のスクリプトを試してみる。

from firecrawl import FirecrawlApp

app = FirecrawlApp(api_url="http://localhost:3002", api_key="test")

crawl_result = app.crawl_url('mendable.ai', {'crawlerOptions': {'excludes': ['blog/*']}})

# Get the markdown
for result in crawl_result:
    print(result['markdown'])

→無事リクエストに成功した。

多少長いが、レスポンスも残しておく。

()
Open main menu

[Sign In](/signin)
[Get Started](/signup)

SOC 2 Type II Certified
-----------------------

Security and privacy at Mendable
================================

We take security and privacy very seriously at Mendable. Take a look at our security features below.

Product Security

#### Encryption in transit

Mendable uses TLS 1.2 or higher everywhere data is transmitted over potentially insecure networks..

#### Penetration Testing

Mendables engages with one of the best penetration testing firms in the industry, Oneleet, at least once a year. Email us to request a full report.

#### Vulnerability Scanning

Mendable uses automated vulnerability scanning tools to identify potential vulnerabilities in our applications and infrastructure.

Enterprise Security

#### Endpoint protection

All corporate devices are centrally managed and are equipped with device management software and anti-malware protection. Endpoint security alerts are monitored with 24/7/365 coverage.

#### Security education

Mendable provides comprehensive security training to all employees upon onboarding and annually through educational modules through Vanta’s platform.

#### SSO

Mendable provides SSO features for enterprises to manage their users and access to Mendable.

Frequently asked security questions

#### What security frameworks is Mendable compliant with?

Mendable is SOC 2 Type II compliant. Additionally, we will soon be making strides to become complaint in ISO 27K:2022 and GDPR.

#### Where does my data go when it is ingested to Mendable?

When you ingest your data into the Mendable ecosystem, it is stored on our database provider. However, your data is not used to train the underlying OpenAI models. OpenAI may hold onto conversation data for up to 30 days for content moderations purposes, however it will be subsequently deleted.

![Mendable logo](https://www.mendable.ai/Frame%20566%20(2).png)[Mendable](#_)

[Instagram](https://instagram.com/sideguide.dev)
[Twitter](https://twitter.com/mendableai)
[GitHub](https://github.com/sideguide)
[Discord](https://discord.com/invite/kJufGDb7AA)

![SOC 2 Type II](https://www.mendable.ai/soc2type2badge.png)

Documentation

*   [Getting Started](/signup)
    

*   [API Docs](https://docs.mendable.ai)
    

*   [Integrations](https://docs.mendable.ai/integrations/slack)
    

*   [Examples](https://docs.mendable.ai/examples)
    

*   [Tools & Actions](https://docs.mendable.ai/tools)
    

Use Cases

*   [Sales Enablement](/usecases/sales-enablement)
    

*   [Knowledge Base](/usecases/documentation)
    

*   [CS Enablement](/usecases/cs-enablement)
    

*   [Product Copilot](/usecases/productcopilot)
    

Resources

*   [Pricing](/pricing)
    

*   [Changelog](https://docs.mendable.ai/changelog)
    

*   [Security](/security)
    

*   [AI Trust Center](https://mendable.wolfia.com/?ref=mendable-footer)
    

Company

*   [Blog](/blog)
    

*   [Contact](mailto:eric@mendable.ai)
    

© 2024 SideGuide - SideGuide Technologies Inc.

[System Status](https://mendable.betteruptime.com)

[Status](https://mendable.betteruptime.com)
[Privacy Policy](/privacy-policy)
[Privacy](/privacy-policy)
[Terms](/terms-of-conditions)

おそらく開発用エンドポイントとサービス提供用のエンドポイントを切り替えたりする際に便利なように引数で受け取れる仕様を残してくれたのだろう。

まとめ

今回はPythonからクローリングするより実践的な使い方について調査した。
Pythonライブラリから呼び出すことで、より使い道の幅が広がる。

次回予告

次回からはLLMとの連携をトライアルする。

szczytszczyt

Mac環境構築メモ

Macで環境構築中に「Hash Sum mismatch」エラーが出た。

解決策

StackOverflowに解決策の記載があった。
https://stackoverflow.com/questions/67732260/how-to-fix-hash-sum-mismatch-in-docker-on-mac
Proxyの設定を変えてやるということで、以下をDockerfileに追加する。

RUN echo "Acquire::http::Pipeline-Depth 0;" > /etc/apt/apt.conf.d/99custom && \
    echo "Acquire::http::No-Cache true;" >> /etc/apt/apt.conf.d/99custom && \
    echo "Acquire::BrokenProxy    true;" >> /etc/apt/apt.conf.d/99custom
このスクラップは2025/01/07にクローズされました