
如何用 Python 抓取 Apple App Store 应用评论与应用数据
来源标题:How to Scrape Apple App Store Reviews and App Data
文章介绍通过 Apple 的 iTunes Lookup、RSS 订阅和 userReviewsRow 三个 JSON 接口,用 Python 抓取 App Store 的评分、星级分布和用户评论。以 ChatGPT 为例,单次 Lookup 请求可获取 37 个元数据字段,RSS 源可返回 500 条评论。方案基于 Scrapfly 已有的 App Store 抓取器,并补充其缺失的评论抓取代码。
以下正文由 AI 翻译自 Hacker News 最新(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。
App Store 最广为人知的是它的应用列表,但它还包含大量公开数据,比如评分、星级分布和用户评论,其中大部分都在 Apple 自己的 JSON 端点里。 以 ChatGPT 为例——一次 iTunes Lookup 请求就给了我们它的 37 个元数据字段,RSS feed 给了我们 500 条评论,而 userReviewsRow 则获取到了 2024 年 11 月的评论。这就是我们用来抓取 apps.apple.com 的三个端点,用 Python 实现,从 Scrapfly 维护的 App Store 抓取器出发,补上它尚未包含的评论代码,那么让我们开始吧! pip install scrapfly-sdk parsel loguru httpx export SCRAPFLY_KEY="YOUR_SCRAPFLY_KEY" 接着,我们创建一个 Scrapfly 客户端和一个基础配置,抓取器中的每个请求都共享这套配置。这里,unblocker 启用 Scrapfly 的 Unblocker(原 ASP),而 country 将我们的出口 IP 固定到美国: import json import os import re from typing import Dict, List, Optional from loguru import logger as log from scrapfly import ScrapeConfig, ScrapflyClient, ScrapeApiResponse, ScrapflyError SCRAPFLY = ScrapflyClient(key=os.environ["SCRAPFLY_KEY"]) BASE_CONFIG = { "unblocker": True, "country": "US", 注意,深度评论部分是唯一的例外,因为它用普通的 httpx 直接调用 Apple,而不是用这个客户端。 以下是 Apple 的六个来源分别为 ChatGPT 提供的内容: 要抓取 App Store 数据,我们只需要一个应用 ID 和一个国家店面,而应用 URL 已经同时包含这两个值。例如,位于 https://apps.apple.com/us/app/chatgpt/id6448311069 的 ChatGPT 应用,其国家(us)在 /app/ 之前的两位字母段中,应用 ID(6448311069)在 id 之后的数字中。 中间的 chatgpt slug 是给人类读者看的,因为 Apple 的端点都不需要它——它们只认 6448311069。也就是说,即使应用被改名,我们的抓取器依然能正常工作! 我们抓取器的第一个函数 parse_app_url,从完整的应用 URL 中读出这两个值,也接受单独的数字 ID: def parse_app_url(value: str) -> tuple[str, str]: """Return (app_id, country) from an App Store URL or a bare numeric app ID.""" if value.isdigit(): return value, "us" match = re.search(r"apps.apple.com/([a-z]{2})/app/[^/]+/id(\d+)", value) if not match: raise ValueError(f"not an App Store app URL: {value}") return match.group(2), match.group(1) print(parse_app_url("https://apps.apple.com/us/app/chatgpt/id6448311069")) print(parse_app_url("6448311069")) python('6448311069', 'us') ('6448311069', 'us') 两次调用都打印出 ('6448311069', 'us'),不过只有第一次是从 URL 中读出 us 的——对于纯 ID,我们的辅助函数自己返回 us,与抓取器的 country="us" 是同一个默认值。此外,任何不是全数字且不匹配我们正则表达式的值都会抛出 ValueError。 从这里开始,这两个值会进入每一个请求,所以先来看看我们如何用它们来获取应用元数据。 要抓取应用元数据,我们可以使用 iTunes Lookup 端点——https://itunes.apple.com/lookup,它接收应用的 id 和店面国家代码。这两个值直接进入 lookup_url 的查询字符串: def parse_app_metadata(response: ScrapeApiResponse, app_id: str, country: str) -> Dict: """parse app metadata from the iTunes lookup API""" data = json.loads(response.content) if not data.get("resultCount"): raise ValueError(f"App {app_id} not found in {country} storefront") app = data["results"][0] price = app.get("price") or 0 return { "appId": str(app.get("trackId", app_id)), "bundleId": app.get("bundleId"), "title": app.get("trackName"), "description": app.get("description"), "summary": app.get("releaseNotes"), "developer": app.get("artistName"), "developerId": app.get("artistId"), "developerUrl": app.get("artistViewUrl"), "seller": app.get("sellerName"), "sellerUrl": app.get("sellerUrl"), "genre": app.get("primaryGenreName"), "genres": app.get("genres", []), "genreIds": app.get("genreIds", []), "price": price, "free": price == 0, "currency": app.get("currency"), "formattedPrice": app.get("formattedPrice"), "score": app.get("averageUserRating"), "scoreCurrentVersion": app.get("averageUserRatingForCurrentVersion"), "ratings": app.get("userRatingCount"), "ratingsCurrentVersion": app.get("userRatingCountForCurrentVersion"), "version": app.get("version"), "released": app.get("releaseDate"), "updated": app.get("currentVersionReleaseDate"), "contentRating": app.get("contentAdvisoryRating") or app.get("trackContentRating"), "minimumOsVersion": app.get("minimumOsVersion"), "fileSizeBytes": app.get("fileSizeBytes"), "languages": app.get("languageCodesISO2A", []), "icon": app.get("artworkUrl512") or app.get("artworkUrl100"), "screenshots": app.get("screenshotUrls", []), "ipadScreenshots": app.get("ipadScreenshotUrls", []), "appletvScreenshots": app.get("appletvScreenshotUrls", []), "supportedDevices": app.get("supportedDevices", []), "advisories": app.get("advisories", []), "features": app.get("features", []), "url": app.get("trackViewUrl"), "country": country.lower(), async def scrape_app_metadata(app_id: str, country: str = "us") -> Dict: """scrape app metadata via the iTunes lookup API, falling back to the apps.apple.com page""" lookup_url = f"https://itunes.apple.com/lookup?id={app_id}&country={country}" response = await SCRAPFLY.async_scrape(ScrapeConfig(lookup_url, **BASE_CONFIG)) try: metadata = parse_app_metadata(response, app_id, country) except: log.info("no iTunes data for {}, falling back to apps.apple.com", app_id) page_url = f"https://apps.apple.com/{country}/app/id{app_id}" response = await SCRAPFLY.async_scrape(ScrapeConfig(page_url, **BASE_CONFIG)) metadata = parse_app_metadata_from_page(response, app_id, country) log.success("scraped metadata for {} ({})", metadata["title"], app_id) return metadata
(原文较长,此处译出前 6000 字,完整内容请点「打开原文」。)
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。