AI

スクレイピングデータでJevを使う方法:シナリオとコード例

Bright Data Python SDKでウェブデータを収集し、Jevで分類する方法。レビュー、投稿、リリースを扱う5つのPython例を紹介します。
3 分読
How to Use Jev with Scraped Data

この記事では、以下について学びます:

  • Jevとは何か、収集したデータをどのように評価するか。
  • System Oneモデルに適したウェブスクレイピング関連のユースケース。
  • Pythonプロジェクトを準備し、Bright DataとTypeSafeのSDKを初期化する方法。
  • Amazonレビューを収集し、Jevで問題の種類と深刻度で分類する方法。
  • Jevを使って公開TikTok投稿をコンテンツ種類とトピック関連性で評価する方法。
  • 暗号化ニュースに関するRedditの議論をJevがどのように分類できるか。
  • Jevを使ってLinkedInの企業プロフィールを業種とターゲット適合性で分類する方法。
  • Jevを通じてGitHubのリリースノートをアップグレード確認のために優先順位付けする方法。
  • Jevによるウェブスクレイピングが適する場合、柔軟な抽出に生成LLMが適する場合、そして両アプローチの違い。

早速見ていきましょう!

Jevとは何か、どのように動作するか?

JevはTypeSafeのSystem Oneモデルであり、入力を評価し、ソフトウェアが直接処理できる構造化された判断を返すように設計されています。

これは、プレーンテキストまたは構造化されたJSONとして提供された特定の状態を、開発者が定義した1つ以上の質問と比較することで機能します。各質問は、何を評価するか、期待される回答形式を指定します。生成型のチャットモデルとは異なり、このAIモデルは自由形式のテキストではなく、型付けされた結果と確率情報を返します。

Jevは3種類の質問タイプをサポートしています:

  • Choice:あらかじめ定義された選択肢のセットから回答を選択し、選択されたオプションとそれに関連する確率を返します。
  • Score:順序付けられたスケールに対して入力を評価し、可能な値全体にわたるスコアと確率分布を返します。
  • Noul:はい・いいえの命題を評価し、それが真である確率を0から1の間の値として推定します。

同一の状態に対して複数の質問を送信し、1回のリクエストで異なる評価を得ることができます。これらの結果により、アプリケーションは生成されたテキストを解釈することなく、分類、スコアリング、意思決定ロジックを実装できます。

なお、確率値と信頼度の値は不確実性を示すのに役立ちますが、正確性を保証するものではありません。アプリケーションは引き続き、閾値の適用、不確かな結果の処理、必要な場合の人によるレビューへのルーティングの責任を負います。カウントや正確な計算などの決定論的な操作は、従来のアプリケーションコードに残すべきです。

詳細については、System OneのドキュメントとTypeSafeのプリミティブをご覧ください。

ウェブスクレイピングにSystem Oneモデルを使用する

JevによるWebスクレイピングは、収集したページに解釈を必要とするテキストが含まれている場合に有用です。例えば、スクレイピングパイプラインはレビューの評価を抽出できますが、そのテキストが製品の欠陥、配送の問題、または顧客が評価する機能のどれを説明しているかを判断するには、その意味を解明する必要があります。Jevはこうした判断を下すことができます。

大まかに言うと、このワークフローには4つのステップがあります:

  1. ウェブページを収集し、JSONにパースする、またはウェブソースからJSONレコードを取得する。
  2. スクレイピングしたコンテンツをパースし、各レコードに関連するテキストとコンテキストを選択する。
  3. その状態を、焦点を絞った質問と、アプリケーションが必要とする回答の選択肢やスケールとともにJevへ送信する。
  4. 型付けされた結果とその確率情報をコード内で処理し、レコードをグループ化したり、閾値を適用したり、不確かなケースをレビューに回したりする。

以下の表は、実際のJevウェブスクレイピングのユースケースをまとめたものです:

ユースケース 例となるソース Jevが役立つ点 コードが処理する内容
レビューのテーマと問題の分類 Amazon、Walmart、Google Playのレビュー テーマ、感情、報告された製品の問題を特定 製品、問題、期間ごとに結果を集計
ソーシャルコンテンツとキャンペーンの監視 TikTok、Instagram、Xの公開投稿 投稿の目的と監視目標との関連性を分類 日付や関連性でフィルタリングし、活動をカウント
コミュニティ議論のトリアージ Reddit、Stack Overflow、GitHub Discussions バグ報告、機能要望、使用方法の質問、その他の議論タイプを区別 トピックをグループ化し、レビュー対象をフラグ付け
企業プロフィールの分類 LinkedInの企業ページ、企業ウェブサイト、ビジネスディレクトリ 記載された業種、サービス、定義した基準との整合性を分類 所在地や企業規模などの正確な適格性ルールを適用
リリースノートの優先順位付け GitHub Releases、GitLabのリリース、ベンダーの変更履歴ページ 更新の種類とその重要性を評価 バージョンを比較し、互換性ルールを適用

レビューのフィードバックを分析する

レビューの分類は、フィードバックが大量に届き、多様な表現が使われている場合に有用です。

小売業者のページ、マーケットプレイス、アプリストアからレビューを収集し、Jevに製品の欠陥、使い勝手の問題、配送の問題、肯定的な特徴などのテーマを区別させることができます。その後、別の実行で、定義したスケールに対して明示的に報告された問題について感情やスコアを評価できます。

評価基準は、結果を使って行おうとする意思決定を反映すべきです。分類後、コードは製品、テーマ、日付ごとに結果をグループ化し、さらなる調査が必要な繰り返しパターンを特定できます。これらの件数は収集したレビューを示すものであり、それ単独で製品全体の傾向を証明するものとして扱うべきではありません。確率情報は、曖昧なレビューを特定し、意思決定に影響を与える前にレビューへ回すのにも役立ちます。

公開ソーシャル投稿を分類する

公開ソーシャルコンテンツは、キャンペーンの監視、製品調査、トピック追跡を支援できます。

プラットフォームに応じて、公開投稿やトピック検索から投稿テキスト、キャプション、ハッシュタグ、公開日を収集できます。Jevは、投稿が発表、デモンストレーション、プロモーション、業界に関する議論、または無関係なコンテンツのいずれであるかを分類できます。また、製品発売の追跡など、特定の監視目標に合致するかどうかも尋ねることができます。

このアプローチは、異なる用語で同じ考えを表現している投稿をキーワードマッチングが特定できない場合に有用です。Jevは各レコードに対して一貫した分類を提供し、コードは日付フィルタリング、カテゴリー件数、関連性の閾値を処理します。

この文脈では、短いキャプションとコンテキストの欠如により、一部の判断が不確かになる可能性があります。そのため、各投稿を解釈するために必要な周辺情報のみを含め、分析にとって重要な場合は不明確なケースをレビューに回してください。

コミュニティ議論をトリアージする

公開フォーラム、Q&Aページ、議論スレッドには、サポートに関する質問、機能要望、バグ報告、一般的な反応が混在していることがよくあります。Jevは、各投稿をその目的によって分類でき、実行可能な製品フィードバックと無関係な議論を区別するのに役立ちます。特定の技術トピックに関するスレッドについては、セキュリティ上の懸念、懐疑や訂正、市場の反応、無関係なコメントなどのカテゴリーを定義することもできます。

これらの分類は議論の整理に役立ち、アプリケーションコードはカテゴリー件数の処理、コメントを親スレッドにリンクさせる処理、レビュー対象項目の優先順位付けを行います。それでも、特にセキュリティや製品の意思決定に影響を与える可能性がある場合は、事実に関する主張をさらなる調査が必要なものとして扱ってください。

ビジネスプロフィールを分類する

企業情報は、公式ウェブサイト、ビジネスディレクトリ、プロフェッショナルプロフィールに掲載されています。スクレイパーは企業の説明、記載されたサービス、その他の関連項目を収集できます。その後、Jevは収集したデータを処理し、記載された業種、サービス、定義した基準との整合性を特定できます。これは、企業が異なる用語で類似の活動を説明している場合に有用です。

アプリケーションは、これらの洞察を所在地や従業員数の範囲などの正確なフィルターと組み合わせることができます。これらのルールをコード内に保持することで、適格性判定プロセスの確認と維持が容易になります。ただし、プロフィールには重要な詳細が欠落していたり、広範な説明が使われていたりすることがあります。確率情報は、より綿密な検討が必要なレコードを特定するのに役立ちます。Jevは候補プロフィールの整理もサポートしますが、最終的な判断は定義した基準と裏付けとなる証拠に基づきます。

ソフトウェアのリリースノートを優先順位付けする

プロジェクトの変更履歴、リポジトリのリリース、ベンダーの更新ページでは、発行者ごとに異なる形式でソフトウェアの変更内容が説明されています。

Jevは、リリースノートをセキュリティ修正、破壊的変更、新機能、またはメンテナンス更新として区別できます。さらなる調査の優先順位をつけるために、明確に定義された注意レベルに対してスコアを割り当てるようJevに依頼することもできます。これにより、アプリケーションはソフトウェアに関連する区別に従って、構造化されていないリリース説明を整理できます。

Jevの分類は、潜在的に重要な変更を特定し、それらをレビューキューの上位に引き上げるのに役立ちます。同時に、アップグレードが自分の環境にとって安全かどうかを判定するものではありません。行動を起こす前に、不確かなまたは影響の大きい変更は人によるレビューに回してください。

実際のウェブスクレイピングシナリオでJevを使用するための前提条件

上記で説明したシナリオの実装を探る前に、いくつか準備すべきことがあります。

各シナリオは、ウェブデータの収集から始まります。これは最も難しいステップです。なぜなら、ほとんどのウェブサイトは自動化されたリクエストを制限するためにアンチスクレイピング対策を使用しているからです。また、Jevは、明確なスキーマに一致するJSONフィールドなど、構造化された形式の関連するページコンテンツを必要とします。そのため、適切なデータパースを行う必要があります。

ウェブデータ収集を簡素化するために、Bright DataのPython SDKを使用できます。これにより、Bright Dataのスクレイピングソリューションとやり取りするためのPythonインターフェースが提供されます。そのメソッドは、プロキシのローテーション、ブラウザのフィンガープリンティング、再試行、CAPTCHAの解決を管理するインフラを通じてウェブデータ収集リクエストをルーティングします。

Python SDKは、Bright DataのWeb Scraper APIのエンドポイントとのやり取りを簡素化し、Amazonレビュー、Redditの議論、その他のソースからのデータを取得する専用メソッドを提供します。Bright DataのWeb Scraper APIは対応するソースからデータを抽出・パースするため、ソースごとに個別のリクエストとパースロジックを構築・保守する必要はありません。これらはJSON、JSONL、CSV、NDJSON、またはParquet形式でデータを返します。

SDKは、構造化された検索エンジン結果を返すSERP APIのメソッドも提供します。同様に、Web Unlocker APIを呼び出して任意の公開ウェブページにアクセスできます。SDKの機能と使用方法の詳細については、公式紹介ブログ記事をお読みください。

注:Bright Dataの無料プランは、Python SDKを通じて利用可能なものを含む対応製品全体で月間5,000クレジットを提供します。そのため、この記事の例を無料で試すことができます。

では、始める前に、以下を用意してください:

以下の手順に従って、セットアップを完了してください!

ステップ1:Pythonプロジェクトを作成し、必要なパッケージをインストールする

プロジェクト用のフォルダ(例:jev-scraping)を作成し、次に仮想環境をセットアップします:

  mkdir jev-scraping
cd jev-scraping
python -m venv .venv

Windowsでは、PowerShellで次のコマンドで環境を有効化します:

  .\.venv\Scripts\Activate.ps1

macOSまたはLinuxでは、以下を使用します:

  source .venv/bin/activate

有効化した仮想環境内で、以下のコマンドで必要なパッケージをインストールします:

  python -m pip install brightdata-sdk typesafe-sdk python-dotenv

依存関係は以下の通りです:

  • brightdata-sdkは、Bright Dataのウェブスクレイピング、検索、データ収集製品を使用するためのメソッドを提供します。
  • typesafe-sdkは、状態と質問をJevに送信し、型付けされた結果を受け取るためのPythonクライアントです。
  • python-dotenvは.envファイルから環境変数を読み込み、スクリプトがソースコードにAPIキーを配置することなくアクセスできるようにします。

Bright Data Python SDKのドキュメントは、対応するスクレイパーとリクエストメソッドを扱っています。JevのPython要件と最初のリクエストについては、TypeSafe クイックスタートをご覧ください。

ステップ2:環境変数を設定する

Bright DataとTypeSafeのAPIキーは認証情報であるため、Pythonスクリプトにハードコーディングすべきではありません。代わりに、環境変数から読み込みます。簡単にするため、プロジェクトフォルダ内の.envファイルに保存し、python-dotenvに読み込ませます。

Pythonスクリプトの隣に.envという名前のファイルを作成し、プレースホルダーの値を自分のキーに置き換えて追加します:

  BRIGHTDATA_API_KEY=<YOUR_BRIGHT_DATA_API_KEY>
TYPESAFE_API_KEY=<YOUR_TYPESAFE_API_KEY>

Pythonスクリプトの先頭で、load_dotenv()をインポートし、いずれかのキーを読み込む前に呼び出します:

  from dotenv import load_dotenv

# Load the API keys from the local .env file
load_dotenv()

load_dotenv()は.envファイルを読み込み、そのキーと値のペアをプロセス環境に追加します。

ステップ3:SDKをセットアップする

Jevの質問タイプとともに、Bright DataとTypeSafeの2つのSDKをインポートします。また、環境変数を定数として読み込みます:

  import asyncio
import os
from dotenv import load_dotenv
from brightdata import BrightDataClient
from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul, Score

# Load the API keys from the local .env file
load_dotenv()

# Store both credentials once so client setup stays easy to read
BRIGHTDATA_API_KEY = os.environ["BRIGHTDATA_API_KEY"]
TYPESAFE_API_KEY = os.environ["TYPESAFE_API_KEY"]

非同期関数内で両方のSDKを初期化し、処理が完了したらコンテキストマネージャーを使用してリソースを解放します:

  async def main():
    async with (
        BrightDataClient(token=BRIGHTDATA_API_KEY) as brightdata,
        AsyncTypeSafeClient(
            api_key=TYPESAFE_API_KEY,
            model="jev-latest",
        ) as jev,
    ):
        # Collect records with Bright Data SDK, then classify selected fields with Jev...
        pass


if __name__ == "__main__":
    asyncio.run(main())

Bright Data SDKはJSON形式で構造化されたウェブデータを収集し、Jevはあなたが指定した質問に対してその状態を評価します。以下の例では、Jevをウェブスクレイピングのワークフローに統合する方法を示します。

例1:Amazonレビューを問題の種類別に分類する

製品レビューには、評価や購入確認済みステータスなどの構造化された詳細と、自由形式のフィードバックが組み合わされています。Bright Data SDKを使用すると、Amazon製品ページからレビューレコードを収集できます。その後、Jevはあなたが定義した分類体系に対してレビューテキストを評価します。

注:Amazon.comのレビューセクションは必ずしも公開アクセス可能であるとは限らず、ユーザーのログインが必要な場合があります。スクレイピングのワークフローは公開データのみを対象とすべきであるため、製品URLを使用する前に、レビューが認証なしでアクセス可能であることを確認してください。このため、この実装では公開アクセス可能なレビューを持つAmazon.co.ukの製品ページを使用しています。

ステップ1:Bright DataでAmazonレビューを収集する

Bright DataのAmazon Reviews Scraper APIは、評価、レビュータイトル、レビューテキスト、購入確認済みステータス、参考になった投票数などのフィールドを持つ構造化されたレビューレコードを返します。Python SDKのbrightdata.scrape.amazon.reviews()メソッドは製品URLを受け取り、これらのフィールドを返します。裏側では、Amazon Reviews Scraper APIを呼び出しています。

対象の製品URLを指定して、Amazonレビューのスクレイパーメソッドを呼び出します:

  result = await brightdata.scrape.amazon.reviews(
    url="https://www.amazon.co.uk/dp/B0GR6C9BXY/",
    timeout=300,
)

SDKは結果オブジェクトを返します。続行する前に、成功ステータスを確認し、データが含まれていることを確かめてください。結果には1件または複数件のレコードが含まれる場合があるため、リストに正規化することで、残りのコードを一貫した形にします:

  # Stop if the scrape failed or returned no reviews
if not result.success or not result.data:
    raise RuntimeError(f"Amazon review scrape failed: {result.error}")

# Normalize a single review and a list into the same loop shape
reviews = result.data if isinstance(result.data, list) else [result.data]

result.dataを確認またはエクスポートすると、各レビューレコードに評価、レビューテキスト、確認済みステータス、参考になった投票数などのフィールドが含まれていることがわかります:

The Amazon reviews data retrieved through the Bright Data Python SDK

ステップ2:Jevでレビューのトピックと深刻度を分類する

Scraper APIは、製品の詳細やレビュアーのメタデータを含む、この分類に必要な以上の情報を返します。Jevをレビューに集中させるために、評価、タイトル、テキストを選択します。これらのフィールドをリクエストのstate引数に渡します。

stateはJevが評価する入力であり、questionsはその入力から何を判定するかを伝えます。ここでは、Choice質問がJevに固定カテゴリーからレビューの主なトピックを選択するように求め、Score質問が定義されたスケールで問題の深刻度を評価するように求めます。これにより、カウントして後のPythonロジックで使用できる構造化された回答が得られます。

まず、カテゴリーと深刻度レベルを指定します。カテゴリーの説明は、耐久性の問題、設定の問題、パッケージングに関する苦情、肯定的なフィードバック、その他のトピックを区別します。順序付けられた深刻度の基準は、問題なしまたは軽微な問題から、通常の使用を妨げる深刻な問題まで及びます:

  questions = {
    "issue": Choice(
        instructions="What is the main topic of `text`?",
        criteria={
            "durability": "The product broke, wore out, or feels poorly made.",
            "setup": "The product is difficult to install or use for the first time.",
            "packaging": "The complaint concerns shipping or packaging.",
            "positive": "The review mainly praises the product.",
            "other": "The review discusses another topic.",
        },
    ),
    "severity": Score(
        instructions="How serious is the product issue described in `text`?",
        criteria=[
            "No issue or a minor preference.",
            "A noticeable issue with a workaround.",
            "A serious issue that prevents normal use.",
        ],
    ),
}

次に、各レビュー用の状態を準備します。APIレスポンスはタイトルにreview_headerを使用するため、コードはその値をtitleキーにマッピングします。レビューテキストフィールドを確認し、それが含まれていないレコードをスキップします:

  # Classify at most five returned reviews
for review in reviews[:5]:
    if not isinstance(review, dict):
        continue

    # Read review text from the first available field in this record
    text = review.get("review_text") or review.get("text") or review.get("body")
    if not text:
        continue

    state = {
        "rating": review.get("rating"),
        "title": review.get("review_header") or review.get("title"),
        "text": text,
    }

同じループ内で、stateを構築した直後に、両方の質問とともに1回のsystem_one()呼び出しでJevに送信します:

  answer = await jev.system_one(
    state=state,
    questions=questions,
)

Jevは各質問に対して型付けされた回答を返します。

ステップ3:すべてをまとめる

以下のスクリプトは、レビューを収集し、スクレイパーのレスポンスを確認し、最大5件のレコードを分類し、選択されたカテゴリーをカウントします。レビューテキストがないレコードはスキップし、処理が終了したらコンテキストマネージャーを使用して両方のクライアントを閉じます:

  import asyncio
import os
from dotenv import load_dotenv
from brightdata import BrightDataClient
from typesafe_sdk import AsyncTypeSafeClient, Choice, Score

# Load the API keys from the local .env file
load_dotenv()

# Store both credentials once so client setup stays easy to read
BRIGHTDATA_API_KEY = os.environ["BRIGHTDATA_API_KEY"]
TYPESAFE_API_KEY = os.environ["TYPESAFE_API_KEY"]


async def main():
    # Context managers release each client's network resources when the script ends
    async with (
        BrightDataClient(token=BRIGHTDATA_API_KEY) as brightdata,
        AsyncTypeSafeClient(api_key=TYPESAFE_API_KEY, model="jev-latest") as jev,
    ):
        # Fetch recent product reviews, then keep the fields needed for classification
        result = await brightdata.scrape.amazon.reviews(
            url="https://www.amazon.co.uk/dp/B0GR6C9BXY/",
            timeout=300,
        )
        # Stop if the scrape failed or returned no reviews
        if not result.success or not result.data:
            raise RuntimeError(f"Amazon review scrape failed: {result.error}")

        # Normalize a single review and a list into the same loop shape
        reviews = result.data if isinstance(result.data, list) else [result.data]
        # Keep category totals for simple, deterministic aggregation
        counts = {}

        # Define the review labels and severity levels for Jev
        questions = {
            "issue": Choice(
                instructions="What is the main topic of `text`?",
                criteria={
                    "durability": "The product broke, wore out, or feels poorly made.",
                    "setup": "The product is difficult to install or use for the first time.",
                    "packaging": "The complaint concerns shipping or packaging.",
                    "positive": "The review mainly praises the product.",
                    "other": "The review discusses another topic.",
                },
            ),
            "severity": Score(
                instructions="How serious is the product issue described in `text`?",
                criteria=[
                    "No issue or a minor preference.",
                    "A noticeable issue with a workaround.",
                    "A serious issue that prevents normal use.",
                ],
            ),
        }

        # Classify at most five returned reviews
        for review in reviews[:5]:
            if not isinstance(review, dict):
                continue
            # Read review text from the first available field in this record
            text = review.get("review_text") or review.get("text") or review.get("body")
            if not text:
                continue

            # Send compact review fields and request fixed category and severity answers
            answer = await jev.system_one(
                state={
                    "rating": review.get("rating"),
                    "title": review.get("review_header") or review.get("title"),
                    "text": text,
                },
                questions=questions,
            )

            # Read the returned label and update the Python count
            issue = answer.choices["issue"].choice
            counts[issue] = counts.get(issue, 0) + 1
            print(f"{issue}: severity={answer.scores['severity'].score:.2f}")

        print("Issue counts:", counts)


if __name__ == "__main__":
    asyncio.run(main())

スクリプトを実行すると、次のような結果が得られます:

The output produced by the above script

この実行では、5件すべてのレビューが肯定的であると分類されました。深刻度スコアは0.00から0.03の範囲で、定義された評価基準によると問題なしまたは軽微な問題のみを示しています。レビューテキストと対応するスコアを考慮すると、これらの結果は提供されたフィードバックと一致しているように見えます。

完全なJevのレスポンスには、ChoiceとScoreの回答に対する確率情報と信頼度も含まれていることに注意してください:

The full output from the Jev API response

これらの値は簡潔なターミナル出力には表示されませんが、不確実性を確認する必要がある場合は、構造化されたレスポンス内で利用可能です:

例2:TikTok投稿をコンテンツタイプ別に分類する

Jevによるウェブスクレイピングを使用して、エスプレッソマシンに関する公開TikTok投稿をコンテンツタイプとトピック関連性で分類できます。

ステップ1:Bright DataでTikTok投稿を取得する

Bright DataのTikTok Scraper APIは、説明文、公開時刻、ハッシュタグ、エンゲージメント数、クリエイター詳細などの構造化された投稿データを返します。Python SDKでスクレイパーを呼び出して、TikTokの公開検索結果を照会します:

  result = await brightdata.scrape.tiktok.posts_by_search_url_fast(
    url="https://www.tiktok.com/search?q=espresso%20machine",
    num_of_posts=5,
    timeout=300,
)

処理する前にSDKの結果を確認し、一貫した反復処理のためにリストに正規化します:

  # Stop if the scrape failed or returned no posts
if not result.success or not result.data:
    raise RuntimeError(f"TikTok scrape failed: {result.error}")

# Normalize a single post and a list into the same loop shape
posts = result.data if isinstance(result.data, list) else [result.data]

返されたデータをエクスポートすると、以下が確認できます:

The structured TikTok JSON data returned by the Bright Data Python SDK

descriptionフィールドには投稿のキャプションが含まれており、ハッシュタグやメンションが含まれる場合があります。レコードには、create_time、hashtags、play_count、profile_usernameなどのフィールドも含まれます。

ステップ2:Jevで投稿コンテンツを分類する

このJevウェブスクレイピングの例では、各キャプションについて2つの判断を下します:

  1. Choiceは投稿をデモンストレーション、発表、プロモーション、または無関係なコンテンツに分類します。
  2. Noulは、キャプションが意味的にエスプレッソマシンに関するものである確率を推定します。

2つの質問を定義します:

  questions = {
    "content_type": Choice(
        instructions="What kind of post is described by `caption`?",
        criteria={
            "demonstration": "Shows a product being used or tested.",
            "announcement": "Announces a product, feature, or company update.",
            "promotion": "Encourages viewers to buy or use a product or service.",
            "unrelated": "Does not fit the other categories.",
        },
    ),
    "on_topic": Noul(
        instructions="Is `caption` meaningfully about espresso machines?"
    ),
}

次に、各レコードからキャプションを選択します。辞書型ではないレコードや、キャプションを含まないレコードはスキップします:

  # Classify at most five returned posts
for post in posts[:5]:
    if not isinstance(post, dict) or not post.get("description"):
        continue

    state = {"caption": post["description"]}

完全なスクリプトは、これらの質問を各キャプションに適用し、返された判断を処理します。

ステップ3:すべてをまとめる

以下のPythonスクリプトは、TikTokの検索結果を取得し、キャプションがないレコードをスキップし、各キャプションをJevに送信し、返されたコンテンツラベルをカウントします。両方の判断を確認できるように、各ラベルの横にトピック確率を出力します:

  import asyncio
import os
from dotenv import load_dotenv
from brightdata import BrightDataClient
from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul

# Load the API keys from the local .env file
load_dotenv()

# Store both credentials once so client setup stays easy to read
BRIGHTDATA_API_KEY = os.environ["BRIGHTDATA_API_KEY"]
TYPESAFE_API_KEY = os.environ["TYPESAFE_API_KEY"]


async def main():
    # Context managers release each client's network resources when the script ends
    async with (
        BrightDataClient(token=BRIGHTDATA_API_KEY) as brightdata,
        AsyncTypeSafeClient(api_key=TYPESAFE_API_KEY, model="jev-latest") as jev,
    ):
        # Fetch up to five posts from TikTok search results
        result = await brightdata.scrape.tiktok.posts_by_search_url_fast(
            url="https://www.tiktok.com/search?q=espresso%20machine",
            num_of_posts=5,
            timeout=300,
        )
        # Stop if the scrape failed or returned no posts
        if not result.success or not result.data:
            raise RuntimeError(f"TikTok scrape failed: {result.error}")

        # Normalize a single post and a list into the same loop shape
        posts = result.data if isinstance(result.data, list) else [result.data]
        # Keep category totals for simple, deterministic aggregation
        counts = {}

        # Define the content labels and topic relevance check
        questions = {
            "content_type": Choice(
                instructions="What kind of post is described by `caption`?",
                criteria={
                    "demonstration": "Shows a product being used or tested.",
                    "announcement": "Announces a product, feature, or company update.",
                    "promotion": "Encourages viewers to buy or use a product or service.",
                    "unrelated": "Does not fit the other categories.",
                },
            ),
            "on_topic": Noul(
                instructions="Is `caption` meaningfully about espresso machines?"
            ),
        }

        # Classify at most five returned posts
        for post in posts[:5]:
            # Skip invalid records and posts without a caption
            if not isinstance(post, dict) or not post.get("description"):
                continue

            # Send only the caption to Jev as the state
            state = {"caption": post["description"]}
            answer = await jev.system_one(
                state=state,
                questions=questions,
            )

            # Count the returned category and print topic probability
            label = answer.choices["content_type"].choice
            counts[label] = counts.get(label, 0) + 1
            print(f"{label}: on_topic={answer.nouls['on_topic'].noul:.2f}")

        print("Post counts:", counts)


if __name__ == "__main__":
    asyncio.run(main())

この実行でのターミナル出力は次の通りでした:

Jev classified 4 posts as

例3:暗号化ニュースに関するReddit議論を分類する

Jevは、過去1週間の「Anthropic encryption」に関するRedditの上位公開検索結果の反応をグループ化します。

ステップ1:Bright DataでReddit投稿を収集する

Bright DataのSocial Media Scraper APIはRedditに対応しており、タイトル、説明文、コメント(各コメントのテキストと支持数を含む)を持つ構造化された投稿を返します。Python SDKを使用して結果をリクエストします:

  result = await brightdata.scrape.reddit.posts_by_keyword(
    keyword="Anthropic encryption",
    date="Past week",
    sort_by="Top",
    num_of_posts=5,
    timeout=300,
)

エラーまたはデータ欠落がないか結果を確認し、単一レコードまたはリストを1つの一貫した形式に正規化します:

  # Stop if the scrape failed or returned no discussions
if not result.success or not result.data:
    raise RuntimeError(f"Reddit scrape failed: {result.error}")

# Normalize a single post and a list into the same loop shape
posts = result.data if isinstance(result.data, list) else [result.data]

スクレイピングしたデータをJSONにエクスポートしたとします。返された投稿レコードを見てみましょう:

The Reddit posts data returned by the Bright Data Python SDK

titleとdescriptionは投稿のテキストを提供し、commentsは説明文が空の場合にコンテキストを追加できます。

ステップ2:Jevで議論の反応を分類する

各投稿のタイトルと説明文を、利用可能な最大3件のコメントと組み合わせ、Jevに2つの判断のためのコンテキストを与えることができます:

  1. Choiceは主な反応をsecurity_concern、skepticism、market_reaction、またはunrelatedに割り当てます。セキュリティ上の懸念は暗号化や保護されたデータへの影響の可能性について議論します。懐疑的な反応は主張や見出しに疑問を呈したり訂正したりします。市場の反応は関連する価格や取引に焦点を当てます。無関係な投稿はニュースやその影響について議論していません。
  2. Noulは、タイトルまたは選択されたコメントが明確なセキュリティ上の懸念、訂正、または市場の反応を示す確率を推定します。

質問と基準を追加します:

  questions = {
    "theme": Choice(
        instructions="What is the main reaction in this Reddit discussion about current AI-and-encryption news?",
        criteria={
            "security_concern": "Expresses concern about the possible impact on encryption or protected data.",
            "skepticism": "Questions or corrects claims, headlines, or alarm about the story.",
            "market_reaction": "Focuses on price movements or trading related to the story.",
            "unrelated": "Does not discuss the encryption news or its effects.",
        },
    ),
    "relevant_reaction": Noul(
        instructions="Do the title or top comments show a clear security concern, correction, or market reaction to the current encryption news?"
    ),
}

コメントを選択するには、利用可能な支持数でランク付けします:

  title = post.get("title", "")
description = post.get("description") or post.get("description_markdown") or ""
comments = [
    comment
    for comment in (post.get("comments") or [])
    if isinstance(comment, dict)
]
comments.sort(key=lambda comment: comment.get("num_upvotes") or 0, reverse=True)
comment_text = " ".join(
    (comment.get("comment") or "") for comment in comments[:3]
)
body = "\n".join(part for part in (description, comment_text) if part)
state = {"title": title, "body": body}

ステップ3:すべてをまとめる

完全なスクリプトは、最大5件の検索結果を収集し、Bright Dataのレスポンスを確認し、各投稿とその最も投票数の多い利用可能なコメントからテキストを準備し、そのテキストを分類します。Pythonは返されたカテゴリーをカウントし、Jevはラベルと関連性の確率を提供します:

  import asyncio
import os
from dotenv import load_dotenv
from brightdata import BrightDataClient
from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul

# Load the API keys from the local .env file
load_dotenv()

# Store both credentials once so client setup stays easy to read
BRIGHTDATA_API_KEY = os.environ["BRIGHTDATA_API_KEY"]
TYPESAFE_API_KEY = os.environ["TYPESAFE_API_KEY"]

async def main():
    # Context managers release each client's network resources when the script ends
    async with (
        BrightDataClient(token=BRIGHTDATA_API_KEY) as brightdata,
        AsyncTypeSafeClient(api_key=TYPESAFE_API_KEY, model="jev-latest") as jev,
    ):
        # Search top Reddit posts about current AI and encryption news
        result = await brightdata.scrape.reddit.posts_by_keyword(
            keyword="Anthropic encryption",
            date="Past week",
            sort_by="Top",
            num_of_posts=5,
            timeout=300,
        )
        # Stop if the scrape failed or returned no discussions
        if not result.success or not result.data:
            raise RuntimeError(f"Reddit scrape failed: {result.error}")

        # Normalize a single post and a list into the same loop shape
        posts = result.data if isinstance(result.data, list) else [result.data]
        # Keep category totals for simple, deterministic aggregation
        counts = {}

        # Define the reaction categories and relevance question
        questions = {
            "theme": Choice(
                instructions="What is the main reaction in this Reddit discussion about current AI-and-encryption news?",
                criteria={
                    "security_concern": "Expresses concern about the possible impact on encryption or protected data.",
                    "skepticism": "Questions or corrects claims, headlines, or alarm about the story.",
                    "market_reaction": "Focuses on price movements or trading related to the story.",
                    "unrelated": "Does not discuss the encryption news or its effects.",
                },
            ),
            "relevant_reaction": Noul(
                instructions="Do the title or top comments show a clear security concern, correction, or market reaction to the current encryption news?"
            ),
        }

        # Process up to five returned discussions
        for post in posts[:5]:
            if not isinstance(post, dict):
                continue

            # Add the highest-voted available comments because descriptions may be empty
            title = post.get("title", "")
            description = post.get("description") or post.get("description_markdown") or ""
            comments = [
                comment
                for comment in (post.get("comments") or [])
                if isinstance(comment, dict)
            ]
            comments.sort(
                key=lambda comment: comment.get("num_upvotes") or 0, reverse=True
            )
            comment_text = " ".join(
                (comment.get("comment") or "") for comment in comments[:3]
            )
            body = "\n".join(part for part in (description, comment_text) if part)
            if not title and not body:
                continue

            # Keep only the post fields needed for Jev's judgments
            state = {"title": title, "body": body}

            # Request a theme label and estimate discussion relevance
            answer = await jev.system_one(
                state=state,
                questions=questions,
            )

            # Read the returned label and update the Python count
            label = answer.choices["theme"].choice
            counts[label] = counts.get(label, 0) + 1
            print(f"{label}: relevant={answer.nouls['relevant_reaction'].noul:.2f}")

        print("Discussion counts:", counts)


if __name__ == "__main__":
    asyncio.run(main())

スクリプトを実行すると、次のような出力が得られます:

The results returned by Jev when processing Reddit discussion data

この実行では、Jevは2件の議論をsecurity_concern、2件をskepticism、1件をmarket_reactionとしてラベル付けしました。関連性の確率は0.31から0.80の範囲でした。Pythonはこれら5つのラベルからカウントを計算しました。一般的に、これらのカテゴリーは反応を整理するために利用し、暗号化に関する主張を確認するためには利用しないでください。

例4:LinkedIn企業プロフィールを業種とターゲット適合性で分類する

市場調査では、Jevと組み合わせたウェブスクレイピングにより、公開LinkedIn企業プロフィールを業種別に分類し、データ関連サービスを提供しているかどうかを推定できます。ここではBright Dataの公開企業ページ(LinkedIn)を対象としますが、他の企業プロフィールでも構いません。

ステップ1:LinkedIn企業プロフィールを取得する

Bright Data LinkedIn Scraperは、名前、業種、説明、専門分野、所在地、ウェブサイトなどの構造化された企業の詳細を返します。

Bright Data Python SDKを使用して、LinkedIn URLから企業レコードをリクエストします:

  result = await brightdata.scrape.linkedin.companies(
    url="https://www.linkedin.com/company/bright-data",
    timeout=300,
)

SDKの結果には成功ステータスと返されたデータが含まれます。エラーまたは空の結果を確認し、単一レコードまたはリストを1つの企業レコードに正規化します:

  # Stop if the scrape failed or returned no company profile
if not result.success or not result.data:
    raise RuntimeError(f"LinkedIn scrape failed: {result.error}")

# Use the first record when the scraper returns a list
company = result.data[0] if isinstance(result.data, list) else result.data
if not isinstance(company, dict):
    raise RuntimeError("LinkedIn returned an unexpected company record")

返されたプロフィールレコードをエクスポートして確認すると、以下が表示されます:

The structured data returned by the Bright Data Python SDK for a LinkedIn company profile

nameとdescriptionは企業に関するコンテキストを提供し、industryは存在する場合、構造化された業種のヒントを追加できます。

ステップ2:Jevで企業の業種とターゲット適合性を分類する

企業名と説明文は、広範または曖昧な業種ラベルからその事業を区別するのに役立ちます。これらのフィールドを2つの焦点を絞った判断に使用します:

  1. Choiceは、企業をdata_and_analytics、software、professional_services、またはotherに位置付けます。カテゴリーの説明は、データプラットフォームとサービスを他のソフトウェア、コンサルティング、情報が不十分なプロフィールから区別します。
  2. Noulは、企業がデータ収集、分析、またはウェブデータサービスを提供している確率を推定します。

まず、カテゴリーの説明とターゲット適合性の質問を定義します:

  questions = {
    "industry_group": Choice(
        instructions="Which category best describes the company in `name`, `industry`, and `description`?",
        criteria={
            "data_and_analytics": "Data platforms, analytics, or data services.",
            "software": "Software products or technology services outside data services.",
            "professional_services": "Consulting or other business services.",
            "other": "Another industry or insufficient information.",
        },
    ),
    "target_fit": Noul(
        instructions="Does the company offer data collection, analytics, or web data services?"
    ),
}

次に、これらの判断に関連する企業フィールドを含むコンパクトなレコードを準備します:

  state = {
    "name": company.get("name"),
    "industry": company.get("industry"),
    "description": company.get("description") or "",
}

ステップ3:すべてをまとめる

完全なスクリプトはプロフィールを取得し、スクレイパーの結果を確認・正規化し、選択した企業の詳細をJevに送信し、Jevのカテゴリーとターゲット適合性の確率を出力します:

  import asyncio
import os
from dotenv import load_dotenv
from brightdata import BrightDataClient
from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul

# Load the API keys from the local .env file
load_dotenv()

# Store both credentials once so client setup stays easy to read
BRIGHTDATA_API_KEY = os.environ["BRIGHTDATA_API_KEY"]
TYPESAFE_API_KEY = os.environ["TYPESAFE_API_KEY"]


async def main():
    # Context managers release each client's network resources when the script ends
    async with (
        BrightDataClient(token=BRIGHTDATA_API_KEY) as brightdata,
        AsyncTypeSafeClient(api_key=TYPESAFE_API_KEY, model="jev-latest") as jev,
    ):
        # Fetch the public Bright Data company profile
        result = await brightdata.scrape.linkedin.companies(
            url="https://www.linkedin.com/company/bright-data",
            timeout=300,
        )
        # Stop if the scrape failed or returned no company profile
        if not result.success or not result.data:
            raise RuntimeError(f"LinkedIn scrape failed: {result.error}")

        # Use the first record when the scraper returns a list
        company = result.data[0] if isinstance(result.data, list) else result.data
        if not isinstance(company, dict):
            raise RuntimeError("LinkedIn returned an unexpected company record")

        # Keep only profile fields relevant to the classification
        state = {
            "name": company.get("name"),
            "industry": company.get("industry"),
            "description": company.get("description") or "",
        }

        # Define the company categories and target-fit question
        questions = {
            "industry_group": Choice(
                instructions="Which category best describes the company in `name`, `industry`, and `description`?",
                criteria={
                    "data_and_analytics": "Data platforms, analytics, or data services.",
                    "software": "Software products or technology services outside data services.",
                    "professional_services": "Consulting or other business services.",
                    "other": "Another industry or insufficient information.",
                },
            ),
            "target_fit": Noul(
                instructions="Does the company offer data collection, analytics, or web data services?"
            ),
        }

        # Ask Jev to classify the company and estimate target fit
        answer = await jev.system_one(
            state=state,
            questions=questions,
        )

        # Print Jev's category and yes probability for the target-fit question
        print("Company:", state["name"])
        print("Category:", answer.choices["industry_group"].choice)
        print("Target fit probability:", f"{answer.nouls['target_fit'].noul:.2f}")


if __name__ == "__main__":
    asyncio.run(main())

この実行のターミナル出力は次の通りでした:

The output produced by the script

Jevは対象の企業プロフィールをdata_and_analyticsとしてラベル付けし、ターゲット適合性の質問に対して0.98のはい確率を返しました。これはBright Dataが行っていることを考慮すると良い結果です。

例5:アップグレード確認のためのGitHubリリースノートの優先順位付け

Jevは、公開Flaskリリースノートを変更の種類と、アップグレード確認にどの程度注意を払うべきかで分類できます。

ステップ1:公開GitHubリリースを取得する

GitHubは、「List releases」エンドポイントを通じて、公開リポジトリで公開されたリリースを認証なしで利用可能にします。これはJSON形式の構造化データを返します。それでも、レート制限によってユーザーをブロックすることがあります。Bright Dataのプロキシと解除ネットワークを通じてスクレイピングリクエストをルーティングするために、Python SDKのscrape_url()メソッドはWeb Unlocker APIを使用してリクエストされたURLを取得します。

GitHubのリリースレコードには、tag_name、name、body、published_at、prereleaseなどのフィールドが含まれます。SDKで公開Flaskリリースエンドポイントをリクエストします:

  result = await brightdata.scrape_url(
    "https://api.github.com/repos/pallets/flask/releases?per_page=5",
    response_format="json",
    timeout=300,
)

生のSDKレスポンス(JSON出力を格納する文字列)を展開し、APIからのJSON本文をデコードし、単一のリリースまたはリストを1つの一貫した形式に正規化します:

  # Stop if the request failed or returned no data
if not result.success or not result.data:
    raise RuntimeError(f"GitHub release scrape failed: {result.error}")

# Unwrap the Bright Data response and decode the GitHub JSON body
payload = result.data
if isinstance(payload, dict) and "body" in payload:
    if payload.get("status_code") != 200:
        raise RuntimeError("GitHub returned HTTP {}".format(payload.get("status_code")))
    payload = payload["body"]
if isinstance(payload, str):
    payload = json.loads(payload)
if not payload:
    raise RuntimeError("GitHub returned no release records")

# Normalize one release record and a list for the loop
releases = payload if isinstance(payload, list) else [payload]

JSONにエクスポートし、デコードされたリリースレコードを確認して、確認可能なフィールドを調べます:

The JSON response from the GitHub

tag_nameはリリースバージョンを識別し、bodyにはJevが分類するノートが含まれています。GitHubが含める場合、nameフィールドが追加のタイトルコンテキストを提供できます。

ステップ2:Jevでリリースの変更とレビューの注意度を分類する

ノートのテキストを2つの判断に使用します:

  1. Choiceは主な変更をsecurity、breaking、feature、またはmaintenanceとしてラベル付けします。これらのカテゴリーは、セキュリティ修正、既存ユーザーに影響を及ぼす可能性のある変更、新しいユーザー向け機能、日常的な修正や依存関係の更新を区別します。
  2. Scoreは、0の日常的な確認から、1のアップグレード前のレビュー、2の影響が大きい可能性のある変更の優先順位付けまで、レビューの注意度を評価します。

カテゴリーと注意レベルを設定します:

  questions = {
    "change_type": Choice(
        instructions="What is the most important change in `notes`?",
        criteria={
            "security": "Fixes a security vulnerability or security risk.",
            "breaking": "Changes behavior in a way that may break existing users.",
            "feature": "Adds a user-facing capability.",
            "maintenance": "Primarily fixes bugs or updates internal dependencies.",
        },
    ),
    "review_attention": Score(
        instructions="How much upgrade review attention do `title` and `notes` warrant?",
        criteria=[
            "Routine, with no special review beyond normal checks.",
            "Review the change before upgrading.",
            "Prioritize review because the change may have high impact.",
        ],
    ),
}

次に、Jevが必要とするフィールドを選択し、ノートがないエントリをスキップして、各リリースを準備します:

  # Review at most five releases with notes
for release in releases[:5]:
    if not isinstance(release, dict):
        continue

    notes = release.get("body") or ""
    if not notes:
        continue

    state = {
        "tag": release.get("tag_name"),
        "title": release.get("name"),
        "notes": notes,
    }

Jevの注意スコアはトリアージの手がかりであり、互換性やセキュリティへの影響の正確な尺度ではありません。数値の精度に関する制限については、TypeSafeのモデルのジャギーさに関するガイダンスをご覧ください。

ステップ3:すべてをまとめる

最後のスクリプトはリリースをリクエストし、レスポンスを確認・正規化し、各ノートを分類してレビューの注意度をスコアリングするようJevに依頼し、カテゴリーをカウントします:

  import asyncio
import json
import os
from dotenv import load_dotenv
from brightdata import BrightDataClient
from typesafe_sdk import AsyncTypeSafeClient, Choice, Score

# Load the API keys from the local .env file
load_dotenv()

# Store both credentials once so client setup stays easy to read
BRIGHTDATA_API_KEY = os.environ["BRIGHTDATA_API_KEY"]
TYPESAFE_API_KEY = os.environ["TYPESAFE_API_KEY"]


async def main():
    # Context managers release each client's network resources when the script ends
    async with (
        BrightDataClient(token=BRIGHTDATA_API_KEY) as brightdata,
        AsyncTypeSafeClient(api_key=TYPESAFE_API_KEY, model="jev-latest") as jev,
    ):
        # Fetch public release records as JSON through Bright Data's URL scraper
        result = await brightdata.scrape_url(
            "https://api.github.com/repos/pallets/flask/releases?per_page=5",
            response_format="json",
            timeout=300,
        )
        # Stop if the scrape failed or returned no release records
        if not result.success or not result.data:
            raise RuntimeError(f"GitHub release scrape failed: {result.error}")

        # Unwrap the Bright Data response and decode the GitHub JSON body
        payload = result.data
        if isinstance(payload, dict) and "body" in payload:
            if payload.get("status_code") != 200:
                raise RuntimeError("GitHub returned HTTP {}".format(payload.get("status_code")))
            payload = payload["body"]
        if isinstance(payload, str):
            payload = json.loads(payload)
        if not payload:
            raise RuntimeError("GitHub returned no release records")

        # Normalize one release record and a list for the loop
        releases = payload if isinstance(payload, list) else [payload]
        # Keep category totals for simple, deterministic aggregation
        attention_counts = {}

        # Define release change categories and review attention levels
        questions = {
            "change_type": Choice(
                instructions="What is the most important change in `notes`?",
                criteria={
                    "security": "Fixes a security vulnerability or security risk.",
                    "breaking": "Changes behavior in a way that may break existing users.",
                    "feature": "Adds a user-facing capability.",
                    "maintenance": "Primarily fixes bugs or updates internal dependencies.",
                },
            ),
            "review_attention": Score(
                instructions="How much upgrade review attention do `title` and `notes` warrant?",
                criteria=[
                    "Routine, with no special review beyond normal checks.",
                    "Review the change before upgrading.",
                    "Prioritize review because the change may have high impact.",
                ],
            ),
        }

        # Review at most five release records
        for release in releases[:5]:
            if not isinstance(release, dict):
                continue
            # Skip release records without notes
            notes = release.get("body") or ""
            if not notes:
                continue

            # Ask Jev about the release note and relevant identifiers
            answer = await jev.system_one(
                state={
                    "tag": release.get("tag_name"),
                    "title": release.get("name"),
                    "notes": notes,
                },
                questions=questions,
            )

            # Count categories and leave upgrade decisions to a reviewer
            change_type = answer.choices["change_type"].choice
            attention = answer.scores["review_attention"].score
            attention_counts[change_type] = attention_counts.get(change_type, 0) + 1
            print(f"{release.get('tag_name')}: {change_type}, attention={attention:.2f}")

        print("Release counts:", attention_counts)


if __name__ == "__main__":
    asyncio.run(main())

スクリプトを起動すると、次のような結果が得られます:

Note the classification of the Flask releases by Jev

今回は、Jevは3件のリリースをsecurity、1件をmaintenance、1件をbreakingとしてラベル付けしました。レビュー注意度のスコアは0.03から1.85の範囲でした。

1つの回答がより綿密な検討に値することに注目してください:

The JSON produced by Jev for release

リリース3.0.3について、Jevはsecurityを選択しましたが、選択の信頼度はわずか0.32でした。その確率はsecurityが0.49、maintenanceが0.42でした。このような結果は、セキュリティ問題の確認としてではなく、レビュー担当者によるフォローアップが必要な不確かなラベルとして扱ってください。

Jev対LLM:ウェブスクレイピングにおいて

ここで、自然な疑問が浮かびます:Jevが適している場合と、生成LLMがそのタスクにより適している場合はいつか?

Jevと生成LLMは、スクレイパーがページコンテンツを収集した後、異なるニーズに応えます。Jevは、そのデータについて焦点を絞った判断を下します。例えば、レビューが欠陥を報告しているか、リリースに破壊的変更が含まれているかなどです。その制約された回答と確率情報は、コードが一貫したルールを適用し、不確かなレコードにフラグを立てるのに役立ちます。

一方、LLMはページのテキストを解釈して可変フィールドを抽出したり、長い議論を要約したり、複数のソースにまたがるパターンを説明したりできます。実際には、Jevは既知のカテゴリーを用いた繰り返しの判断に適しており、LLMは柔軟な抽出パイプラインに適しています。

ウェブスクレイピングでJevを選ぶべき場合

収集したデータについて繰り返し行われる焦点を絞った判断が必要な場合、Jevによるウェブスクレイピングを選択してください。以下の場合に適しています:

  • レビューを問題の種類別に、またはリリースノートを変更の種類別に分類するなど、既知のカテゴリーを使って多数のレコードを分類する必要がある場合。
  • 監視トピックに関連する投稿や、より綿密なレビューが必要な議論を見つけるなど、意味によってコンテンツをフィルタリングまたは優先順位付けする必要がある場合。
  • 意味的判断はJevに任せ、正確なカウント、日付比較、閾値、不確かな結果のエスカレーションはコードで処理したい場合。

関連情報:

ウェブスクレイピングでLLMを使うべき場合

タスクが柔軟な抽出または生成されたテキストを必要とする場合は、生成LLMを選択してください。以下の場合に有用です:

  • 名前、価格、説明など、事前にわからずページごとに異なり得る値を持つ構造化されたフィールドを抽出する必要がある場合。
  • スクレイピング対象のサイトがレイアウトを頻繁に変更したり、同じ情報を異なる方法で提示したりする場合。LLMはページコンテンツを解釈してスキーマにマッピングでき、特定の要素に結びついたCSSセレクタやXPathルールへの依存を減らせます。
  • 一貫したカテゴリーのセットを定義する前に、長い議論を要約したり、ページ間の違いを説明したり、テーマを探索したりしたい場合。

ウェブスクレイピングでLLMを使用する実装例については、以下をお読みください:

まとめ

このチュートリアルでは、Jevが製品レビュー、ソーシャルメディア投稿、企業プロフィール、ソフトウェアのリリースノートなど、スクレイピングしたレコードから選択されたフィールドをどのように分類できるかを見てきました。

ユースケースにかかわらず、このプロセスはウェブデータの収集から始まりました。多くのウェブサイトが最も価値のある公開ページをアンチボットソリューションで保護しているため、独自のスクレイピングインフラを構築・保守する手間を避けるには専用のスクレイピングソリューションが必要でした。

Bright DataのPython SDKは、実運用に対応したウェブデータスクレイピング製品を使いやすいPythonメソッドでラップしています。Bright Dataの無料プランを活用することで、SDKを通じて月に最大5,000件のウェブデータレコードを無料で収集できます。

Bright Dataは、人気のドメインからウェブデータを無料で取得するのに役立ちます。その後、Jevがそのコンテンツを評価し、Pythonがパース、カウント、閾値チェック、その他の決定論的な操作を処理します。

無料のBright Dataアカウントを作成し、Jevで構造化されたウェブデータレコードの分類を始めましょう!