AI

如何使用 Jev 处理抓取数据:场景、示例与代码

使用 Bright Data Python SDK 采集网页数据,并通过 Jev 对其进行分类。包含 5 个 Python 示例,涵盖评论、帖子和发布版本。
3 分钟阅读
如何使用 Jev 处理抓取数据

在本文中,你将了解:

  • Jev 是什么,以及它如何评估采集的数据。
  • 哪些网页爬虫相关用例适合 System One 模型。
  • 如何准备 Python 项目并初始化 Bright Data 和 TypeSafe SDK。
  • 如何采集 Amazon 评论,并使用 Jev 按问题类型和严重程度进行分类。
  • 如何使用 Jev 按内容类型和主题相关性评估 TikTok 公开帖子。
  • Jev 如何对有关加密新闻的 Reddit 讨论进行分类。
  • 如何使用 Jev 按行业和目标匹配度对 LinkedIn 公司资料进行分类。
  • 如何通过 Jev 确定 GitHub 发行说明的升级审查优先级。
  • 何时适合结合 Jev 使用网页爬虫,何时生成式 LLM 更适合灵活提取,以及这两种方法有何不同。

让我们开始吧!

什么是 Jev?它如何工作?

Jev 是 TypeSafe 的 System One 模型,旨在评估输入并返回可由软件直接处理的结构化判断。

它会将以纯文本或结构化 JSON 提供的给定状态与开发者定义的一个或多个问题进行比较。每个问题都会指定要评估的内容以及预期的答案格式。与生成式聊天模型不同,这种 AI 模型返回的是类型化结果和概率信息,而不是开放式文本。

Jev 支持三种问题类型:

  • Choice:从预定义选项集中选择答案,并返回所选选项及其相关概率。
  • Score:根据有序量表评估输入,并返回分数及各个可能值的概率分布。
  • Noul:评估一个是非陈述,并估算其为真的概率,以 0 到 1 之间的值表示。

你可以针对同一状态提交多个问题,从而在一次请求中获得不同的评估结果。这些结果让你的应用程序无需解读生成的文本,即可实现分类、评分和决策逻辑。

请注意,概率和置信度值有助于反映不确定性,但不能保证结果正确。你的应用程序仍需负责应用阈值、处理不确定结果,并在必要时将案例转交人工审查。计数和精确计算等确定性操作应继续由常规应用程序代码完成。

有关更多详细信息,请参阅 System One 文档和 TypeSafe 基元。

将 System One 模型用于网页爬虫

当采集的页面包含需要解读的文本时,结合 Jev 使用网页爬虫非常实用。例如,你的抓取管道可以提取评论评分,但要判断文本描述的是产品缺陷、配送问题,还是客户看重的功能,则需要理解其含义。Jev 可以完成这些判断。

从整体上看,该工作流包括四个步骤:

  1. 采集网页并将其解析为 JSON,或从 Web 来源获取 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 为每条记录提供一致的分类,而你的代码负责日期筛选、类别计数和相关性阈值。

在这种情况下,简短的说明文字和缺失的上下文可能使部分判断存在不确定性。因此,只需加入解读每个帖子所需的周边信息,并在不明确案例对分析非常重要时将其转交审查。

对社区讨论进行分流

公开论坛、问答页面和讨论串通常混合了支持问题、功能请求、错误报告和一般反馈。Jev 可以根据每条内容的表面用途进行分类,帮助你将可操作的产品反馈与无关讨论区分开来。对于围绕特定技术主题的讨论串,你还可以定义安全问题、质疑或纠正、市场反应和无关评论等类别。

这些分类有助于整理讨论,而你的应用程序代码负责统计类别数量、将评论关联到其上级讨论串,并确定待审查项目的优先级。不过,事实性主张仍应接受进一步调查,尤其是当它们可能影响安全或产品决策时。

对企业资料进行分类

公司信息分布在官方网站、商业目录和职业资料中。抓取工具可以采集公司描述、所列服务及其他相关字段。随后,Jev 可以处理采集的数据,识别声明的行业、服务以及与所定义标准的匹配程度。当不同公司使用不同术语描述类似活动时,这种方法非常实用。

你的应用程序可以将这些洞察与所在地或员工人数范围等精确筛选条件结合起来。将这些规则保留在代码中,可以使资格认定流程更易于检查和维护。不过,公司资料可能遗漏重要细节或使用宽泛描述。概率信息有助于识别需要进一步审查的记录。Jev 也支持整理候选公司资料,而你的标准和佐证则用于指导最终决策。

确定软件发行说明的优先级

项目变更日志、代码库发行版和供应商更新页面会采用因发布者而异的格式描述软件变更。

Jev 可以将发行说明区分为安全修复、破坏性变更、新功能或维护更新。为了确定进一步调查的优先级,你还可以要求 Jev 根据明确定义的关注级别进行评分。这样,你的应用程序就可以按照与你的软件相关的区分标准整理非结构化的发行版描述。

Jev 的分类有助于识别可能很重要的变更,并将其置于审查队列顶部。同时,这些分类无法确定升级对你的环境是否安全。在采取行动之前,应将不确定或影响重大的变更交由人工审查。

在实际网页爬虫场景中使用 Jev 的前提条件

在探索上述场景的实现之前,你需要先完成一些准备工作。

每个场景都从采集 Web 数据开始。这是最困难的步骤,因为大多数网站都会使用反抓取措施来限制自动请求。Jev 还需要相关页面内容采用结构化格式,例如符合清晰模式的 JSON 字段。因此,你必须妥善处理数据解析。

为了简化 Web 数据采集,你可以使用 Bright Data 的 Python SDK。它提供了一个 Python 接口,用于与 Bright Data 抓取解决方案交互。其方法会通过能够管理代理轮换、浏览器指纹、重试和验证码破解的基础设施传送 Web 数据采集请求。

Python SDK 简化了与 Bright Data 网页爬虫工具 API端点的交互,并提供专用方法来检索 Amazon 评论、Reddit 讨论和其他来源的数据。Bright Data 网页爬虫工具 API 会从支持的来源提取并解析数据,因此你无需为每个来源分别构建和维护请求及解析逻辑。它们以 JSON、JSONL、CSV、NDJSON 或 Parquet 格式返回数据。

该 SDK 还为搜索引擎 API提供了相关方法,可返回结构化的搜索引擎结果。同样,你可以调用网络解锁器 API访问任何公开网页。有关该 SDK 功能和用法的更多详细信息,请阅读官方介绍博文。

注意:Bright Data 的免费套餐每月提供 5,000 个积分,可用于支持的产品,包括可通过 Python SDK 使用的产品。因此,你可以免费试用本文中的示例。

现在,在开始之前,请确保你已具备:

按照以下步骤完成设置!

第 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 是一个 Python 客户端,用于向 Jev 发送状态和问题并接收类型化结果。
  • 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

导入 Bright Data 和 TypeSafe 这两个 SDK 以及 Jev 问题类型。同时,将环境变量加载为常量:

  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 格式采集结构化 Web 数据,而 Jev 会根据你提供的问题评估状态。以下示例展示了如何将 Jev 集成到网页爬虫工作流中。

示例 1:按问题类型对 Amazon 评论进行分类

产品评论结合了评分、已验证购买状态等结构化详细信息和自由文本反馈。Bright Data SDK 可让你从 Amazon 产品页面采集评论记录。随后,Jev 会根据你定义的分类体系评估评论文本。

注意:Amazon.com 上的评论部分并非总是公开可访问,并且可能要求用户登录。由于抓取工作流应仅以公开数据为目标,因此在使用产品 URL 之前,请确认无需身份验证即可访问评论。为此,本实现使用 Amazon.co.uk 上评论可公开访问的产品页面。

第 1 步:使用 Bright Data 采集 Amazon 评论

Bright Data 的 Amazon Reviews 爬虫工具 API 返回结构化评论记录,其中包含评分、评论标题、评论文本、已验证购买状态和“有帮助”投票数等字段。Python SDK 中的 brightdata.scrape.amazon.reviews() 方法接受产品 URL 并返回这些字段。它会在后台调用 Amazon Reviews 抓取工具 API。

使用目标产品 URL 调用 Amazon 评论抓取方法:

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

SDK 会返回一个结果对象。继续之前,请检查其成功状态并确认其中包含数据。结果可能包含一条或多条记录,因此请将其规范化为列表,使其余代码使用一致的数据结构:

  # 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,就会看到每条评论记录都包含评分、评论文本、验证状态和“有帮助”投票数等字段:

通过 Bright Data Python SDK 检索到的 Amazon 评论数据

第 2 步:使用 Jev 对评论主题和严重程度进行分类

抓取工具 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 后立即通过一次 system_one() 调用,将它连同两个问题一起发送给 Jev:

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

Jev 将为每个问题返回类型化答案。

第 3 步:整合所有内容

以下脚本会采集评论、检查抓取工具响应、对最多五条记录进行分类,并统计所选类别。它会跳过没有评论文本的记录,并使用上下文管理器在处理结束时关闭两个客户端:

  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())

执行脚本后,你将得到类似以下的结果:

上述脚本生成的输出

在此次运行中,所有五条评论都被归类为正面评论。其严重程度分数介于 0.00 和 0.03 之间,表明按照定义的评分标准不存在问题或仅有轻微问题。考虑到评论文本和相应分数,这些结果与所提供的反馈基本一致。

请注意,完整的 Jev 响应还包含其 Choice 和 Score 答案的概率信息和置信度:

Jev API 响应的完整输出

这些值不会显示在简洁的终端输出中,但如果你需要审查不确定性,可以在结构化响应中访问它们:

示例 2:按内容类型对 TikTok 帖子进行分类

你可以结合 Jev 使用网页爬虫,按内容类型和主题相关性对有关意式咖啡机的 TikTok 公开帖子进行分类。

第 1 步:使用 Bright Data 获取 TikTok 帖子

Bright Data 的 TikTok 爬虫 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]

如果导出返回的数据,你将看到:

Bright Data Python SDK 返回的结构化 TikTok JSON 数据

description 字段包含帖子的说明文字,其中可能包括话题标签和提及。记录还包含 create_time、hashtags、play_count 和 profile_username 等字段。

第 2 步:使用 Jev 对帖子内容进行分类

这个 Jev 网页爬虫示例会对每条说明文字做出两项判断:

  1. 一个 Choice 将帖子分类为演示、公告、推广或无关内容。
  2. 一个 Noul 估算说明文字与意式咖啡机存在实质关联的概率。

定义这两个问题:

  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 将 4 条帖子分类为“推广”,将 1 条分类为“无关”

示例 3:对有关加密新闻的 Reddit 讨论进行分类

Jev 会对过去一周 Reddit 中“Anthropic encryption”的热门公开搜索结果中的反应进行分组。

第 1 步:使用 Bright Data 采集 Reddit 帖子

Bright Data 的社交媒体抓取工具 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,
)

检查结果中是否存在错误或缺失数据,然后将单条记录或记录列表规范化为一种一致的数据结构:

  # 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。查看返回的帖子记录:

Bright Data Python SDK 返回的 Reddit 帖子数据

title 和 description 提供帖子文本,而当描述为空时,comments 可以补充上下文。

第 2 步:使用 Jev 对讨论反应进行分类

你可以将每篇帖子的标题和描述与最多三条可用评论组合起来,为 Jev 提供上下文以进行两项判断:

  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 步:整合所有内容

完整脚本会采集最多五条搜索结果,检查 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())

运行脚本后,你将得到类似以下的输出:

Jev 处理 Reddit 讨论数据时返回的结果

在此次运行中,Jev 将两条讨论标记为 security_concern,两条标记为 skepticism,一条标记为 market_reaction。相关性概率介于 0.31 和 0.80 之间。Python 根据这五个标签计算了数量。通常,应使用这些类别来整理反应,而不是确认有关加密的主张。

示例 4:按行业和目标匹配度对 LinkedIn 公司资料进行分类

在市场研究中,网页爬虫可以与 Jev 配合使用,按行业对 LinkedIn 公开公司资料进行分类,并估算该公司是否提供数据相关服务。在这里,我们将以 Bright Data 的 LinkedIn 公开公司页面为目标,但也可以使用任何其他公司资料。

第 1 步:获取 LinkedIn 公司资料

Bright Data LinkedIn 抓取工具返回结构化的公司详细信息,例如名称、行业、描述、专长、所在地和网站。

使用 Bright Data Python SDK,通过公司的 LinkedIn URL 请求公司记录:

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

SDK 结果包含成功状态和返回的数据。检查是否存在错误或空结果,然后将单条记录或记录列表规范化为一条公司记录:

  # 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")

如果你导出并检查返回的资料记录,将会看到:

Bright Data Python SDK 为 LinkedIn 公司资料返回的结构化数据

name 和 description 提供有关公司的上下文,而 industry 在存在时可以提供结构化的行业提示。

第 2 步:使用 Jev 对公司行业和目标匹配度进行分类

公司名称和描述有助于将其业务与宽泛或含义模糊的行业标签区分开来。使用这些字段进行两项针对性判断:

  1. 一个 Choice 将公司归入 data_and_analytics、software、professional_services 或 other。类别描述会区分数据平台和服务、其他软件、咨询服务以及信息不足的公司资料。
  2. 一个 Noul 估算公司提供数据采集、分析或 Web 数据服务的概率。

首先定义类别描述和目标匹配问题:

  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())

此次运行的终端输出如下:

脚本生成的输出

Jev 将源公司资料标记为 data_and_analytics,并为目标匹配问题返回了 0.98 的“是”概率。考虑到 Bright Data 的业务,这一结果很合理。

示例 5:确定 GitHub 发行说明的升级审查优先级

Jev 可以按变更类型以及升级审查可能需要的关注程度,对 Flask 的公开发行说明进行分类。

第 1 步:获取 GitHub 公开发行版

GitHub 通过其“List releases”端点,允许用户无需身份验证即可访问公共代码库中已发布的发行版。该端点以 JSON 格式返回结构化数据。不过,它仍可能通过速率限制来阻止用户。为了通过 Bright Data 的代理和解锁网络传送抓取请求,Python SDK 的 scrape_url() 方法会使用网络解锁器 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 正文,并将单个发行版或发行版列表规范化为一种一致的数据结构:

  # 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 并检查已解码的发行版记录,以查看可供审查的字段:

GitHub “List releases”端点返回的 JSON 响应

tag_name 标识发行版本,而 body 包含 Jev 要分类的发行说明。当 GitHub 提供标题时,name 字段可以补充标题上下文。

第 2 步:使用 Jev 对发行版变更和审查关注度进行分类

使用发行说明文本进行两项判断:

  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())

启动脚本。你将得到类似以下的结果:

请注意 Jev 对 Flask 各版本的分类

这一次,Jev 将三个发行版标记为 security,一个标记为 maintenance,另一个标记为 breaking。其审查关注度分数介于 0.03 和 1.85 之间。

请注意,其中一个响应值得进一步检查:

Jev 为“3.0.3”版本生成的 JSON

对于发行版 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 如何对抓取记录中的选定字段进行分类,包括产品评论、社交媒体帖子、公司资料和软件发行说明。

无论用例是什么,该流程都从采集 Web 数据开始。由于许多网站使用反机器人解决方案保护其最有价值的公开页面,因此你需要专门的抓取解决方案,以避免自行构建和维护抓取基础设施带来的开销。

Bright Data Python SDK 将其生产就绪的 Web 数据抓取产品封装为易于使用的 Python 方法。借助 Bright Data 免费套餐,你每月可以通过该 SDK 免费采集多达 5,000 条 Web 数据记录。

Bright Data 可帮助你免费从热门域名检索 Web 数据。随后,Jev 会评估其内容,而 Python 则负责解析、计数、阈值检查和其他确定性操作。

创建免费的 Bright Data 账户,立即开始使用 Jev 对结构化 Web 数据记录进行分类!

支持支付宝等多种支付方式

Antonello Zanini

技术写作

5.5 years experience

Antonello是一名软件工程师,但他更喜欢称自己为技术传教士。通过写作传播知识是他的使命。

Expertise
Web 开发 网页抓取 AI 集成