搜索
首页后端开发Python教程使用 Pydantic、Crawl 和 Gemini 构建异步电子商务网络爬虫

Building an Async E-Commerce Web Scraper with Pydantic, Crawl & Gemini

简而言之: 本指南演示了如何使用crawl4ai 的人工智能提取和 Pydantic 数据模型构建电子商务抓取工具。 抓取工具异步检索产品列表(名称、价格)和详细的产品信息(规格、评论)。

在 Google Colab 上访问完整代码


厌倦了电子商务数据分析的传统网络抓取的复杂性?本教程使用现代 Python 工具简化了该过程。我们将利用 crawl4ai 进行智能数据提取,并利用 Pydantic 进行稳健的数据建模和验证。

为什么选择 Crawl4AI 和 Pydantic?

  • crawl4ai:使用人工智能驱动的提取方法简化网络爬行和抓取。
  • Pydantic:提供数据验证和模式管理,确保抓取的数据结构化且准确。

为什么瞄准 Tokopedia?

印尼主要电商平台Tokopedia就是我们的例子。 (注:作者是印度尼西亚人,也是该平台的用户,但不隶属于该平台。)这些原则适用于其他电子商务网站。 这种抓取方法对于对电子商务分析、市场研究或自动数据收集感兴趣的开发人员来说是有益的。

是什么让这种方法与众不同?

我们不依赖复杂的CSS选择器或XPath,而是利用crawl4ai基于LLM的提取。这提供:

  • 增强了对网站结构变化的适应能力。
  • 更清晰、更结构化的数据输出。
  • 减少维护开销。

设置您的开发环境

首先安装必要的软件包:

%pip install -U crawl4ai
%pip install nest_asyncio
%pip install pydantic

对于笔记本中的异步代码执行,我们还将使用 nest_asyncio:

import crawl4ai
import asyncio
import nest_asyncio
nest_asyncio.apply()

使用 Pydantic 定义数据模型

我们使用 Pydantic 来定义预期的数据结构。 以下是型号:

from pydantic import BaseModel, Field
from typing import List, Optional

class TokopediaListingItem(BaseModel):
    product_name: str = Field(..., description="Product name from listing.")
    product_url: str = Field(..., description="URL to product detail page.")
    price: str = Field(None, description="Price displayed in listing.")
    store_name: str = Field(None, description="Store name from listing.")
    rating: str = Field(None, description="Rating (1-5 scale) from listing.")
    image_url: str = Field(None, description="Primary image URL from listing.")

class TokopediaProductDetail(BaseModel):
    product_name: str = Field(..., description="Product name from detail page.")
    all_images: List[str] = Field(default_factory=list, description="List of all product image URLs.")
    specs: str = Field(None, description="Technical specifications or short info.")
    description: str = Field(None, description="Long product description.")
    variants: List[str] = Field(default_factory=list, description="List of variants or color options.")
    satisfaction_percentage: Optional[str] = Field(None, description="Customer satisfaction percentage.")
    total_ratings: Optional[str] = Field(None, description="Total number of ratings.")
    total_reviews: Optional[str] = Field(None, description="Total number of reviews.")
    stock: Optional[str] = Field(None, description="Stock availability.")

这些模型充当模板,确保数据验证并提供清晰的文档。

抓取过程

刮刀分两个阶段运行:

1.抓取产品列表

首先,我们检索搜索结果页面:

async def crawl_tokopedia_listings(query: str = "mouse-wireless", max_pages: int = 1):
    # ... (Code remains the same) ...

2.正在获取产品详细信息

接下来,对于每个产品 URL,我们获取详细信息:

async def crawl_tokopedia_detail(product_url: str):
    # ... (Code remains the same) ...

结合各个阶段

最后,我们整合两个阶段:

async def run_full_scrape(query="mouse-wireless", max_pages=2, limit=15):
    # ... (Code remains the same) ...

运行爬虫

执行抓取工具的方法如下:

%pip install -U crawl4ai
%pip install nest_asyncio
%pip install pydantic

专业提示

  1. 速率限制:尊重 Tokopedia 的服务器;在大规模抓取请求之间引入延迟。
  2. 缓存:在开发过程中启用crawl4ai的缓存(cache_mode=CacheMode.ENABLED)。
  3. 错误处理:为生产使用实现全面的错误处理和重试机制。
  4. API 密钥: 将 Gemini API 密钥安全地存储在环境变量中,而不是直接存储在代码中。

后续步骤

这个刮刀可以扩展到:

  • 将数据存储在数据库中。
  • 监控价格随时间的变化。
  • 分析产品趋势和模式。
  • 比较多家商店的价格。

结论

crawl4ai 基于 LLM 的提取与传统方法相比显着提高了网页抓取的可维护性。 与 Pydantic 的集成确保了数据的准确性和结构。

在抓取之前始终遵守网站的robots.txt和服务条款。


重要链接:

爬行4AI

皮丹蒂克


注意:完整的代码可以在Colab笔记本中找到。 请随意尝试并根据您的具体需求进行调整。

以上是使用 Pydantic、Crawl 和 Gemini 构建异步电子商务网络爬虫的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器