在本文中,你将了解:
- 为什么 Kimi K3 是适合 LLM 驱动网页抓取的优秀模型。
- AI 驱动的网页抓取中的主要障碍,以及为什么 Bright Data 网络解锁器 API 是解决方案。
- 如何在 Python 脚本中使用 Kimi 执行 AI 驱动的网页抓取。
- 如何使用 Kimi K3 进行视觉网页抓取。
开始吧!
为什么使用 Kimi 进行网页抓取?
LLM 为网页抓取引入了一种新方法。你不必再编写复杂的解析逻辑从原始 HTML 中获取数据,而是可以让 AI 模型处理提取工作。这意味着你的爬虫工具不必依赖脆弱的 CSS 选择器或 XPath 表达式。
你只需要一个设计良好的提示词,告诉模型要提取哪些数据。只需几行代码,你就可以指示 Kimi 从任何网页抓取结构化数据。这种 AI 驱动的方法可以让网页抓取工具更灵活,也更易于维护。
Kimi K3 是最新的 Kimi 模型,非常适合基于文本的数据提取。它还提供视觉能力,可让你从网页截图、图像和其他视觉元素中提取信息。
更多详情,请参考我们的指南:
- 使用 AI 进行网页抓取。
- 使用视觉 AI 进行网页抓取。
AI 网页抓取中的最大挑战以及如何克服
AI 驱动的网页抓取面临的最大挑战,在很大程度上与你在传统网页抓取中遇到的挑战相同。尽管 AI 凭借灵活的提取能力,让页面结构变化不再那么棘手,但你仍然需要处理 JavaScript 渲染、反机器人系统、指纹识别、速率限制、CAPTCHA 以及其他访问限制。
毕竟,AI 抓取并不会消除大规模检索网页时的障碍。在 LLM 解析页面之前,你的爬虫工具必须先获取其内容,这意味着要应对所有阻止自动化请求成功的措施。
除此之外,token 使用量也很重要。将大型 HTML 文档发送给像 Kimi K3 这样强大的模型可能很快变得昂贵。在这种情况下,解决方案是将原始 HTML 转换为针对 LLM 优化的 Markdown。
将网页转换为干净的 Markdown,可以保留相关内容和结构,同时与原始 HTML 相比显著减少不必要的 token。它还可以以更便于 LLM 处理的格式保留标题、列表、链接和其他页面元素等信息。请参考我们的教程:如何将网站抓取为 Markdown。
Bright Data 网络解锁器 API:解决方案
Bright Data 的网络解锁器 API为 AI 驱动的网页抓取的主要挑战提供了实用解决方案。
该端点接受网页 URL,并在处理常见反机器人和反爬虫机制的同时返回其内容。它可以破解 CAPTCHA、渲染大量依赖 JavaScript 的页面、帮助克服浏览器指纹识别问题、管理速率限制等。
网络解锁器还可以以不同格式返回检索到的内容,包括:
随后,网络解锁器 API 请求的输出可以作为 Kimi K3 进行基于文本或视觉提取的输入。
注意:网络解锁器 API 包含在 Bright Data 免费套餐中,该套餐每月提供 5,000 次免费请求。
网络解锁器 API 的突出之处在于,它运行在 Bright Data 的大规模代理基础设施之上,其中包括 4 亿多个住宅 IP并支持无限并发。这为程序化网页抓取提供了可靠且高度可扩展的基础。
如何在 Python 中使用 Kimi K3 执行网页抓取
在这一指导部分中,你将学习如何构建一个使用 Kimi 进行 AI 驱动网页抓取的 Python 脚本。目标页面将是一个 Amazon 产品页面。
具体来说,你将看到如何抓取“Amazon Basics 20-Pack AA Alkaline Batteries, 1.5 Volt, 10-Year Leak-Free Shelf Life, for Everyday and Household Devices”这款产品。不过,这种方法的优势在于,它适用于任何其他 Amazon 产品页面,无论其结构或布局如何。
注意:对于可投入生产的结构化 Amazon 产品数据检索,请考虑使用 Amazon 爬虫 API。
工作流很简单:
- Bright Data 网络解锁器 API 检索目标页面,并以 Markdown 格式返回其内容。
- Kimi K3 接收 Markdown 内容,并通过 Kimi API 收集产品信息。
- 提取出的数据会根据预定义 schema 以结构化 JSON 形式返回。
- 抓取到的产品数据会导出到磁盘。
请按照下面的说明操作!
先决条件
开始之前,请确保你具备:
- 本地已安装 Python 3.10+。
- 一个已充值的 Kimi 账户,并且已配置 API key。
- 一个Bright Data 账户并已配置网络解锁器 API 区域。请按照官方网络解锁器文档设置你的网络解锁器 API 区域。
这里,我们假设你的网络解锁器 API 区域名为 web_unlocker:

第 1 步:初始化你的 Python 项目
首先,为你的 Kimi 网页抓取项目创建一个新文件夹:
mkdir kimi-scraper
kimi-scraper 目录将作为使用 Kimi 进行网页抓取的项目文件夹。
进入该文件夹,并在其中创建一个 Python 虚拟环境:
cd kimi-scraper
python -m venv .venv
将项目文件夹加载到你喜欢的 Python IDE 中,例如带 Python 扩展的 Visual Studio Code 或 PyCharm Community Edition。
在项目文件夹中,创建一个 scraper.py 文件:
kimi-scraper
├─── .venv/
└─── scraper.py # <-----
scraper.py 很快将包含通过 Kimi 进行 LLM 网页抓取的 Python 逻辑。
接下来,在终端中激活虚拟环境。在 Linux 或 macOS 上,运行:
source .venv/bin/activate
同样,在 Windows 上,执行:
.venv\Scripts\activate
激活虚拟环境后,使用以下命令安装所有项目依赖项:
pip install dotenv requests openai pydantic
所需的包包括:
dotenv:用于从.env文件读取 API 密钥。requests:用于向 Bright Data 网络解锁器 API 发送网页检索请求。openai:用于连接到兼容 OpenAI 的 Kimi API,并处理检索到的网页。pydantic:用于为网页抓取 Kimi 请求定义输出模型。
很好!你现在已经有了一个用于通过 Kimi 进行网页抓取的 Python 项目。
第 2 步:设置环境变量读取
你的 Kimi 网页爬虫工具将连接到第三方服务,包括 Bright Data 和 Kimi。这些服务使用 API 密钥进行身份验证,你绝不应该在源代码中硬编码这类密钥。
相反,应将你的 API 密钥存储在环境文件中,并在运行时加载它们。为此,请使用 python-dotenv 包从 .env 文件读取环境变量。
在 scraper.py 中,导入 load_dotenv() 并调用它:
from dotenv import load_dotenv
# Load the environment variables from the .env file
load_dotenv()
然后,在你的项目文件夹中添加一个 .env 文件:
kimi-scraper
├─── .venv/
├─── .env # <-----
└─── scraper.py
用你的 API 密钥填充它:
MOONSHOT_API_KEY="<YOUR_MOONSHOT_API_KEY>"
BRIGHT_DATA_API_KEY="<YOUR_BRIGHT_DATA_API_KEY>"
替换:
- 将
<YOUR_MOONSHOT_API_KEY>替换为你的 Kimi API 密钥。 - 将
<YOUR_BRIGHT_DATA_API_KEY>替换为你的 Bright Data API 密钥。
接下来,使用 Python 的 os.getenv() 读取这些环境变量:
import os
MOONSHOT_API_KEY = os.environ.get("MOONSHOT_API_KEY")
BRIGHT_DATA_API_KEY = os.environ.get("BRIGHT_DATA_API_KEY")
很好!你的 API 密钥现在可以供爬虫工具使用,而不会暴露出来。
提示:在使用版本控制的仓库中,将 .env 添加到你的 .gitignore 文件,以防止意外提交 API 密钥。
第 3 步:使用网络解锁器 API 检索目标网页
Kimi 驱动的抓取脚本的第一步,是以针对 LLM 优化的 Markdown 格式获取目标网页。最简单的方式是使用 Bright Data 网络解锁器 API。
要了解如何连接到网络解锁器请参阅官方文档或查看 Bright Data 仓库中的 Python 示例。
使用 requests 库向网络解锁器 API 发送 HTTP POST 请求,并以 Markdown 格式检索目标页面:
import requests
# Set up the authentication headers for Web Unlocker
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {BRIGHT_DATA_API_KEY}"
}
# Define the request payload for the Web Unlocker API call
payload = {
"zone": "web_unlocker", # Replace with your Web Unlocker API name
"url": "https://www.amazon.com/Amazon-Basics-Batteries-Leak-Free-Household/dp/B00NTCH52W/",
"format": "raw",
"country": "us",
"data_format": "markdown" # To get the web page in Markdown
}
# Fetch the unlocked content of the target page
web_unlocker_response = requests.post(
"https://api.brightdata.com/request",
json=payload,
headers=headers
)
markdown_page = web_unlocker_response.text
如果你不熟悉这段代码,请阅读我们的 Python Requests 指南。
注意请求载荷中的 data_format="markdown" 字段。它会告诉网络解锁器 API 以 Markdown 返回网页而不是返回原始 HTML。
如果你打印 markdown_page会得到:

这对应于目标 Amazon 商品页面的 Markdown 表示。
如你所见,网络解锁器通过以下方式替你处理了检索页面时的困难部分:
- 通过 Bright Data 的住宅代理基础设施访问目标 Amazon 页面。
- 处理常见反机器人挑战包括 Amazon CAPTCHA。
- 检索渲染后的页面内容。
- 将页面转换为干净的 Markdown 并返回。
现在,你已经以一种可以传递给 Kimi 的格式获得了页面内容,用于 AI 驱动的数据提取。在此之前,我们先定义 Kimi 将生成的目标输出模型!
第 4 步:定义输出数据模型
Kimi 与其他 LLM 一样,默认返回基于文本的响应。这对于网页抓取并不理想,因为你通常希望将非结构化网页内容转换为结构化数据。
Kimi API 通过 JSON 模式支持结构化输出。这让你可以定义响应结构,并指示模型返回符合该 schema 的数据。
在 Python 中定义 JSON Schema 的最简单方式之一,是使用 Pydantic这是一个常用的数据验证和解析库。Pydantic 让你能够使用 Python 类定义数据的预期结构和类型,然后可将其转换为供 Kimi API 使用的 JSON Schema 对象。
首先,检查目标页面并确定你想收集的字段。对于本教程使用的 Amazon 商品页面,你可以按如下方式定义 Pydantic 模型:
from pydantic import BaseModel, Field
from typing import List, Optional
class Product(BaseModel):
asin: Optional[str] = Field(None, description="The Amazon Standard Identification Number (e.g., B00NTCH52W)")
title: Optional[str] = Field(None, description="The full product title")
brand: Optional[str] = Field(None, description="Brand name (e.g., Amazon Basics)")
price: Optional[float] = Field(None, description="One-time purchase price")
rating: Optional[float] = Field(None, description="Average customer rating out of 5")
review_count: Optional[int] = Field(None, description="Total number of customer reviews")
size_options: Optional[List[str]] = Field(None, description="Available pack sizes or variants")
about_item: Optional[List[str]] = Field(None, description="Bullet points under 'About this item'")
images: Optional[List[str]] = Field(None, description="URLs for product images")
category_path: Optional[List[str]] = Field(None, description="Breadcrumb navigation list")
is_in_stock: Optional[bool] = Field(True, description="Availability status")
此模型将 Amazon 商品页面中最相关的字段映射到带类型的 Python 字段。随后,Kimi K3 会从页面内容中获取对应的值,并以可预测的 JSON Schema 返回。
很好!你现在已经具备了使用 Kimi 进行网页抓取所需的一切。
第 5 步:使用 Kimi 进行数据解析
Kimi API 兼容 OpenAI这意味着你可以使用 OpenAI Python SDK 访问它。你只需要使用你的 Kimi API 密钥(MOONSHOT_API_KEY env)和 Moonshot 的 API 基础 URL 来配置 OpenAI 客户端。
然后,使用 Chat Completions API 将抓取到的 Markdown 内容发送给 Kimi K3,并根据你的 Pydantic schema 提取商品数据:
from openai import OpenAI
# Initialize the OpenAI client for Kimi
kimi_client = OpenAI(
api_key=MOONSHOT_API_KEY,
base_url="https://api.moonshot.ai/v1",
)
# Perform web data parsing with Kimi
response = kimi_client.chat.completions.create(
model="kimi-k3",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text":
f"""
Extract the product information from the following Markdown document
and return it according to the provided schema.
MARKDOWN:
{markdown_page}
""",
},
],
}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "product",
"strict": True,
"schema": Product.model_json_schema(), # Transform the Pydantic schema in a JSON Schema object
},
},
)
# Get the parsed data in the defined schema format
product_data = response.choices[0].message.content
用户提示包含通过 Bright Data 网络解锁器 API 检索到的 Markdown 页面,并指示 Kimi 返回相关商品信息。
response_format 参数启用 json_schema 模式。在这里Product.model_json_schema() 会将 Pydantic 模型转换为 JSON Schema,Kimi 将使用它来组织响应结构。
因此product_data 包含一个 JSON 字符串,其中包含按你的 Product 模型所定义结构提取出的商品数据。最后一步,将这个 JSON 字符串解析为 Python 对象,并将结构化数据保存到磁盘!
第 6 步:导出抓取的数据
使用以下方式将抓取到的商品数据保存为 JSON 文件:
import json
with open("product.json", "w", encoding="utf-8") as f:
json.dump(json.loads(product_data), f, indent=2, ensure_ascii=False)
注意:json.dump(json.loads(...)) 可确保 Kimi 生成的输出是有效 JSON。
这会创建一个 product.json 文件,其中包含 Kimi 根据 Product Pydantic schema 收集到的结构化商品数据。完美!
第 7 步:整合所有内容
下面是你的 Kimi 爬虫工具的最终代码:
# pip install dotenv requests openai pydantic
from dotenv import load_dotenv
import os
import requests
from pydantic import BaseModel, Field
from typing import List, Optional
from openai import OpenAI
import json
# Load the environment variables from the .env file
load_dotenv()
# Loading the required secrets from the envs
MOONSHOT_API_KEY = os.environ.get("MOONSHOT_API_KEY")
BRIGHT_DATA_API_KEY = os.environ.get("BRIGHT_DATA_API_KEY")
# The output schema for the product information
class Product(BaseModel):
asin: Optional[str] = Field(None, description="The Amazon Standard Identification Number (e.g., B00NTCH52W)")
title: Optional[str] = Field(None, description="The full product title")
brand: Optional[str] = Field(None, description="Brand name (e.g., Amazon Basics)")
price: Optional[float] = Field(None, description="One-time purchase price")
rating: Optional[float] = Field(None, description="Average customer rating out of 5")
review_count: Optional[int] = Field(None, description="Total number of customer reviews")
size_options: Optional[List[str]] = Field(None, description="Available pack sizes or variants")
about_item: Optional[List[str]] = Field(None, description="Bullet points under 'About this item'")
images: Optional[List[str]] = Field(None, description="URLs for product images")
category_path: Optional[List[str]] = Field(None, description="Breadcrumb navigation list")
is_in_stock: Optional[bool] = Field(True, description="Availability status")
# Set up the authentication headers for Web Unlocker
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {BRIGHT_DATA_API_KEY}"
}
# Define the request payload for the Web Unlocker API call
payload = {
"zone": "web_unlocker", # Replace with your Web Unlocker API name
"url": "https://www.amazon.com/Amazon-Basics-Batteries-Leak-Free-Household/dp/B00NTCH52W/",
"format": "raw",
"country": "us",
"data_format": "markdown" # To get the web page in Markdown
}
# Fetch the unlocked content of the target page
web_unlocker_response = requests.post(
"https://api.brightdata.com/request",
json=payload,
headers=headers
)
markdown_page = web_unlocker_response.text
# Initialize the OpenAI client for Kimi
kimi_client = OpenAI(
api_key=MOONSHOT_API_KEY,
base_url="https://api.moonshot.ai/v1",
)
# Perform web data parsing with Kimi
response = kimi_client.chat.completions.create(
model="kimi-k3",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text":
f"""
Extract the product information from the following Markdown document
and return it according to the provided schema.
MARKDOWN:
{markdown_page}
""",
},
],
}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "product",
"strict": True,
"schema": Product.model_json_schema(), # Transform the Pydantic schema in a JSON Schema object
},
},
)
# Get the parsed data in the defined schema format
product_data = response.choices[0].message.content
# Export the scraped data to a JSON file
with open("product.json", "w", encoding="utf-8") as f:
json.dump(json.loads(product_data), f, indent=2, ensure_ascii=False)
使用以下命令执行 Python 脚本:
python scraper.py
从使用网络解锁器 API 检索页面,到用 Kimi LLM 处理页面,整个执行过程需要一些时间。所以,请耐心等待。
结果将是一个 product.json 文件,其中包含 Kimi 返回的抓取商品数据:

注意,提取的数据与目标 Amazon 商品页面上可见的信息高度一致:

网络解锁器 API 处理了 Amazon 的反机器人措施,并检索了针对 LLM 优化的 Markdown 页面内容,而 Kimi K3 成功解析了这些内容并将其转换为结构化数据。任务完成!
如何利用 Kimi K3 视觉能力执行可视化网页抓取
Kimi K3 也是一个视觉模型这意味着它可以执行可视化网页抓取。你可以不向 LLM 提供网页的文本内容,而是提供截图或图像,并让 Kimi K3 从中提取结构化数据。
同样,方法很简单:
- Bright Data 网络解锁器 API 检索目标网页的截图(与之前相同的 Amazon 商品页面)。
- Kimi K3 通过 Kimi API 接收截图,并根据预定义 schema 收集商品信息。
- 抓取的数据以结构化 JSON 保存到磁盘。
注意:大部分工作流保持不变,因此本节只介绍为了实现可视化网页抓取而需要更新的步骤。前面描述的所有前提条件和设置步骤仍然适用。
第 1 步:检索页面截图
更新网络解锁器 API 请求,使其返回截图,而不是 Markdown 格式的页面内容:
# Set up the authentication headers for Web Unlocker
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {BRIGHT_DATA_API_KEY}"
}
# Define the request payload for the Web Unlocker API call
payload = {
"zone": "web_unlocker", # Replace with your Web Unlocker API name
"url": "https://www.amazon.com/Amazon-Basics-Batteries-Leak-Free-Household/dp/B00NTCH52W/",
"format": "raw",
"country": "us",
"data_format": "screenshot" # <----- To get the screenshot of the web page
}
# Fetch the unlocked content of the target page
web_unlocker_response = requests.post(
"https://api.brightdata.com/request",
json=payload,
headers=headers
)
page_screenshot = web_unlocker_response.content
关键变化是 data_format 字段,现在它被设置为 "screenshot"。这会告诉网络解锁器 API 返回截图。具体来说,API 响应将包含以 PNG 图像字节形式表示的截图,代表完整渲染后的页面。
为了进行可视化调试,将截图导出到磁盘:
with open("screenshot.png", "wb") as f:
f.write(page_screenshot)
这一步是可选的,但有助于直观检查检索到的页面,并排查 Kimi 抓取工作流中的问题。
结果是一个 screenshot.png 文件:

注意,其中包含由 Bright Data 网络解锁器 API 捕获的整个 Amazon 商品页面截图。开始吧!
第 2 步:更新 Pydantic 模型
通过分析目标页面的截图,Kimi K3 可以检索页面 Markdown 内容中不可用的视觉信息。例如,它可以读取嵌入在图像中的文本,比如“From the manufacturer”部分中的文本:

与此同时,截图不会提供底层图片 URL。因此,像 images 这样的字段在之前基于文本的 Kimi K3 爬虫工作流中可用,但在这里无法填充。
因此,请像这样调整 Product Pydantic 模型:
class Product(BaseModel):
asin: Optional[str] = Field(None, description="The Amazon Standard Identification Number (e.g., B00NTCH52W)")
title: Optional[str] = Field(None, description="The full product title")
brand: Optional[str] = Field(None, description="Brand name (e.g., Amazon Basics)")
price: Optional[float] = Field(None, description="One-time purchase price")
rating: Optional[float] = Field(None, description="Average customer rating out of 5")
review_count: Optional[int] = Field(None, description="Total number of customer reviews")
size_options: Optional[List[str]] = Field(None, description="Available pack sizes or variants")
from_the_manufacturer_info: Optional[str] = Field(None, description="Text of the image in the 'From the manufacturer' section")
category_path: Optional[List[str]] = Field(None, description="Breadcrumb navigation list")
is_in_stock: Optional[bool] = Field(True, description="Availability status")
注意新的 from_the_manufacturer_info 字段。它会明确指示 Kimi 读取并提取商品页面“From the manufacturer”部分中图像内显示的文本。
太好了!将新的 Pydantic 模型和网页截图传递给 Kimi API,用于网页抓取。
第 3 步:使用 Kimi K3 Vision 从图像中抓取数据
Kimi 通过 image_url 类型接收图像该类型支持可公开访问的图像 URL,也支持图像的 Base64 编码表示。
由于截图以图像字节的形式存储在本地,你首先需要将其编码为 Base64。可以使用 Python 标准库中的 base64 包来完成:
import base64
screenshot_base64 = base64.b64encode(page_screenshot).decode("utf-8")
然后,你可以将编码后的截图连同提取提示词一起传给 Kimi K3:
response = kimi_client.chat.completions.create(
model="kimi-k3",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": (
f"data:image/png;base64,{screenshot_base64}"
),
},
},
{
"type": "text",
"text":
"""
Extract the product information from this Amazon product page screenshot.
Return the information according to the provided schema.
""",
},
],
}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "product",
"strict": True,
"schema": Product.model_json_schema(), # Transform the Pydantic schema in a JSON Schema object
},
},
)
# Get the parsed data in the defined schema format
product_data = response.choices[0].message.content
该请求包含两部分信息:
- 页面截图。
- 一段文本提示词,指示 Kimi 使用指定的 Pydantic schema 提取产品信息。
结果是一个 product_data 变量,其中包含带有通过视觉抓取到的产品信息的 JSON 字符串。你可以使用上一节中描述的相同方法将其保存到磁盘。就是这样!
第 4 步:测试视觉 AI 爬虫工具
你的 Kimi 视觉网页抓取脚本将包含:
# pip install dotenv requests openai pydantic
import os
import requests
from pydantic import BaseModel, Field
from typing import List, Optional
from dotenv import load_dotenv
from openai import OpenAI
import base64
import json
# Load the environment variables from the .env file
load_dotenv()
# Loading the required secrets from the envs
MOONSHOT_API_KEY = os.environ.get("MOONSHOT_API_KEY")
BRIGHT_DATA_API_KEY = os.environ.get("BRIGHT_DATA_API_KEY")
# The output schema for the product information
class Product(BaseModel):
asin: Optional[str] = Field(None, description="The Amazon Standard Identification Number (e.g., B00NTCH52W)")
title: Optional[str] = Field(None, description="The full product title")
brand: Optional[str] = Field(None, description="Brand name (e.g., Amazon Basics)")
price: Optional[float] = Field(None, description="One-time purchase price")
rating: Optional[float] = Field(None, description="Average customer rating out of 5")
review_count: Optional[int] = Field(None, description="Total number of customer reviews")
size_options: Optional[List[str]] = Field(None, description="Available pack sizes or variants")
from_the_manufacturer_info: Optional[str] = Field(None, description="Text of the image in the 'From the manufacturer' section")
category_path: Optional[List[str]] = Field(None, description="Breadcrumb navigation list")
is_in_stock: Optional[bool] = Field(True, description="Availability status")
# Set up the authentication headers for Web Unlocker
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {BRIGHT_DATA_API_KEY}"
}
# Define the request payload for the Web Unlocker API call
payload = {
"zone": "web_unlocker", # Replace with your Web Unlocker zone name
"url": "https://www.amazon.com/Amazon-Basics-Batteries-Leak-Free-Household/dp/B00NTCH52W/",
"format": "raw",
"country": "us",
"data_format": "screenshot" # To get the screenshot of the web page
}
# Fetch the unlocked content of the target page
web_unlocker_response = requests.post(
"https://api.brightdata.com/request",
json=payload,
headers=headers
)
page_screenshot = web_unlocker_response.content
# Export the screenshot to a PNG file
with open("screenshot.png", "wb") as f:
f.write(page_screenshot)
# Convert the screenshot to base64 for Kimi processing
screenshot_base64 = base64.b64encode(page_screenshot).decode("utf-8")
# Initialize the OpenAI client for Kimi
kimi_client = OpenAI(
api_key=MOONSHOT_API_KEY,
base_url="https://api.moonshot.ai/v1",
)
# Perform visual web data parsing with Kimi
response = kimi_client.chat.completions.create(
model="kimi-k3",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": (
f"data:image/png;base64,{screenshot_base64}"
),
},
},
{
"type": "text",
"text":
"""
Extract the product information from this Amazon product page screenshot.
Return the information according to the provided schema.
""",
},
],
}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "product",
"strict": True,
"schema": Product.model_json_schema(), # Transform the Pydantic schema in a JSON Schema object
},
},
)
# Get the parsed data in the defined schema format
product_data = response.choices[0].message.content
# Export the scraped data to a JSON file
with open("image_product.json", "w", encoding="utf-8") as f:
json.dump(json.loads(product_data), f, indent=2, ensure_ascii=False)
启动它,它将生成一个 image_product.json 文件,内容如下:

可以看到,Kimi K3 从截图中检索到了产品数据,包括“来自制造商”图片中嵌入的文本。太棒了!
结论
在这篇博客文章中,你学习了如何使用 Kimi K3 构建由 AI 驱动的网页爬虫工具。最大的挑战,也就是可靠地检索网页内容并获取针对 LLM 优化的数据且不被封锁,已经通过 Bright Data 的网络解锁器 API 得到解决。
如前所述,将 Kimi K3 与网络解锁器 API 结合使用,可以让你通过简单的提示词从网页或页面截图中提取结构化数据,而无需编写自定义解析逻辑。这只是 Bright Data 的 AI 就绪服务支持的众多用例之一。
注册 Bright Data,开始免费试用我们的网页爬虫 API!