youtube_crawler.py
13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
"""
YouTube Trending Video Crawler
使用 YouTube Data API v3 获取热门视频数据
Usage:
from youtube_crawler import YouTubeTrendingCrawler
crawler = YouTubeTrendingCrawler()
result = crawler.get_trending(region_code="US", max_results=10)
Requires:
pip install requests urllib3
export YOUTUBE_API_KEY="your_api_key_here"
"""
import os
import json
import csv
import time
import logging
from datetime import datetime
from typing import List, Dict, Optional, Union
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class YouTubeTrendingCrawler:
"""
YouTube 热门视频爬虫
使用 YouTube Data API v3 获取当日最热门视频列表
Attributes:
api_key: YouTube Data API Key
quota_used: 已使用的 API 配额
session: 带重试机制的 HTTP session
"""
# API 端点
API_BASE_URL = "https://www.googleapis.com/youtube/v3"
# 视频分类映射
VIDEO_CATEGORIES = {
1: "Film & Animation",
2: "Autos & Vehicles",
10: "Music",
17: "Sports",
20: "Gaming",
22: "People & Blogs",
23: "Comedy",
24: "Entertainment",
25: "News & Politics",
27: "Education",
28: "Science & Technology",
}
# 常见地区代码
REGION_CODES = ["US", "JP", "KR", "CN", "GB", "DE", "FR", "IN", "BR", "RU"]
def __init__(self, api_key: Optional[str] = None):
"""
初始化爬虫
Args:
api_key: YouTube Data API Key,默认从环境变量 YOUTUBE_API_KEY 读取
Raises:
ValueError: 当 API Key 未提供时
"""
self.api_key = api_key or os.getenv("YOUTUBE_API_KEY")
if not self.api_key:
raise ValueError(
"API Key 未提供。请传入 api_key 参数或设置 YOUTUBE_API_KEY 环境变量"
)
# 创建带重试机制的 session
self.session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.session.mount("https://", adapter)
# 配额使用统计
self.quota_used = 0
def _make_request(self, endpoint: str, params: Dict) -> Dict:
"""
发送 API 请求
Args:
endpoint: API 端点路径
params: 请求参数
Returns:
API 响应数据 (JSON)
Raises:
ValueError: API 错误或网络错误
"""
url = f"{self.API_BASE_URL}/{endpoint}"
params["key"] = self.api_key
try:
response = self.session.get(url, params=params, timeout=30)
# 处理特定错误码
if response.status_code == 403:
error_data = response.json()
error_reason = error_data.get("error", {}).get("errors", [{}])[0].get("reason", "")
if error_reason == "quotaExceeded":
raise ValueError("API 配额已耗尽,请明日再试或申请更高配额")
elif error_reason in ["keyInvalid", "badRequest"]:
raise ValueError(f"API Key 无效: {error_reason}")
else:
raise ValueError(f"访问被拒绝: {error_reason}")
elif response.status_code == 429:
logger.warning("触发速率限制,等待后重试...")
time.sleep(5)
params_copy = {k: v for k, v in params.items() if k != "key"}
return self._make_request(endpoint, params_copy)
response.raise_for_status()
# 统计配额使用
self.quota_used += 1
return response.json()
except requests.exceptions.Timeout:
raise ValueError("请求超时,请检查网络连接")
except requests.exceptions.ConnectionError:
raise ValueError("网络连接错误,请检查网络设置")
except requests.exceptions.RequestException as e:
raise ValueError(f"请求失败: {str(e)}")
def get_trending(
self,
region_code: str = "US",
category_id: Optional[int] = None,
max_results: int = 50,
page_token: Optional[str] = None
) -> Dict:
"""
获取指定地区的热门视频
Args:
region_code: ISO 3166-1 alpha-2 地区代码,如 US, JP, KR
category_id: 视频分类 ID (可选)
max_results: 返回结果数量 (1-50)
page_token: 分页令牌 (可选)
Returns:
包含视频列表和分页信息的字典:
{
"region_code": str,
"category_id": Optional[int],
"videos": List[Dict],
"total_results": int,
"next_page_token": Optional[str],
"quota_used": int
}
"""
if not 1 <= max_results <= 50:
raise ValueError("max_results 必须在 1-50 之间")
params = {
"part": "snippet,statistics,contentDetails",
"chart": "mostPopular",
"regionCode": region_code,
"maxResults": max_results,
}
if category_id:
params["videoCategoryId"] = category_id
if page_token:
params["pageToken"] = page_token
logger.info(f"获取 {region_code} 地区热门视频 (category={category_id or 'all'})")
data = self._make_request("videos", params)
videos = []
for item in data.get("items", []):
video_info = self.extract_video_info(item)
if video_info:
videos.append(video_info)
return {
"region_code": region_code,
"category_id": category_id,
"videos": videos,
"total_results": len(videos),
"next_page_token": data.get("nextPageToken"),
"quota_used": self.quota_used,
}
def extract_video_info(self, item: Dict) -> Optional[Dict]:
"""
从 API 响应中提取视频信息
Args:
item: API 返回的单个视频数据
Returns:
标准化的视频信息字典,或 None (解析失败时)
"""
try:
video_id = item.get("id")
snippet = item.get("snippet", {})
statistics = item.get("statistics", {})
thumbnails = snippet.get("thumbnails", {})
return {
"videoId": video_id,
"url": f"https://youtube.com/watch?v={video_id}",
"title": snippet.get("title", ""),
"description": snippet.get("description", ""),
"channelTitle": snippet.get("channelTitle", ""),
"channelId": snippet.get("channelId", ""),
"publishedAt": snippet.get("publishedAt", ""),
"categoryId": snippet.get("categoryId", ""),
"categoryName": self.VIDEO_CATEGORIES.get(
int(snippet.get("categoryId", 0)), "Unknown"
),
"viewCount": int(statistics.get("viewCount", 0)),
"likeCount": int(statistics.get("likeCount", 0)) if statistics.get("likeCount") else 0,
"commentCount": int(statistics.get("commentCount", 0)) if statistics.get("commentCount") else 0,
"duration": item.get("contentDetails", {}).get("duration", ""),
"thumbnails": {
"default": thumbnails.get("default", {}).get("url", ""),
"medium": thumbnails.get("medium", {}).get("url", ""),
"high": thumbnails.get("high", {}).get("url", ""),
"standard": thumbnails.get("standard", {}).get("url", ""),
"maxres": thumbnails.get("maxres", {}).get("url", ""),
},
"tags": snippet.get("tags", []),
"liveBroadcastContent": snippet.get("liveBroadcastContent", "none"),
}
except Exception as e:
logger.warning(f"解析视频数据失败: {str(e)}")
return None
def get_multi_region_trending(
self,
regions: List[str],
category_id: Optional[int] = None,
max_results: int = 50
) -> Dict[str, Dict]:
"""
批量获取多个地区的热门视频
高效使用配额:每个地区仅消耗 1 unit
Args:
regions: 地区代码列表,如 ["US", "JP", "KR"]
category_id: 视频分类 ID (可选)
max_results: 每个地区返回结果数量
Returns:
以地区代码为键的结果字典
"""
results = {}
logger.info(f"开始批量获取 {len(regions)} 个地区的热门视频")
for region in regions:
try:
result = self.get_trending(
region_code=region,
category_id=category_id,
max_results=max_results
)
results[region] = result
time.sleep(0.5) # 请求间隔
except Exception as e:
logger.error(f"获取 {region} 地区数据失败: {str(e)}")
results[region] = {"error": str(e), "videos": []}
logger.info(f"批量获取完成,总配额使用: {self.quota_used} units")
return results
def save_to_json(
self,
data: Union[Dict, List],
filepath: Optional[str] = None,
region: Optional[str] = None
) -> str:
"""
保存数据为 JSON 文件
Args:
data: 要保存的数据
filepath: 文件路径 (可选)
region: 地区代码 (用于生成文件名)
Returns:
保存的文件路径
"""
if filepath is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
region_suffix = f"_{region}" if region else ""
filepath = f"youtube_trending{region_suffix}_{timestamp}.json"
os.makedirs(os.path.dirname(filepath) if os.path.dirname(filepath) else ".", exist_ok=True)
with open(filepath, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
logger.info(f"数据已保存到: {filepath}")
return filepath
def save_to_csv(
self,
videos: List[Dict],
filepath: Optional[str] = None,
region: Optional[str] = None
) -> str:
"""
保存视频列表为 CSV 文件
Args:
videos: 视频数据列表
filepath: 文件路径 (可选)
region: 地区代码 (用于生成文件名)
Returns:
保存的文件路径
"""
if filepath is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
region_suffix = f"_{region}" if region else ""
filepath = f"youtube_trending{region_suffix}_{timestamp}.csv"
os.makedirs(os.path.dirname(filepath) if os.path.dirname(filepath) else ".", exist_ok=True)
if not videos:
logger.warning("没有数据可保存")
return filepath
fieldnames = [
"videoId", "url", "title", "channelTitle", "channelId",
"viewCount", "likeCount", "commentCount", "publishedAt",
"categoryId", "categoryName", "duration", "thumbnail_high"
]
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for video in videos:
row = {
"videoId": video.get("videoId", ""),
"url": video.get("url", ""),
"title": video.get("title", ""),
"channelTitle": video.get("channelTitle", ""),
"channelId": video.get("channelId", ""),
"viewCount": video.get("viewCount", 0),
"likeCount": video.get("likeCount", 0),
"commentCount": video.get("commentCount", 0),
"publishedAt": video.get("publishedAt", ""),
"categoryId": video.get("categoryId", ""),
"categoryName": video.get("categoryName", ""),
"duration": video.get("duration", ""),
"thumbnail_high": video.get("thumbnails", {}).get("high", ""),
}
writer.writerow(row)
logger.info(f"CSV 数据已保存到: {filepath}")
return filepath
def get_quota_status(self) -> Dict:
"""
获取配额使用状态
Returns:
配额使用信息字典
"""
return {
"quota_used": self.quota_used,
"quota_limit": 10000,
"quota_remaining": 10000 - self.quota_used,
"usage_percentage": (self.quota_used / 10000) * 100,
}
if __name__ == "__main__":
# 简单的自测
print("YouTube Trending Crawler 模块加载成功")
print(f"支持的分类: {list(YouTubeTrendingCrawler.VIDEO_CATEGORIES.keys())}")