BrightData: LangChain で構造化 Web データを抽出する

この高度なチュートリアルでは、LangChain フレームワーク内で BrightData の Scraper API を使用する方法を学びます。

生の HTML をスクレイピングするだけでなく、LinkedIn のような複雑な Web サイトからクリーンで構造化された JSON データを直接抽出する方法を学びます。次に、この構造化データを解釈して処理するために大規模言語モデル(LLM)を使用します。

1. 核心コンセプト: 生のスクレイピングを超えて

BrightData Scraper API は、主要な Web サイトから特定のタイプのデータを収集するために設計された強力なプリビルドコレクターです。例えば、LinkedIn プロフィール用のスクレイパーを書く代わりに、API に「この URL のプロフィールデータを取得してください」と伝えるだけで、クリーンな JSON オブジェクトが返されます。

langchain-brightdata 統合は、この機能を LangChain の Tool にパッケージ化します。Tool は、LLM が外部世界と相互作用するために使用できるコンポーネントです。今回の場合、BrightDataWebScraperAPI ツールを使用すると、AI エージェントが Web から構造化データを調べることができます。

2. セットアップ

まず、必要なライブラリをインストールしましょう。langchain、BrightData と OpenAI の統合、および API キー用の python-dotenv が必要です。

# Uncomment to install the required packages
# !pip install langchain langchain-brightdata langchain-openai python-dotenv

次に、このノートブックと同じディレクトリに .env という名前のファイルを作成します。このファイルには API キーが安全に保存されます。

.env ファイルは以下のようになります。

BRIGHT_DATA_API_KEY=your_brightdata_api_key
OPENAI_API_KEY=your_openai_api_key

注: .env ファイル内の変数名は BRIGHT_DATA_API_KEY であり、ツールが自動的に検索します。

BRIGHT_DATA_API_KEY は Bright Data ダッシュボード で確認できます。

3. スクレイパーツールの初期化と使用

提供されたコードは以下の通りです。API キーを読み込み、BrightDataWebScraperAPI をツールとして初期化します。次に、LinkedIn プロフィールから構造化データを取得するためにこれを呼び出します。dataset_type パラメーターは重要です。BrightData にどのタイプのデータを抽出するかを伝えます。

import os
import json
from dotenv import load_dotenv
from langchain_brightdata import BrightDataWebScraperAPI

# Load API keys from .env file
load_dotenv()

# The tool automatically finds the BRIGHT_DATA_API_KEY in your environment variables
scraper_tool = BrightDataWebScraperAPI()

# Invoke the tool to get structured data from a LinkedIn profile
print("Extracting data from LinkedIn profile...")
linkedin_data = scraper_tool.invoke(
    {"url": "https://www.linkedin.com/in/williamhgates/", "dataset_type": "linkedin_person_profile"}
 )

# Remove unwanted fields from the result before storing
fields_to_remove = ['people_also_viewed', 'activity', 'similar_profiles']

if isinstance(linkedin_data, list) and len(linkedin_data) > 0 and isinstance(linkedin_data[0], dict):
    data_to_print = dict(linkedin_data[0])
elif isinstance(linkedin_data, dict):
    data_to_print = dict(linkedin_data)
else:
    data_to_print = {}

for field in fields_to_remove:
    data_to_print.pop(field, None)

# Store the cleaned data for later use
profile_data = data_to_print
print("Data extraction completed successfully!")
Extracting data from LinkedIn profile...
Data extraction completed successfully!
print("Profile Data:")
print(json.dumps(profile_data, indent=2))
Profile Data:
{
  "id": "williamhgates",
  "name": "Bill Gates",
  "city": "Seattle, Washington, United States",
  "country_code": "US",
  "position": "Chair, Gates Foundation and Founder, Breakthrough Energy",
  "about": "Chair of the Gates Foundation. Founder of Breakthrough Energy. Co-founder of Microsoft. Voracious reader. Avid traveler. Active blogger.",
  "current_company": {
    "name": "Gates Foundation",
    "company_id": "gates-foundation",
    "title": "Co-chair",
    "location": null
  },
  "experience": [
    {
      "title": "Co-chair",
      "description_html": null,
      "start_date": "2000",
      "end_date": "Present",
      "company": "Gates Foundation",
      "company_id": "gates-foundation",
      "url": "https://www.linkedin.com/company/gates-foundation",
      "company_logo_url": "https://media.licdn.com/dms/image/v2/D560BAQEgMqqFTd40Tg/company-logo_100_100/company-logo_100_100/0/1736784969376/bill__melinda_gates_foundation_logo?e=2147483647&v=beta&t=2JH2cMcZms60vPAMbvVZyMeYXosQ1Jjy5axDlyeQ1Ww"
    },
    {
      "title": "Founder",
      "description_html": null,
      "start_date": "2015",
      "end_date": "Present",
      "company": "Breakthrough Energy",
      "company_id": "breakthrough-energy",
      "url": "https://www.linkedin.com/company/breakthrough-energy",
      "company_logo_url": "https://media.licdn.com/dms/image/v2/C4D0BAQGwD9vNu044FA/company-logo_100_100/company-logo_100_100/0/1630531940051/breakthrough_energy_ventures_logo?e=2147483647&v=beta&t=nL8eeluwraYnfTTnHApCodLZnaRGV8WtyNeFI_XhJ-M"
    },
    {
      "title": "Co-founder",
      "description_html": null,
      "start_date": "1975",
      "end_date": "Present",
      "company": "Microsoft",
      "company_id": "microsoft",
      "url": "https://www.linkedin.com/company/microsoft",
      "company_logo_url": "https://media.licdn.com/dms/image/v2/D560BAQH32RJQCl3dDQ/company-logo_100_100/B56ZYQ0mrGGoAU-/0/1744038948046/microsoft_logo?e=2147483647&v=beta&t=rr_7_bFRKp6umQxIHErPOZHtR8dMPIYeTjlKFdotJBY"
    }
  ],
  "url": "https://www.linkedin.com/in/williamhgates/",
  "educations_details": "Harvard University",
  "education": [
    {
      "title": "Harvard University",
      "url": "https://www.linkedin.com/school/harvard-university/?trk=public_profile_school_profile-section-card_image-click",
      "start_year": "1973",
      "end_year": "1975",
      "description": null,
      "description_html": null,
      "institute_logo_url": "https://media.licdn.com/dms/image/v2/C4E0BAQF5t62bcL0e9g/company-logo_100_100/company-logo_100_100/0/1631318058235?e=2147483647&v=beta&t=Ye1klXowyo8TIcnkhTlmORgiA5ZywvooNihDMnx5urQ"
    },
    {
      "title": "Lakeside School",
      "url": "https://www.linkedin.com/school/lakeside-school/?trk=public_profile_school_profile-section-card_image-click",
      "description": null,
      "description_html": null,
      "institute_logo_url": "https://media.licdn.com/dms/image/v2/D560BAQGFmOQmzpxg9A/company-logo_100_100/company-logo_100_100/0/1683732883164/lakeside_school_logo?e=2147483647&v=beta&t=EmadOLH7MckKZvCCrgmAOikCRtzVRtqqN4PJi35CNyo"
    }
  ],
  "avatar": "https://media.licdn.com/dms/image/v2/D5603AQF-RYZP55jmXA/profile-displayphoto-shrink_200_200/B56ZRi8g.aGsAY-/0/1736826818802?e=2147483647&v=beta&t=bKWfN6UwwtiCqFWsG7rBELbd48qJOAMLdxhBzzkJV0k",
  "followers": 38381729,
  "connections": 8,
  "current_company_company_id": "gates-foundation",
  "current_company_name": "Gates Foundation",
  "location": "Seattle",
  "input_url": "https://www.linkedin.com/in/williamhgates/",
  "linkedin_id": "williamhgates",
  "linkedin_num_id": "251749025",
  "banner_image": "https://media.licdn.com/dms/image/v2/D5616AQEjhPbTCeblYg/profile-displaybackgroundimage-shrink_200_800/B56ZcytR5SGsAc-/0/1748902420393?e=2147483647&v=beta&t=a-tBeZkxzWTHWYY6MAjxt0oTEuxlW33EUkK3gm5_te4",
  "honors_and_awards": null,
  "default_avatar": false,
  "memorialized_account": false,
  "bio_links": [
    {
      "title": "Blog",
      "link": "https://gatesnot.es/sourcecode-li"
    }
  ],
  "first_name": "Bill",
  "last_name": "Gates",
  "timestamp": "2025-08-06T04:01:50.054Z",
  "input": {
    "url": "https://www.linkedin.com/in/williamhgates/"
  }
}

4. LLM で構造化データを処理する

さて、楽しい部分です!クリーンで構造化されたデータがあります。HTML を解析したりテキストをクリーンアップしたりする必要はありません。このデータを直接 LLM に入力して、インテリジェントな処理を行うことができます。

抽出したデータに基づいて、LLM に短いプロフェッショナルな略歴を書いてもらいましょう。

from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from IPython.display import display, Markdown

# 1. Initialize the LLM
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.7)

# 2. Create a Prompt Template that accepts our structured data
prompt_template = PromptTemplate(
    input_variables=["profile_json"],
    template="""
    Based on the following JSON data from a LinkedIn profile, please write a concise, one-paragraph professional biography for this person within 50 words.
    
    JSON Data:
    {profile_json}
    
    Professional Biography:
    """
)

# 3. Create an LLM Chain
bio_chain = LLMChain(llm=llm, prompt=prompt_template)

# 4. Run the chain with our extracted data
print("Generating biography with LLM...")
professional_bio = bio_chain.run(profile_json=json.dumps(profile_data, indent=2))

display(Markdown(professional_bio))
Generating biography with LLM...

Bill Gates, Chair of the Gates Foundation and Founder of Breakthrough Energy, is a renowned philanthropist and technology pioneer. As the co-founder of Microsoft, he has revolutionized the digital landscape. With a passion for innovation and social impact, Gates continues to drive positive change worldwide.

5. まとめ

このノートブックでは、データ収集戦略をレベルアップしました。BrightData の Scraper API を LangChain 経由で使用することで、生の HTML を解析する面倒なステップを完全に回避しました。URL からクリーンで構造化された JSON データに直接移行し、それをインテリジェントな LLM タスクに使用しました。

このワークフローは、以下のタスクに信じられないほど効果的です。

  • 採用: 候補者プロフィールの分析。
  • 市場調査: E コマースサイトからの製品データの集約。
  • リード生成: 企業とその主要人物に関する情報の収集。

Bright Data の AI 提供について詳しくは、Bright Data AI offerings をご覧ください。