| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2019-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Extractors for https://www.weibo.com/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message, Dispatch |
| 12 |
from .. import text, util |
| 13 |
import random |
| 14 |
|
| 15 |
BASE_PATTERN = r"(?:https?://)?(?:www\.|m\.)?weibo\.c(?:om|n)" |
| 16 |
USER_PATTERN = BASE_PATTERN + r"/(?:(u|n|p(?:rofile)?)/)?([^/?#]+)(?:/home)?" |
| 17 |
|
| 18 |
|
| 19 |
class WeiboExtractor(Extractor): |
| 20 |
category = "weibo" |
| 21 |
directory_fmt = ("{category}", "{user[screen_name]}") |
| 22 |
filename_fmt = "{status[id]}_{num:>02}.{extension}" |
| 23 |
archive_fmt = "{status[id]}_{num}" |
| 24 |
cookies_domain = ".weibo.com" |
| 25 |
cookies_names = ("SUB", "SUBP") |
| 26 |
root = "https://weibo.com" |
| 27 |
request_interval = (1.0, 2.0) |
| 28 |
|
| 29 |
def __init__(self, match): |
| 30 |
Extractor.__init__(self, match) |
| 31 |
self._prefix = match[1] |
| 32 |
self.user = match[2] |
| 33 |
|
| 34 |
def _init(self): |
| 35 |
self.livephoto = self.config("livephoto", True) |
| 36 |
self.retweets = self.config("retweets", False) |
| 37 |
self.longtext = self.config("text", False) |
| 38 |
self.videos = self.config("videos", True) |
| 39 |
self.movies = self.config("movies", False) |
| 40 |
self.likes = self.config("likes", False) |
| 41 |
self.gifs = self.config("gifs", True) |
| 42 |
self.gifs_video = (self.gifs == "video") |
| 43 |
|
| 44 |
cookies = self.cache( |
| 45 |
_cookie_cache, _key=None, _exp=365*86400, _mem=False) |
| 46 |
if cookies is None: |
| 47 |
self.logged_in = self.cookies_check( |
| 48 |
self.cookies_names, self.cookies_domain) |
| 49 |
return |
| 50 |
|
| 51 |
domain = self.cookies_domain |
| 52 |
cookies = {c.name: c for c in cookies if c.domain == domain} |
| 53 |
for cookie in self.cookies: |
| 54 |
if cookie.domain == domain and cookie.name in cookies: |
| 55 |
del cookies[cookie.name] |
| 56 |
if not cookies: |
| 57 |
self.logged_in = True |
| 58 |
return |
| 59 |
|
| 60 |
self.logged_in = False |
| 61 |
for cookie in cookies.values(): |
| 62 |
self.cookies.set_cookie(cookie) |
| 63 |
|
| 64 |
def request(self, url, **kwargs): |
| 65 |
response = Extractor.request(self, url, **kwargs) |
| 66 |
|
| 67 |
if response.history: |
| 68 |
if "login.sina.com" in response.url: |
| 69 |
raise self.exc.AbortExtraction( |
| 70 |
f"HTTP redirect to login page " |
| 71 |
f"({response.url.partition('?')[0]})") |
| 72 |
if "passport.weibo.com" in response.url: |
| 73 |
self._sina_visitor_system(response) |
| 74 |
response = Extractor.request(self, url, **kwargs) |
| 75 |
|
| 76 |
return response |
| 77 |
|
| 78 |
def items(self): |
| 79 |
original_retweets = (self.retweets == "original") |
| 80 |
is_like = text.re(r"\d-\d\d?赞过").search |
| 81 |
|
| 82 |
for status in self.statuses(): |
| 83 |
|
| 84 |
if "ori_mid" in status and not self.retweets: |
| 85 |
self.log.debug("Skipping %s (快转 retweet)", status["id"]) |
| 86 |
continue |
| 87 |
|
| 88 |
if "retweeted_status" in status: |
| 89 |
if not self.retweets: |
| 90 |
self.log.debug("Skipping %s (retweet)", status["id"]) |
| 91 |
continue |
| 92 |
|
| 93 |
# videos of the original post are in status |
| 94 |
# images of the original post are in status["retweeted_status"] |
| 95 |
files = [] |
| 96 |
self._extract_retweet(status, files) |
| 97 |
self._extract_status(status["retweeted_status"], files) |
| 98 |
|
| 99 |
if original_retweets: |
| 100 |
status = status["retweeted_status"] |
| 101 |
else: |
| 102 |
files = [] |
| 103 |
self._extract_status(status, files) |
| 104 |
|
| 105 |
if title := status.get("title"): |
| 106 |
if is_like(title.get("text") or ""): |
| 107 |
if not self.likes: |
| 108 |
self.log.debug("Skipping %s (赞过 like)", status["id"]) |
| 109 |
continue |
| 110 |
status["like"] = True |
| 111 |
else: |
| 112 |
status["like"] = False |
| 113 |
else: |
| 114 |
status["like"] = None |
| 115 |
|
| 116 |
if self.longtext and status.get("isLongText") and \ |
| 117 |
status["text"].endswith('class="expand">展开</span>'): |
| 118 |
status = self._status_by_id(status["id"]) |
| 119 |
|
| 120 |
status["date"] = self.parse_datetime( |
| 121 |
status["created_at"], "%a %b %d %H:%M:%S %z %Y") |
| 122 |
status["count"] = len(files) |
| 123 |
yield Message.Directory, "", status |
| 124 |
|
| 125 |
num = 0 |
| 126 |
for file in files: |
| 127 |
url = file["url"] |
| 128 |
if not url: |
| 129 |
continue |
| 130 |
if url.startswith("http:"): |
| 131 |
url = "https:" + url[5:] |
| 132 |
if "filename" not in file: |
| 133 |
text.nameext_from_url(url, file) |
| 134 |
if file["extension"] == "json": |
| 135 |
file["extension"] = "mp4" |
| 136 |
if file["extension"] == "m3u8": |
| 137 |
url = "ytdl:" + url |
| 138 |
file["_ytdl_manifest"] = "hls" |
| 139 |
file["extension"] = "mp4" |
| 140 |
num += 1 |
| 141 |
file["status"] = status |
| 142 |
file["num"] = num |
| 143 |
yield Message.Url, url, file |
| 144 |
|
| 145 |
def _extract_status(self, status, files): |
| 146 |
if "mix_media_info" in status: |
| 147 |
for item in status["mix_media_info"]["items"]: |
| 148 |
type = item.get("type") |
| 149 |
if type == "video": |
| 150 |
if self.videos: |
| 151 |
files.append(self._extract_video( |
| 152 |
item["data"]["media_info"])) |
| 153 |
elif type == "pic": |
| 154 |
files.append(item["data"]["largest"].copy()) |
| 155 |
else: |
| 156 |
self.log.warning("Unknown media type '%s'", type) |
| 157 |
return |
| 158 |
|
| 159 |
if pic_ids := status.get("pic_ids"): |
| 160 |
pics = status["pic_infos"] |
| 161 |
for pic_id in pic_ids: |
| 162 |
pic = pics[pic_id] |
| 163 |
pic_type = pic.get("type") |
| 164 |
|
| 165 |
if pic_type == "gif" and self.gifs: |
| 166 |
if self.gifs_video: |
| 167 |
files.append({"url": pic["video"]}) |
| 168 |
else: |
| 169 |
files.append(pic["largest"].copy()) |
| 170 |
|
| 171 |
elif pic_type == "livephoto" and self.livephoto: |
| 172 |
files.append(pic["largest"].copy()) |
| 173 |
files.append({"url": pic["video"]}) |
| 174 |
|
| 175 |
else: |
| 176 |
files.append(pic["largest"].copy()) |
| 177 |
|
| 178 |
if "page_info" in status: |
| 179 |
info = status["page_info"] |
| 180 |
if "media_info" in info and self.videos: |
| 181 |
if info.get("type") != "5" or self.movies: |
| 182 |
files.append(self._extract_video(info["media_info"])) |
| 183 |
else: |
| 184 |
self.log.debug("%s: Ignoring 'movie' video", status["id"]) |
| 185 |
|
| 186 |
def _extract_retweet(self, status, files): |
| 187 |
self._extract_status(status, files) |
| 188 |
if "url_struct" in status: |
| 189 |
for item in status["url_struct"]: |
| 190 |
if pics := item.get("pic_infos"): |
| 191 |
for pic in pics.values(): |
| 192 |
files.append(pic.get("largest") or pic["large"]) |
| 193 |
|
| 194 |
def _extract_video(self, info): |
| 195 |
if info.get("live_status") == 1: |
| 196 |
self.log.debug("Skipping ongoing live stream") |
| 197 |
return {"url": ""} |
| 198 |
|
| 199 |
try: |
| 200 |
media = max(info["playback_list"], |
| 201 |
key=lambda m: m["meta"].get("quality_index", 0)) |
| 202 |
except Exception: |
| 203 |
video = {"url": (info.get("replay_hd") or |
| 204 |
info.get("stream_url_hd") or |
| 205 |
info.get("stream_url") or "")} |
| 206 |
else: |
| 207 |
video = media["play_info"].copy() |
| 208 |
|
| 209 |
if "//wblive-out." in video["url"] and \ |
| 210 |
not text.ext_from_url(video["url"]): |
| 211 |
try: |
| 212 |
video["url"] = self.request_location(video["url"]) |
| 213 |
except self.exc.HttpError as exc: |
| 214 |
self.log.warning("%s: %s", exc.__class__.__name__, exc) |
| 215 |
video["url"] = "" |
| 216 |
|
| 217 |
return video |
| 218 |
|
| 219 |
def _status_by_id(self, status_id): |
| 220 |
url = (f"{self.root}/ajax/statuses/show" |
| 221 |
f"?id={status_id}&isGetLongText=true") |
| 222 |
return self.request_json(url) |
| 223 |
|
| 224 |
def _user(self, user): |
| 225 |
url = (f"{self.root}/ajax/profile/info?" |
| 226 |
f"{'screen_name' if self._prefix == 'n' else 'custom'}={user}") |
| 227 |
return self.request_json(url, interval=False)["data"]["user"] |
| 228 |
|
| 229 |
def _user_id(self): |
| 230 |
user = self.user |
| 231 |
if len(user) >= 10 and user.isdecimal(): |
| 232 |
return user[-10:] |
| 233 |
else: |
| 234 |
return self._user(user)["idstr"] |
| 235 |
|
| 236 |
def _pagination(self, endpoint, params, |
| 237 |
since_key="sinceid", subalbums=None): |
| 238 |
url = f"{self.root}/ajax{endpoint}" |
| 239 |
headers = { |
| 240 |
"Accept": "application/json, text/plain, */*", |
| 241 |
"X-Requested-With": "XMLHttpRequest", |
| 242 |
"X-XSRF-TOKEN": None, |
| 243 |
"Referer": f"{self.root}/u/{params['uid']}", |
| 244 |
} |
| 245 |
|
| 246 |
while True: |
| 247 |
response = self.request(url, params=params, headers=headers) |
| 248 |
headers["X-XSRF-TOKEN"] = response.cookies.get("XSRF-TOKEN") |
| 249 |
|
| 250 |
data = response.json() |
| 251 |
if not (ok := data.get("ok", 0)): |
| 252 |
self.log.debug(response.content) |
| 253 |
if "since_id" not in params: # first iteration |
| 254 |
raise self.exc.AbortExtraction( |
| 255 |
f'"{data.get("msg") or "unknown error"}"') |
| 256 |
elif ok < 0: |
| 257 |
self.request(self.root + "/").content |
| 258 |
continue |
| 259 |
|
| 260 |
try: |
| 261 |
data = data["data"] |
| 262 |
statuses = data["list"] |
| 263 |
except KeyError: |
| 264 |
return |
| 265 |
|
| 266 |
if subalbums is not None: |
| 267 |
subalbums = None |
| 268 |
yield data.get("album_list") or () |
| 269 |
|
| 270 |
yield from statuses |
| 271 |
|
| 272 |
# videos, newvideo |
| 273 |
if cursor := data.get("next_cursor"): |
| 274 |
if cursor == -1: |
| 275 |
return |
| 276 |
params["cursor"] = cursor |
| 277 |
continue |
| 278 |
|
| 279 |
# album |
| 280 |
if "since_id" in data: |
| 281 |
params[since_key] = since_id = data["since_id"] |
| 282 |
if not since_id: |
| 283 |
return |
| 284 |
if "page" in params: |
| 285 |
params["page"] += 1 |
| 286 |
continue |
| 287 |
|
| 288 |
# home, article |
| 289 |
if "page" in params: |
| 290 |
if not statuses: |
| 291 |
return |
| 292 |
params["page"] += 1 |
| 293 |
continue |
| 294 |
|
| 295 |
# feed, last album page |
| 296 |
try: |
| 297 |
params["since_id"] = statuses[-1]["id"] - 1 |
| 298 |
except LookupError: |
| 299 |
return |
| 300 |
|
| 301 |
def _sina_visitor_system(self, response): |
| 302 |
self.log.info("Sina Visitor System") |
| 303 |
|
| 304 |
passport_url = "https://passport.weibo.com/visitor/genvisitor2" |
| 305 |
headers = {"Referer": response.url} |
| 306 |
data = { |
| 307 |
"cb" : "visitor_gray_callback", |
| 308 |
"ver" : "20250916", |
| 309 |
"tid" : "", |
| 310 |
"from": "weibo", |
| 311 |
"webdriver" : "false", |
| 312 |
"return_url": "https://weibo.com/", |
| 313 |
} |
| 314 |
|
| 315 |
page = Extractor.request( |
| 316 |
self, passport_url, method="POST", headers=headers, data=data).text |
| 317 |
data = util.json_loads(text.extr(page, "(", ");"))["data"] |
| 318 |
|
| 319 |
passport_url = "https://passport.weibo.com/visitor/visitor" |
| 320 |
params = { |
| 321 |
"a" : "crossdomain", |
| 322 |
"t" : data.get("tid"), |
| 323 |
"sp" : data["subp"], |
| 324 |
"s" : data["sub"], |
| 325 |
"from" : "weibo", |
| 326 |
"_rand": random.random(), |
| 327 |
"url" : response.url |
| 328 |
} |
| 329 |
response = Extractor.request( |
| 330 |
self, passport_url, params=params, allow_redirects=False) |
| 331 |
self.cache_update( |
| 332 |
_cookie_cache, ..., response.cookies, _exp=365*86400) |
| 333 |
|
| 334 |
|
| 335 |
class WeiboUserExtractor(WeiboExtractor): |
| 336 |
"""Extractor for weibo user profiles""" |
| 337 |
subcategory = "user" |
| 338 |
pattern = USER_PATTERN + r"(?:$|#)" |
| 339 |
example = "https://weibo.com/USER" |
| 340 |
|
| 341 |
# do NOT override 'initialize()' |
| 342 |
# it is needed for 'self._user_id()' |
| 343 |
# def initialize(self): |
| 344 |
# pass |
| 345 |
|
| 346 |
def items(self): |
| 347 |
base = f"{self.root}/u/{self._user_id()}?tabtype=" |
| 348 |
return Dispatch._dispatch_extractors(self, ( |
| 349 |
(WeiboHomeExtractor , base + "home"), |
| 350 |
(WeiboFeedExtractor , base + "feed"), |
| 351 |
(WeiboVideosExtractor , base + "video"), |
| 352 |
(WeiboNewvideoExtractor, base + "newVideo"), |
| 353 |
(WeiboArticleExtractor , base + "article"), |
| 354 |
(WeiboAlbumExtractor , base + "album"), |
| 355 |
), ("feed",), { |
| 356 |
("album", "subalbums", base + "album-only"), |
| 357 |
}) |
| 358 |
|
| 359 |
|
| 360 |
class WeiboHomeExtractor(WeiboExtractor): |
| 361 |
"""Extractor for weibo 'home' listings""" |
| 362 |
subcategory = "home" |
| 363 |
pattern = USER_PATTERN + r"\?tabtype=home" |
| 364 |
example = "https://weibo.com/USER?tabtype=home" |
| 365 |
|
| 366 |
def statuses(self): |
| 367 |
endpoint = "/profile/myhot" |
| 368 |
params = {"uid": self._user_id(), "page": 1, "feature": "2"} |
| 369 |
return self._pagination(endpoint, params) |
| 370 |
|
| 371 |
|
| 372 |
class WeiboFeedExtractor(WeiboExtractor): |
| 373 |
"""Extractor for weibo user feeds""" |
| 374 |
subcategory = "feed" |
| 375 |
pattern = USER_PATTERN + r"\?tabtype=feed" |
| 376 |
example = "https://weibo.com/USER?tabtype=feed" |
| 377 |
|
| 378 |
def statuses(self): |
| 379 |
endpoint = "/statuses/mymblog" |
| 380 |
params = {"uid": self._user_id(), "feature": "0"} |
| 381 |
if self.logged_in: |
| 382 |
params["page"] = 1 |
| 383 |
return self._pagination(endpoint, params) |
| 384 |
|
| 385 |
|
| 386 |
class WeiboVideosExtractor(WeiboExtractor): |
| 387 |
"""Extractor for weibo 'video' listings""" |
| 388 |
subcategory = "videos" |
| 389 |
pattern = USER_PATTERN + r"\?tabtype=video" |
| 390 |
example = "https://weibo.com/USER?tabtype=video" |
| 391 |
|
| 392 |
def statuses(self): |
| 393 |
endpoint = "/profile/getprofilevideolist" |
| 394 |
params = {"uid": self._user_id()} |
| 395 |
|
| 396 |
for status in self._pagination(endpoint, params): |
| 397 |
yield status["video_detail_vo"] |
| 398 |
|
| 399 |
|
| 400 |
class WeiboNewvideoExtractor(WeiboExtractor): |
| 401 |
"""Extractor for weibo 'newVideo' listings""" |
| 402 |
subcategory = "newvideo" |
| 403 |
pattern = USER_PATTERN + r"\?tabtype=newVideo" |
| 404 |
example = "https://weibo.com/USER?tabtype=newVideo" |
| 405 |
|
| 406 |
def statuses(self): |
| 407 |
endpoint = "/profile/getWaterFallContent" |
| 408 |
params = {"uid": self._user_id()} |
| 409 |
return self._pagination(endpoint, params) |
| 410 |
|
| 411 |
|
| 412 |
class WeiboArticleExtractor(WeiboExtractor): |
| 413 |
"""Extractor for weibo 'article' listings""" |
| 414 |
subcategory = "article" |
| 415 |
pattern = USER_PATTERN + r"\?tabtype=article" |
| 416 |
example = "https://weibo.com/USER?tabtype=article" |
| 417 |
|
| 418 |
def statuses(self): |
| 419 |
endpoint = "/statuses/mymblog" |
| 420 |
params = {"uid": self._user_id(), "page": 1, "feature": "10"} |
| 421 |
return self._pagination(endpoint, params) |
| 422 |
|
| 423 |
|
| 424 |
class WeiboAlbumExtractor(WeiboExtractor): |
| 425 |
"""Extractor for weibo 'album' listings""" |
| 426 |
subcategory = "album" |
| 427 |
pattern = USER_PATTERN + r"\?tabtype=album(?:[:_-]([^&#]+))?" |
| 428 |
example = "https://weibo.com/USER?tabtype=album" |
| 429 |
|
| 430 |
def items(self): |
| 431 |
subalbum = self.groups[2] |
| 432 |
|
| 433 |
if not subalbum and not self.config("subalbums", False): |
| 434 |
return WeiboExtractor.items(self) |
| 435 |
|
| 436 |
self.directory_fmt = ("{category}", "{user[screen_name]}", |
| 437 |
"Album", "{subalbum[pic_title]|''}") |
| 438 |
self.filename_fmt = "{filename}.{extension}" |
| 439 |
self.archive_fmt = "{subalbum[pic_title]}_{pid}" |
| 440 |
return self.items_subalbum(subalbum) |
| 441 |
|
| 442 |
def items_subalbum(self, subalbum): |
| 443 |
user = self.kwdict["user"] = self._user(self.user) |
| 444 |
base = self.root + "/ajax/common/download?pid=" |
| 445 |
|
| 446 |
for data, files in self.albums(user["idstr"], subalbum): |
| 447 |
self.kwdict["subalbum"] = data |
| 448 |
yield Message.Directory, "", {} |
| 449 |
for file in files: |
| 450 |
if "pid" in file: |
| 451 |
file["filename"] = file["pid"] |
| 452 |
file["extension"] = "jpg" |
| 453 |
yield Message.Url, base + file["pid"], file |
| 454 |
elif "mid" in file: |
| 455 |
mid = file["mid"] |
| 456 |
status = self._status_by_id(mid) |
| 457 |
if status.get("ok") != 1: |
| 458 |
self.log.debug("Skipping status %s (%s)", mid, status) |
| 459 |
else: |
| 460 |
self.statuses = lambda: (status,) |
| 461 |
yield from WeiboExtractor.items(self) |
| 462 |
yield Message.Directory, "", {} |
| 463 |
|
| 464 |
def statuses(self): |
| 465 |
endpoint = "/profile/getImageWall" |
| 466 |
params = {"uid": self._user_id()} |
| 467 |
|
| 468 |
seen = set() |
| 469 |
for image in self._pagination(endpoint, params): |
| 470 |
mid = image["mid"] |
| 471 |
if mid not in seen: |
| 472 |
seen.add(mid) |
| 473 |
status = self._status_by_id(mid) |
| 474 |
if status.get("ok") != 1: |
| 475 |
self.log.debug("Skipping status %s (%s)", mid, status) |
| 476 |
else: |
| 477 |
yield status |
| 478 |
|
| 479 |
def albums(self, uid, subalbum): |
| 480 |
endpoint = "/profile/getImageWall" |
| 481 |
params = { |
| 482 |
"uid" : uid, |
| 483 |
"sinceid" : "0", |
| 484 |
"has_album": "true", |
| 485 |
} |
| 486 |
album = self._pagination(endpoint, params, subalbums=True) |
| 487 |
subalbums = next(album, ()) |
| 488 |
|
| 489 |
if not subalbum or subalbum == "0": |
| 490 |
return (({}, album),) |
| 491 |
|
| 492 |
if subalbum == "all": |
| 493 |
results = [ |
| 494 |
(sub, self._pagination_subalbum(uid, sub)) |
| 495 |
for sub in subalbums |
| 496 |
] |
| 497 |
results.append(({}, album)) |
| 498 |
return results |
| 499 |
|
| 500 |
if subalbum == "only": |
| 501 |
return [ |
| 502 |
(sub, self._pagination_subalbum(uid, sub)) |
| 503 |
for sub in subalbums |
| 504 |
] |
| 505 |
|
| 506 |
if subalbum.isdecimal(): |
| 507 |
try: |
| 508 |
sub = subalbums[int(subalbum)-1] |
| 509 |
except Exception: |
| 510 |
raise self.exc.NotFoundError("subalbum") |
| 511 |
else: |
| 512 |
subalbum = text.unquote(subalbum) |
| 513 |
for sub in subalbums: |
| 514 |
if sub["pic_title"] == subalbum: |
| 515 |
break |
| 516 |
else: |
| 517 |
raise self.exc.NotFoundError("subalbum") |
| 518 |
return ((sub, self._pagination_subalbum(uid, sub)),) |
| 519 |
|
| 520 |
def _pagination_subalbum(self, uid, sub): |
| 521 |
params = {"uid": uid, "containerid": text.unquote(sub["containerid"])} |
| 522 |
return self._pagination("/profile/getAlbumDetail", params, "since_id") |
| 523 |
|
| 524 |
|
| 525 |
class WeiboStatusExtractor(WeiboExtractor): |
| 526 |
"""Extractor for a weibo status""" |
| 527 |
subcategory = "status" |
| 528 |
pattern = BASE_PATTERN + r"/(detail|status|\d+)/(\w+)" |
| 529 |
example = "https://weibo.com/detail/12345" |
| 530 |
|
| 531 |
def statuses(self): |
| 532 |
status = self._status_by_id(self.user) |
| 533 |
if status.get("ok") != 1: |
| 534 |
self.log.debug(status) |
| 535 |
raise self.exc.NotFoundError("status") |
| 536 |
return (status,) |
| 537 |
|
| 538 |
|
| 539 |
def _cookie_cache(): |
| 540 |
return None |