新增: 实时热卖榜(11分类/想要人数排序/热门搜索词热度)、价格监控(目标价通知/卖家信用筛选/销量下限/AI精准监控)、 一键转卖(收藏自动加载/改价直发/详情直达)、AI回复免费token(ai.88531.cn)、API密钥掩码、 推理模型兼容修复、商品本地编辑、授权系统接入(在线人数/版本/公告)、品牌更名躺赚鱼。 README 重写为项目介绍(改动清单/优势/真实截图/两种安装方式/体验地址 tzy.88531.cn/使用引导), 原版 README 完整保留为 README.upstream.md。
217 lines
9.4 KiB
Python
217 lines
9.4 KiB
Python
"""闲鱼搜索结果解析(pc.search)。
|
||
|
||
实测结论(2026-11-15,探针 probe_hot1~8):
|
||
|
||
- 响应结构是 ``data.resultList[].data.item.main.exContent`` —— 比直觉多一层
|
||
``main``,漏掉这一层会让 exContent 恒为空、所有条目因 item_id 为空被
|
||
跳过,接口返回 0 条(面板「一键转卖-搜索」曾长期 0 条就是这个根因)。
|
||
- 搜索结果里**没有商品级「已售/成交量」字段**(闲鱼单件二手成交),真实热度
|
||
指标是 fishTags 里的「N 人想要」文本(实测 0 ~ 26202);``clickParam.args.wantNum``
|
||
恒为 0,不能用。
|
||
- **卖家维度**信号实测可得(2026-11-15):① fishTags 里有「卖家信用极好/
|
||
优秀」「百分百好评」「回复超快」「验货宝」;② ``userFishShopLabel.tagList``
|
||
里有「N 条评价」(0/32/37/74/126 条)—— 这是**卖家累计成交量**的近似
|
||
(每笔成交一条评价)。故 ``parse_search_items`` 额外输出
|
||
``seller_credit``(信用等级文本,未标注为空串)与 ``seller_deals``
|
||
(评价数,未知为 -1)。
|
||
- ``sort``/``sortType``/``filter`` 排序参数均不生效:同参数连发两次结果
|
||
顺序都不同(结果本身带随机打散),所以只能本地聚合后排序。
|
||
- ``picUrl`` 个别是 ``.heic``,浏览器不显示;经
|
||
``?x-oss-process=image/format,jpg`` 实测可转成 image/jpeg。**jpg 原图
|
||
加该参数会 404**,故只对 .heic 追加。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
# 「1566人想要」「2.3万人想要」
|
||
_WANT_RE = re.compile(r"(\d+(?:\.\d+)?)\s*(万?)\s*人想要")
|
||
|
||
|
||
def _as_text(value: Any) -> str:
|
||
"""富文本片段数组([{"text": "¥55"}, ...])拼回纯文本。"""
|
||
if isinstance(value, list):
|
||
return "".join(
|
||
str(part.get("text", "")) for part in value if isinstance(part, dict)
|
||
).strip()
|
||
if value is None:
|
||
return ""
|
||
return str(value)
|
||
|
||
|
||
def extract_want(content: Dict[str, Any], args: Dict[str, Any]) -> int:
|
||
"""取「人想要」数:先扫 fishTags 全部行,再回退 wantNum(兼容字段)。"""
|
||
tags = content.get("fishTags") or {}
|
||
if isinstance(tags, dict):
|
||
for block in tags.values():
|
||
for tag in (block or {}).get("tagList") or []:
|
||
text = _as_text(((tag or {}).get("data") or {}).get("content"))
|
||
match = _WANT_RE.search(text)
|
||
if match:
|
||
try:
|
||
num = float(match.group(1))
|
||
if match.group(2) == "万":
|
||
num *= 10000
|
||
return int(num)
|
||
except ValueError:
|
||
pass
|
||
# want 字段类型未知(可能 int / str),只在能安全转换时使用
|
||
raw = content.get("want")
|
||
if isinstance(raw, (int, float)):
|
||
return int(raw)
|
||
if isinstance(raw, str) and raw.strip().isdigit():
|
||
return int(raw.strip())
|
||
want_num = args.get("wantNum")
|
||
if isinstance(want_num, (int, float)) and want_num:
|
||
return int(want_num)
|
||
return 0
|
||
|
||
|
||
_CREDIT_RE = re.compile(r"卖家信用\s*([\u4e00-\u9fa5]{1,4})")
|
||
_DEALS_RE = re.compile(r"(\d+)\s*条评价")
|
||
# 闲鱼卖家信用等级(低→高)。未出现在表里的文本按 0 处理,仍高于「无标注」。
|
||
CREDIT_RANK: Dict[str, int] = {"较差": 0, "中等": 1, "一般": 1, "良好": 2, "优秀": 3, "极好": 4}
|
||
|
||
|
||
def credit_rank(text: str) -> int:
|
||
"""信用等级 → 数值;未标注返回 -1(低于任何具体等级)。"""
|
||
if not text:
|
||
return -1
|
||
return CREDIT_RANK.get(text.strip(), 0)
|
||
|
||
|
||
def extract_seller_signal(content: Dict[str, Any]) -> tuple:
|
||
"""取卖家信号 → (信用等级文本, 评价数)。
|
||
|
||
- 信用:扫 fishTags 全部行找「卖家信用XXX」(实测见 极好/优秀)。
|
||
- 评价数:扫 userFishShopLabel.tagList 找「N条评价」,即卖家累计成交量。
|
||
没找到返回 -1(与「0条评价」区分:0 是真没成交,-1 是没数据)。
|
||
"""
|
||
credit = ""
|
||
tags = content.get("fishTags") or {}
|
||
if isinstance(tags, dict):
|
||
for block in tags.values():
|
||
for tag in (block or {}).get("tagList") or []:
|
||
text = _as_text(((tag or {}).get("data") or {}).get("content"))
|
||
match = _CREDIT_RE.search(text)
|
||
if match:
|
||
credit = match.group(1)
|
||
break
|
||
if credit:
|
||
break
|
||
|
||
deals = -1
|
||
label = content.get("userFishShopLabel")
|
||
if isinstance(label, dict):
|
||
for tag in label.get("tagList") or []:
|
||
text = _as_text(((tag or {}).get("data") or {}).get("content"))
|
||
match = _DEALS_RE.search(text)
|
||
if match:
|
||
deals = int(match.group(1))
|
||
break
|
||
return credit, deals
|
||
|
||
|
||
def normalize_image(url: Any) -> str:
|
||
"""图片 URL:升级到 https;.heic 追加转码参数(jpg 加会 404,别加)。"""
|
||
text = str(url or "").strip()
|
||
if not text:
|
||
return ""
|
||
if text.startswith("http://"):
|
||
text = "https://" + text[len("http://"):]
|
||
if text.lower().split("?")[0].endswith(".heic"):
|
||
text += ("&" if "?" in text else "?") + "x-oss-process=image/format,jpg"
|
||
return text
|
||
|
||
|
||
def normalize_price(content: Dict[str, Any]) -> str:
|
||
"""价格:优先 detailParams.soldPrice(干净字符串),回退富文本 price。"""
|
||
sold = str((content.get("detailParams") or {}).get("soldPrice") or "").strip()
|
||
if sold:
|
||
return sold if sold.startswith("¥") else f"¥{sold}"
|
||
price = _as_text(content.get("price")).replace("当前价", "").strip()
|
||
if price and not price.startswith("¥") and any(ch.isdigit() for ch in price):
|
||
price = f"¥{price}"
|
||
return price
|
||
|
||
|
||
def parse_search_items(result: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""把 pc.search 响应拍平成面板通用的条目列表(不去重、不排序)。"""
|
||
items: List[Dict[str, Any]] = []
|
||
for raw in (result.get("data") or {}).get("resultList") or []:
|
||
# 关键:多一层 main
|
||
main = (((raw or {}).get("data") or {}).get("item") or {}).get("main") or {}
|
||
content = main.get("exContent") or {}
|
||
if not content:
|
||
continue
|
||
args = (main.get("clickParam") or {}).get("args") or {}
|
||
params = content.get("detailParams") or {}
|
||
item_id = str(
|
||
content.get("itemId") or params.get("itemId") or args.get("item_id") or ""
|
||
).strip()
|
||
if not item_id:
|
||
continue
|
||
title = _as_text(content.get("title")) or str(params.get("title") or "").strip()
|
||
publish = args.get("publishTime")
|
||
try:
|
||
publish_ts = int(publish) if publish else 0
|
||
except (TypeError, ValueError):
|
||
publish_ts = 0
|
||
items.append({
|
||
"item_id": item_id,
|
||
"title": title,
|
||
"price": normalize_price(content),
|
||
"image": normalize_image(content.get("picUrl")),
|
||
"area": _as_text(content.get("area")),
|
||
"seller": _as_text(content.get("userNickName"))
|
||
or str(params.get("userNick") or "").strip(),
|
||
"want_count": extract_want(content, args),
|
||
"publish_time": publish_ts,
|
||
"url": f"https://www.goofish.com/item?id={item_id}",
|
||
# 卖家维度(价格监控筛信用度/销量用;未标注时 credit=""、deals=-1)
|
||
**dict(zip(("seller_credit", "seller_deals"), extract_seller_signal(content))),
|
||
})
|
||
return items
|
||
|
||
|
||
def merge_by_item(existing: Dict[str, Dict[str, Any]], incoming: List[Dict[str, Any]],
|
||
keyword: str) -> None:
|
||
"""按 item_id 合并进榜单:保留更高的 want_count,累计命中关键词。"""
|
||
for item in incoming:
|
||
item = dict(item)
|
||
item.setdefault("keywords", [])
|
||
if keyword and keyword not in item["keywords"]:
|
||
item["keywords"].append(keyword)
|
||
prev = existing.get(item["item_id"])
|
||
if prev is None:
|
||
existing[item["item_id"]] = item
|
||
continue
|
||
# 同一商品可能被多个关键词命中:want 取最大,关键词取并集
|
||
prev["want_count"] = max(prev.get("want_count", 0), item.get("want_count", 0))
|
||
# 卖家成交量取已知值中的较大者;信用等级取先到的非空标注
|
||
if item.get("seller_deals", -1) > prev.get("seller_deals", -1):
|
||
prev["seller_deals"] = item["seller_deals"]
|
||
if not prev.get("seller_credit") and item.get("seller_credit"):
|
||
prev["seller_credit"] = item["seller_credit"]
|
||
for kw in item["keywords"]:
|
||
if kw not in prev["keywords"]:
|
||
prev["keywords"].append(kw)
|
||
# 用更晚抓到的字段补空(图片/标题以先到的为准,避免抖动)
|
||
for field in ("image", "price", "area", "seller", "publish_time",
|
||
"seller_credit", "seller_deals"):
|
||
if not prev.get(field) and item.get(field):
|
||
prev[field] = item[field]
|
||
|
||
|
||
def rank_items(items: Dict[str, Dict[str, Any]], top_n: int = 50) -> List[Dict[str, Any]]:
|
||
"""按想要人数降序排,同分按发布时间新在前,截断并写入 rank。"""
|
||
ordered = sorted(
|
||
items.values(),
|
||
key=lambda it: (-it.get("want_count", 0), -it.get("publish_time", 0)),
|
||
)[:top_n]
|
||
for index, item in enumerate(ordered, start=1):
|
||
item["rank"] = index
|
||
return ordered
|