scp_core.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.12.10
  4. # Date : 2026/07/15
  5. """
  6. SCP Auctions (catalogs.scpauctions.com) 公用模块:HTTP 配置、拍卖会列表解析、
  7. 场次内 lot 列表分页抓取、详情页解析。被 scp_history.py / scp_spider.py 复用。
  8. 目标网站: https://catalogs.scpauctions.com/auctions/past
  9. 逻辑要点:
  10. 1. 站点为 Bidsquare 托管平台,页面服务端渲染(SSR),无独立数据 API,
  11. 全部数据直接在 HTML 里,用 parsel 解析即可(本地开了 VPN,请求统一走代理)。
  12. 2. 拍卖会列表页 /auctions/past 分页:?page=N(每页 24 场),翻到空页为止。
  13. 每张拍卖会卡片是 <div class="gtm-visible_event" data-event_id=...>:
  14. event_id(去重键)、标题、类型、起止时间、主页/图录链接、封面图。
  15. 3. 图录(lot 列表)页 catalog_url?page=N&limit=120(limit 上限 120):
  16. lot 卡片是 <div id="stl-{item_id}" data-item_id=...>,含 Lot 号 / 标题 /
  17. 详情链接 / 缩略图 / 出价数 / 成交状态与成交价。翻到空页为止。
  18. 4. lot 详情页 /online-auctions/{house}/{slug}-{item_id}:
  19. 标题取 og:title;成交价在 .bidding-price(流拍则为空);
  20. 属性(Collection/Sport/Type/Athlete/Team 等)在 .item-attributes li,
  21. label/span 成对,字段数量不固定(2~5 个,可能缺 Athlete/Team),
  22. 故按 label 建字典再按需取值,缺失置空;
  23. 多图为 s1.img.bidsquare.com/item/{l|s}/... 归一化到 large 尺寸去重。
  24. """
  25. import re
  26. import random
  27. from datetime import datetime
  28. from loguru import logger
  29. from parsel import Selector
  30. from curl_cffi import requests
  31. from curl_cffi.requests import BrowserType
  32. from urllib.parse import urljoin
  33. from tenacity import retry, stop_after_attempt, wait_fixed
  34. # —— 站点常量 ——
  35. BASE_URL = "https://catalogs.scpauctions.com" # 站点根,用于拼接相对链接
  36. PAST_URL = "https://catalogs.scpauctions.com/auctions/past" # 拍卖会(历史)列表页
  37. CATALOG_PAGE_SIZE = 120 # 图录页每页 lot 数(limit 参数,站点上限 120)
  38. IMG_ITEM_RE = r'https://s1\.img\.bidsquare\.com/item/[ls]/\d+/\d+\.jpe?g(?:\?t=[^"\'\s\\]+)?' # 拍品图 URL
  39. # 直接用库内置的所有浏览器指纹(伪装真实浏览器 TLS/UA,规避潜在的指纹风控)
  40. client_identifier_list = [b.value for b in BrowserType]
  41. # 不写死 user-agent:curl_cffi 会按 impersonate 指纹自动带匹配的 UA,
  42. # 写死会造成 TLS 指纹与 UA 头矛盾,反而更易被识别。只保留通用、不冲突的头。
  43. headers = {
  44. "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  45. "accept-language": "en-US,en;q=0.9",
  46. }
  47. def after_log(retry_state):
  48. """tenacity retry 回调,统一打印重试日志。
  49. Args:
  50. retry_state: tenacity.RetryCallState,retry 框架自动传入。
  51. Returns:
  52. None: 仅打印日志,无返回值。
  53. """
  54. if retry_state.args and len(retry_state.args) > 0:
  55. log = retry_state.args[0]
  56. else:
  57. log = logger
  58. if retry_state.outcome.failed:
  59. log.warning(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  60. else:
  61. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  62. @retry(stop=stop_after_attempt(5), wait=wait_fixed(2), after=after_log)
  63. def get_proxys(log):
  64. """获取代理字典,全部请求方法的 proxies 参数都走这里。
  65. 本地开了 VPN,从大陆直连站点不通,请求必须走代理。默认用住宅代理(北美出口,
  66. 与 SCP 面向的美区一致)。若要改用本地 VPN 客户端的 HTTP 代理端口(如 Clash 的
  67. 127.0.0.1:7890),把 http_proxy / https_proxy 换成对应地址即可。
  68. Args:
  69. log: logger 对象。
  70. Returns:
  71. dict: requests 风格代理字典 {"http": ..., "https": ...}。
  72. Raises:
  73. Exception: 透传内部异常以便 tenacity 触发重试。
  74. """
  75. # 住宅 ip 池 北美(与参考项目 rea_spider 一致);如需切本地 VPN 端口在此改
  76. http_proxy = "http://u1952150085001297:sJMHl4qc4bM0@proxy.123proxy.cn:36927"
  77. https_proxy = "http://u1952150085001297:sJMHl4qc4bM0@proxy.123proxy.cn:36927"
  78. # 本地 VPN(Clash)示例,二选一:
  79. # http_proxy = https_proxy = "http://127.0.0.1:7890"
  80. try:
  81. return {
  82. "http": http_proxy,
  83. "https": https_proxy,
  84. }
  85. except Exception as e:
  86. log.error(f"Error getting proxy: {e}")
  87. raise e
  88. @retry(stop=stop_after_attempt(5), wait=wait_fixed(2), after=after_log)
  89. def _get_selector(log, session, impersonate, url):
  90. """GET 一个页面并返回 parsel Selector(带重试,走代理)。
  91. Args:
  92. log: logger 对象。
  93. session (requests.Session): curl_cffi 会话对象。
  94. impersonate (str): 浏览器指纹标识。
  95. url (str): 目标绝对 URL。
  96. Returns:
  97. Selector: 响应 HTML 的 parsel 解析对象。
  98. Raises:
  99. Exception: HTTP 状态非 2xx 时透传异常以触发重试。
  100. """
  101. resp = session.get(url, headers=headers, impersonate=impersonate,
  102. proxies=get_proxys(log), timeout=30)
  103. resp.raise_for_status()
  104. return Selector(resp.text)
  105. def _parse_datetime(raw):
  106. """把站点时间原文解析成 datetime(丢弃时区名,保留东部墙钟时间)。
  107. Args:
  108. raw (str): 时间原文,如 "May 20, 2026 01:00PM EDT" 或带 "Start:" 前缀。
  109. Returns:
  110. datetime | None: 解析成功返回 datetime;失败或空返回 None。
  111. """
  112. if not raw:
  113. return None
  114. # 去掉 Start:/End: 前缀与末尾时区名(EDT/EST/…),只留 "May 20, 2026 01:00PM"
  115. text = re.sub(r'^\s*(Start|End)\s*:\s*', '', raw.strip(), flags=re.I)
  116. m = re.search(r'([A-Za-z]{3,9}\s+\d{1,2},\s*\d{4}\s+\d{1,2}:\d{2}\s*[AP]M)', text, re.I)
  117. if not m:
  118. return None
  119. try:
  120. return datetime.strptime(m.group(1).replace(" ", " ").upper(), "%b %d, %Y %I:%M%p")
  121. except ValueError:
  122. return None
  123. def parse_auction_list(selector):
  124. """解析 /auctions/past 单页的拍卖会卡片列表。
  125. Args:
  126. selector (Selector): 拍卖会列表页某一页 GET 响应的 parsel 解析对象。
  127. Returns:
  128. list[dict]: 每场一个 dict,字段:event_id, auction_name, auction_type,
  129. event_status, start_time_raw, end_time_raw, start_time, end_time,
  130. auction_url, catalog_url, cover_img;无卡片返回空列表。
  131. """
  132. auctions = []
  133. for card in selector.css('div.gtm-visible_event[data-event_id]'):
  134. event_id = card.attrib.get("data-event_id", "").strip()
  135. if not event_id:
  136. continue
  137. # 标题 + 拍卖会主页链接
  138. title_a = card.css('.list-top h1 a')
  139. auction_name = (title_a.xpath('normalize-space(.)').get() or
  140. card.attrib.get("data-event_name", "")).strip()
  141. auction_url = title_a.attrib.get("href", "").strip()
  142. # 类型(Timed Auction 等)
  143. auction_type = (card.css('.list-top label::text').get() or "").strip()
  144. # 起止时间:.list-top 下多个 <span>,按前缀区分
  145. start_raw = end_raw = ""
  146. for sp in card.css('.list-top span'):
  147. t = (sp.xpath('normalize-space(.)').get() or "").strip()
  148. if t.lower().startswith("start"):
  149. start_raw = t
  150. elif t.lower().startswith("end"):
  151. end_raw = t
  152. # 图录链接(去掉锚点 #catalog)
  153. catalog_url = (card.css('a.view-catalog-btn::attr(href)').get() or "").strip()
  154. catalog_url = catalog_url.split("#")[0]
  155. cover_img = (card.css('.slider-for img::attr(src)').get() or "").strip()
  156. start_dt = _parse_datetime(start_raw)
  157. end_dt = _parse_datetime(end_raw)
  158. auctions.append({
  159. "event_id": event_id,
  160. "auction_name": auction_name,
  161. "auction_type": auction_type,
  162. "event_status": card.attrib.get("data-event_status", "").strip(),
  163. "start_time_raw": re.sub(r'^\s*Start\s*:\s*', '', start_raw, flags=re.I).strip(),
  164. "end_time_raw": re.sub(r'^\s*End\s*:\s*', '', end_raw, flags=re.I).strip(),
  165. "start_time": start_dt.strftime("%Y-%m-%d %H:%M:%S") if start_dt else None,
  166. "end_time": end_dt.strftime("%Y-%m-%d %H:%M:%S") if end_dt else None,
  167. "auction_url": urljoin(BASE_URL, auction_url) if auction_url else None,
  168. "catalog_url": urljoin(BASE_URL, catalog_url) if catalog_url else None,
  169. "cover_img": cover_img or None,
  170. })
  171. return auctions
  172. @retry(stop=stop_after_attempt(3), wait=wait_fixed(2), after=after_log)
  173. def get_auction_list(log, session, impersonate, only_first_page=False):
  174. """翻页抓取 /auctions/past 全部(或仅首页)拍卖会。
  175. Args:
  176. log: logger 对象。
  177. session (requests.Session): curl_cffi 会话对象。
  178. impersonate (str): 浏览器指纹标识。
  179. only_first_page (bool, optional): True 仅取首页(增量用,最近场次在首页顶部);
  180. False 翻完全部页(全量用)。Defaults to False。
  181. Returns:
  182. list[dict]: 拍卖会 dict 列表,已按 event_id 去重。
  183. """
  184. scope = "首页" if only_first_page else "全部"
  185. log.info(f"获取{scope}拍卖会列表")
  186. result, seen = [], set()
  187. page = 1
  188. while True:
  189. url = f"{PAST_URL}?page={page}"
  190. sel = _get_selector(log, session, impersonate, url)
  191. page_auctions = parse_auction_list(sel)
  192. if not page_auctions:
  193. break # 空页 = 已翻过末页
  194. new = [a for a in page_auctions if a["event_id"] not in seen]
  195. for a in new:
  196. seen.add(a["event_id"])
  197. result.append(a)
  198. if not new:
  199. break # 本页全重复(越界回卷兜底),停止
  200. log.info(f" 第 {page} 页解析到 {len(page_auctions)} 场(新增 {len(new)},累计 {len(result)})")
  201. if only_first_page:
  202. break
  203. page += 1
  204. log.info(f"共解析到 {len(result)} 场拍卖会")
  205. return result
  206. def _clean_price(text):
  207. """把成交价文本清洗成纯数字字符串。
  208. Args:
  209. text (str): 原始价格文本,如 "$90,000"。
  210. Returns:
  211. str: 去掉 $ 和千分位逗号后的数字串,如 "90000";无价格返回空串。
  212. """
  213. if not text:
  214. return ""
  215. m = re.search(r'\$?\s*([\d,]+)', text)
  216. return m.group(1).replace(",", "") if m else ""
  217. def parse_lot_cards(selector, auction):
  218. """解析图录页单页的 lot 卡片。
  219. Args:
  220. selector (Selector): 图录页某一页 GET 响应的 parsel 解析对象。
  221. auction (dict): 当前场次 dict(含 event_id / auction_name),回填到每条 lot。
  222. Returns:
  223. list[dict]: 每条 lot 一个 dict,字段:item_id, event_id, auction_name,
  224. lot_number, title, detail_url, list_img, sold_status, sold_for, bids;
  225. 无卡片返回空列表。
  226. """
  227. rows = []
  228. for card in selector.css('div[id^="stl-"][data-item_id]'):
  229. item_id = card.attrib.get("data-item_id", "").strip()
  230. if not item_id:
  231. continue
  232. title_a = card.css('.lot_title a')
  233. title = (title_a.xpath('normalize-space(.)').get() or "").strip()
  234. detail_url = (title_a.attrib.get("href") or "").strip()
  235. # Lot 号:"Lot 1" → "1"
  236. lot_raw = (card.css('.lot_Num::text').get() or "").strip()
  237. lot_number = (re.search(r'(\d+)', lot_raw) or [None, ""])[1] if lot_raw else ""
  238. list_img = (card.css('.catalog_img img::attr(src)').get() or "").strip()
  239. # 底部区:"9 BidsSold for$90,000" / "24 BidsUnsold"
  240. bottom = card.css('.item-list-bottom')
  241. bottom_text = (bottom.xpath('normalize-space(.)').get() or "") if bottom else ""
  242. bids_m = re.search(r'(\d+)\s*Bids?', bottom_text, re.I)
  243. bids = bids_m.group(1) if bids_m else ""
  244. if re.search(r'Unsold', bottom_text, re.I):
  245. sold_status, sold_for = "unsold", ""
  246. elif re.search(r'Sold\s*for', bottom_text, re.I):
  247. sold_status = "sold"
  248. sold_for = _clean_price(re.sub(r'.*Sold\s*for', '', bottom_text, flags=re.I))
  249. else:
  250. sold_status, sold_for = "", ""
  251. rows.append({
  252. "item_id": item_id,
  253. "event_id": auction["event_id"],
  254. "auction_name": auction.get("auction_name"),
  255. "lot_number": lot_number,
  256. "title": title,
  257. "detail_url": urljoin(BASE_URL, detail_url) if detail_url else None,
  258. "list_img": list_img or None,
  259. "sold_status": sold_status or None,
  260. "sold_for": sold_for or None,
  261. "bids": bids or None,
  262. })
  263. return rows
  264. @retry(stop=stop_after_attempt(5), wait=wait_fixed(2), after=after_log)
  265. def _fetch_lot_page(log, session, impersonate, catalog_url, page):
  266. """抓取图录页的某一页 lot 卡片。
  267. Args:
  268. log: logger 对象。
  269. session (requests.Session): curl_cffi 会话对象。
  270. impersonate (str): 浏览器指纹标识。
  271. catalog_url (str): 图录页绝对 URL(不含 query)。
  272. page (int): 页码,从 1 开始。
  273. Returns:
  274. Selector: 该页响应的 parsel 解析对象。
  275. """
  276. url = f"{catalog_url}?page={page}&limit={CATALOG_PAGE_SIZE}"
  277. return _get_selector(log, session, impersonate, url)
  278. def fetch_auction_lots(log, session, impersonate, auction):
  279. """抓取一个场次下的全部 lot 列表(翻页,去重 item_id)。
  280. Args:
  281. log: logger 对象。
  282. session (requests.Session): curl_cffi 会话对象。
  283. impersonate (str): 浏览器指纹标识。
  284. auction (dict): 场次 dict(含 event_id / auction_name / catalog_url)。
  285. Returns:
  286. list[dict]: 该场次全部 lot 列表(阶段一字段,不含详情)。
  287. """
  288. catalog_url = auction.get("catalog_url")
  289. if not catalog_url:
  290. log.warning(f"场次 {auction['event_id']} 无 catalog_url,跳过")
  291. return []
  292. log.info(f"开始抓取场次 {auction['event_id']}({auction.get('auction_name')}) 的 lot 列表")
  293. all_lots, seen = [], set()
  294. page = 1
  295. while True:
  296. sel = _fetch_lot_page(log, session, impersonate, catalog_url, page)
  297. lots = parse_lot_cards(sel, auction)
  298. if not lots:
  299. break # 空页 = 已翻过末页
  300. new = [x for x in lots if x["item_id"] not in seen]
  301. for x in new:
  302. seen.add(x["item_id"])
  303. all_lots.extend(new)
  304. log.info(f" 第 {page} 页 {len(lots)} 条(新增 {len(new)},累计 {len(all_lots)})")
  305. if not new:
  306. break # 本页全重复,停止
  307. page += 1
  308. log.info(f"场次 {auction['event_id']} 共抓 {len(all_lots)} 条 lot")
  309. return all_lots
  310. def parse_lot_detail(selector):
  311. """解析 lot 详情页,抽取标题、成交价、属性、多图。
  312. 详情页属性区(.item-attributes)字段数量不固定:不同拍品可能是 2~5 个,
  313. Athlete/Team 等常缺失。故先把所有 li 的 label→span 建成字典,再按需取字段,
  314. 缺失字段返回 None,保证解析健壮。
  315. Args:
  316. selector (Selector): 详情页 GET 响应的 parsel 解析对象。
  317. Returns:
  318. dict: {
  319. "title": 标题, "sold_for": 成交价(纯数字串,流拍为空),
  320. "sold_status": "sold"/"unsold", "bids": 出价数,
  321. "collection", "sport", "item_type", "athlete", "team": 属性(缺失为 None),
  322. "imgs": 多图 URL 逗号拼接
  323. }。
  324. """
  325. # 标题:og:title 最干净(页面首个 h1 是拍卖会名,非拍品标题)
  326. title = (selector.css('meta[property="og:title"]::attr(content)').get() or "").strip()
  327. if not title:
  328. # 兜底:取非拍卖会名的那个 h1
  329. h1s = [t.strip() for t in selector.css('h1 ::text, h1::text').getall() if t.strip()]
  330. title = h1s[1] if len(h1s) > 1 else (h1s[0] if h1s else "")
  331. # 成交价:.bidding-price 内首个 $金额;流拍则为空
  332. price_text = selector.css('.bidding-price').xpath('normalize-space(.)').get() or ""
  333. sold_for = _clean_price(price_text)
  334. sold_status = "sold" if sold_for else "unsold"
  335. # 出价数:页面 "[9 Bids]"
  336. body_text = selector.xpath('normalize-space(//body)').get() or ""
  337. bids_m = re.search(r'\[?\s*(\d+)\s*Bids?\s*\]?', body_text, re.I)
  338. bids = bids_m.group(1) if bids_m else ""
  339. # 属性:.item-attributes li -> {label: value},字段数量不固定,按需取
  340. attrs = {}
  341. for li in selector.css('.item-attributes li'):
  342. label = (li.css('label::text').get() or "").strip().rstrip(":")
  343. value = (li.css('span').xpath('normalize-space(.)').get() or "").strip()
  344. if label:
  345. attrs[label.lower()] = value
  346. # 多图:/item/{l|s}/... 统一归一化到 large 尺寸并去重(保持出现顺序)
  347. imgs, seen = [], set()
  348. for u in selector.re(IMG_ITEM_RE):
  349. large = u.replace("/item/s/", "/item/l/")
  350. if large not in seen:
  351. seen.add(large)
  352. imgs.append(large)
  353. return {
  354. "title": title,
  355. "sold_for": sold_for or None,
  356. "sold_status": sold_status,
  357. "bids": bids or None,
  358. "collection": attrs.get("collection") or None,
  359. "sport": attrs.get("sport") or None,
  360. "item_type": attrs.get("type") or None,
  361. "athlete": attrs.get("athlete") or None,
  362. "team": attrs.get("team") or None,
  363. "imgs": ",".join(imgs) if imgs else None,
  364. }
  365. @retry(stop=stop_after_attempt(3), wait=wait_fixed(2), after=after_log)
  366. def fetch_lot_detail(log, session, impersonate, detail_url):
  367. """GET lot 详情页并解析。
  368. Args:
  369. log: logger 对象。
  370. session (requests.Session): curl_cffi 会话对象。
  371. impersonate (str): 浏览器指纹标识。
  372. detail_url (str): 详情页绝对 URL。
  373. Returns:
  374. dict: parse_lot_detail 的返回结果。
  375. """
  376. log.debug(f"获取详情 {detail_url}")
  377. sel = _get_selector(log, session, impersonate, detail_url)
  378. return parse_lot_detail(sel)
  379. def save_auction(log, sql_pool, auction):
  380. """把一场拍卖会写入 scp_auction_record(幂等,靠 event_id 唯一索引去重)。
  381. Args:
  382. log: logger 对象。
  383. sql_pool: MySQL 连接池;传 None 时不入库。
  384. auction (dict): parse_auction_list 产出的场次 dict。
  385. Returns:
  386. None: 仅入库,无返回值。
  387. """
  388. if sql_pool is None:
  389. return
  390. row = {k: auction.get(k) for k in (
  391. "event_id", "auction_name", "auction_type", "event_status",
  392. "start_time_raw", "end_time_raw", "start_time", "end_time",
  393. "auction_url", "catalog_url", "cover_img",
  394. )}
  395. sql_pool.insert_many(table="scp_auction_record", data_list=[row], ignore=True)
  396. def crawl_one_auction(log, sql_pool, session, impersonate, auction):
  397. """抓取单个场次的全部 lot 列表并入库(阶段一:只抓列表,不进详情页)。
  398. 两阶段设计:本函数只负责 lot 列表入库(state 默认 0),详情字段由后续
  399. update_details_for_pending 扫库 state != 1 的记录单独补抓。抓完把
  400. scp_auction_record.lots_state 置 1,标记该场列表已抓。
  401. Args:
  402. log: logger 对象。
  403. sql_pool: MySQL 连接池;传 None 时只返回数据,不入库。
  404. session (requests.Session): curl_cffi 会话对象。
  405. impersonate (str): 浏览器指纹标识。
  406. auction (dict): 场次 dict(含 event_id / auction_name / catalog_url)。
  407. Returns:
  408. list[dict]: 该场次全部 lot 列表数据(阶段一字段,不含详情)。
  409. """
  410. lots = fetch_auction_lots(log, session, impersonate, auction)
  411. if sql_pool is not None:
  412. if lots:
  413. sql_pool.insert_many(table="scp_lot_record", data_list=lots, ignore=True)
  414. # 标记该场 lot 列表已抓
  415. sql_pool.update_one_or_dict(
  416. table="scp_auction_record",
  417. data={"lots_state": 1},
  418. condition={"event_id": auction["event_id"]},
  419. )
  420. log.info(f"场次 {auction['event_id']}({auction.get('auction_name')}) 共抓 {len(lots)} 条 lot")
  421. return lots
  422. def get_details(log, detail_url, sql_pool, sql_id):
  423. """对单条已入库 lot 补抓详情(阶段二),写回 scp_lot_record。
  424. Args:
  425. log: logger 对象。
  426. detail_url (str): 详情页 URL。
  427. sql_pool: MySQL 连接池。
  428. sql_id: 数据库记录 id。
  429. Returns:
  430. None: 仅入库,无返回值。
  431. """
  432. log.info(f">>> 补抓详情 {detail_url}")
  433. impersonate = random.choice(client_identifier_list)
  434. with requests.Session() as session:
  435. detail = fetch_lot_detail(log, session, impersonate, detail_url)
  436. # 详情字段 + 标记已抓;成交价/状态/出价以详情页为准(覆盖列表阶段的值)
  437. data = {**detail, "state": 1}
  438. sql_pool.update_one_or_dict(
  439. table="scp_lot_record",
  440. data=data,
  441. condition={"id": sql_id},
  442. )
  443. def update_details_for_pending(log, sql_pool):
  444. """扫库里 state != 1 的 lot,逐条补抓详情。
  445. Args:
  446. log: logger 对象。
  447. sql_pool: MySQL 连接池。
  448. Returns:
  449. None: 仅入库,无返回值。
  450. """
  451. log.debug("Updating detail pages ...")
  452. rows = sql_pool.select_all(
  453. "select id, detail_url from scp_lot_record where state != 1"
  454. )
  455. for row in rows:
  456. sql_id, detail_url = row[0], row[1]
  457. try:
  458. get_details(log, detail_url, sql_pool, sql_id)
  459. except Exception as e:
  460. log.error(f"Error getting details for {detail_url}: {e}")
  461. sql_pool.update_one_or_dict(
  462. table="scp_lot_record",
  463. data={"state": 2},
  464. condition={"id": sql_id},
  465. )