HeadlessBrowserService.ts 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175
  1. /// <reference lib="dom" />
  2. import { chromium, type BrowserContext, type Page } from 'playwright';
  3. import { logger } from '../utils/logger.js';
  4. import type { PlatformType } from '@media-manager/shared';
  5. // 抖音 API 接口配置
  6. const DOUYIN_API = {
  7. // 检查用户登录状态 - 返回 result: true 表示已登录(需要在浏览器上下文中调用)
  8. CHECK_USER: '/aweme/v1/creator/check/user/',
  9. // 获取作品列表(新接口,支持分页)
  10. WORK_LIST: 'https://creator.douyin.com/janus/douyin/creator/pc/work_list',
  11. // 获取评论列表
  12. COMMENT_LIST: 'https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/',
  13. // 创作者首页(用于触发登录检查)
  14. CREATOR_HOME: 'https://creator.douyin.com/creator-micro/home',
  15. };
  16. // 平台 API 配置(用于直接 HTTP 请求检查)
  17. const PLATFORM_API_CONFIG: Record<string, {
  18. checkUrl: string;
  19. isValidResponse: (data: unknown) => boolean;
  20. }> = {
  21. douyin: {
  22. // 使用账号基础信息接口检查 Cookie 有效性
  23. checkUrl: 'https://creator.douyin.com/web/api/creator/mcn/account_base_info?show_mcn_status=1',
  24. isValidResponse: (data: unknown) => {
  25. const resp = data as { status_code?: number; BaseResp?: { StatusCode?: number } };
  26. // status_code 为 0 表示 Cookie 有效
  27. return resp?.status_code === 0 || resp?.BaseResp?.StatusCode === 0;
  28. },
  29. },
  30. };
  31. export interface AccountInfo {
  32. accountId: string;
  33. accountName: string;
  34. avatarUrl: string;
  35. fansCount: number;
  36. worksCount: number;
  37. worksList?: WorkItem[];
  38. }
  39. export interface WorkItem {
  40. videoId?: string;
  41. title: string;
  42. coverUrl: string;
  43. duration: string;
  44. publishTime: string;
  45. status: string;
  46. playCount: number;
  47. likeCount: number;
  48. commentCount: number;
  49. shareCount: number;
  50. }
  51. export interface CommentItem {
  52. commentId: string;
  53. authorId: string;
  54. authorName: string;
  55. authorAvatar: string;
  56. content: string;
  57. likeCount: number;
  58. commentTime: string;
  59. parentCommentId?: string;
  60. videoId?: string;
  61. videoTitle?: string;
  62. videoCoverUrl?: string;
  63. }
  64. export interface WorkComments {
  65. videoId: string;
  66. videoTitle: string;
  67. videoCoverUrl: string;
  68. comments: CommentItem[];
  69. }
  70. export interface CookieData {
  71. name: string;
  72. value: string;
  73. domain: string;
  74. path: string;
  75. }
  76. /**
  77. * 无头浏览器服务 - 用于后台静默获取账号信息
  78. */
  79. class HeadlessBrowserService {
  80. /**
  81. * 检查 Cookie 是否有效
  82. * 优先使用 API 检查,如果平台不支持 API 则使用浏览器检查
  83. */
  84. async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
  85. // 优先使用 API 检查(更快更可靠)
  86. const apiConfig = PLATFORM_API_CONFIG[platform];
  87. if (apiConfig) {
  88. return this.checkCookieValidByApi(platform, cookies, apiConfig);
  89. }
  90. // 其他平台使用浏览器检查
  91. return this.checkCookieValidByBrowser(platform, cookies);
  92. }
  93. /**
  94. * 通过 API 检查 Cookie 是否有效
  95. */
  96. private async checkCookieValidByApi(
  97. platform: PlatformType,
  98. cookies: CookieData[],
  99. apiConfig: typeof PLATFORM_API_CONFIG[string]
  100. ): Promise<boolean> {
  101. try {
  102. // 构建 Cookie 字符串(所有 Cookie 拼接)
  103. const cookieString = cookies
  104. .map(c => `${c.name}=${c.value}`)
  105. .join('; ');
  106. logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);
  107. // 发起 API 请求,模拟浏览器请求
  108. const response = await fetch(apiConfig.checkUrl, {
  109. method: 'GET',
  110. headers: {
  111. 'Accept': 'application/json, text/plain, */*',
  112. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  113. 'Cache-Control': 'no-cache',
  114. 'Cookie': cookieString,
  115. 'Pragma': 'no-cache',
  116. 'Referer': this.getPlatformReferer(platform),
  117. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  118. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  119. 'sec-ch-ua-mobile': '?0',
  120. 'sec-ch-ua-platform': '"Windows"',
  121. 'sec-fetch-dest': 'empty',
  122. 'sec-fetch-mode': 'cors',
  123. 'sec-fetch-site': 'same-origin',
  124. },
  125. });
  126. const data = await response.json();
  127. const isValid = apiConfig.isValidResponse(data);
  128. logger.info(`API check cookie for ${platform}: valid=${isValid}, status_code=${(data as { status_code?: number })?.status_code}`);
  129. return isValid;
  130. } catch (error) {
  131. logger.error(`API check cookie error for ${platform}:`, error);
  132. // API 检查失败时,回退到浏览器检查
  133. return this.checkCookieValidByBrowser(platform, cookies);
  134. }
  135. }
  136. /**
  137. * 获取平台 Referer
  138. */
  139. private getPlatformReferer(platform: PlatformType): string {
  140. const referers: Record<string, string> = {
  141. douyin: 'https://creator.douyin.com/',
  142. bilibili: 'https://member.bilibili.com/',
  143. kuaishou: 'https://cp.kuaishou.com/',
  144. };
  145. return referers[platform] || '';
  146. }
  147. /**
  148. * 通过浏览器检查 Cookie 是否有效(检查是否被重定向到登录页)
  149. */
  150. private async checkCookieValidByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
  151. // 对于抖音平台,使用 check/user 接口检查
  152. if (platform === 'douyin') {
  153. return this.checkDouyinLoginByApi(cookies);
  154. }
  155. const browser = await chromium.launch({ headless: true });
  156. try {
  157. const context = await browser.newContext({
  158. viewport: { width: 1920, height: 1080 },
  159. locale: 'zh-CN',
  160. timezoneId: 'Asia/Shanghai',
  161. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  162. });
  163. await context.addCookies(cookies);
  164. const page = await context.newPage();
  165. const config = this.getPlatformConfig(platform);
  166. // 访问平台主页
  167. await page.goto(config.homeUrl, {
  168. waitUntil: 'domcontentloaded',
  169. timeout: 30000,
  170. });
  171. await page.waitForTimeout(3000);
  172. const url = page.url();
  173. logger.info(`Browser check cookie for ${platform}: URL=${url}`);
  174. // 检查是否被重定向到登录页
  175. const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));
  176. await page.close();
  177. await context.close();
  178. await browser.close();
  179. return !isLoginPage;
  180. } catch (error) {
  181. logger.error(`Browser check cookie error for ${platform}:`, error);
  182. await browser.close();
  183. return false;
  184. }
  185. }
  186. /**
  187. * 抖音登录状态检查 - 通过监听 check/user 接口
  188. * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
  189. */
  190. async checkDouyinLoginByApi(cookies: CookieData[]): Promise<boolean> {
  191. const browser = await chromium.launch({ headless: true });
  192. let isLoggedIn = false;
  193. let checkCompleted = false;
  194. try {
  195. const context = await browser.newContext({
  196. viewport: { width: 1920, height: 1080 },
  197. locale: 'zh-CN',
  198. timezoneId: 'Asia/Shanghai',
  199. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  200. });
  201. await context.addCookies(cookies);
  202. const page = await context.newPage();
  203. // 监听 check/user 接口响应
  204. page.on('response', async (response) => {
  205. const url = response.url();
  206. if (url.includes(DOUYIN_API.CHECK_USER)) {
  207. try {
  208. const data = await response.json();
  209. // result: true 表示已登录
  210. isLoggedIn = data?.result === true && data?.status_code === 0;
  211. checkCompleted = true;
  212. logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
  213. } catch {
  214. // 忽略解析错误
  215. }
  216. }
  217. });
  218. // 访问创作者首页,触发 check/user 接口
  219. await page.goto(DOUYIN_API.CREATOR_HOME, {
  220. waitUntil: 'domcontentloaded',
  221. timeout: 30000,
  222. });
  223. // 等待接口响应或超时
  224. const startTime = Date.now();
  225. while (!checkCompleted && Date.now() - startTime < 10000) {
  226. await page.waitForTimeout(500);
  227. }
  228. // 如果没有收到 check/user 响应,检查 URL 是否被重定向到登录页
  229. if (!checkCompleted) {
  230. const currentUrl = page.url();
  231. isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
  232. logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
  233. }
  234. await page.close();
  235. await context.close();
  236. await browser.close();
  237. return isLoggedIn;
  238. } catch (error) {
  239. logger.error('[Douyin] checkDouyinLoginByApi error:', error);
  240. try {
  241. await browser.close();
  242. } catch { }
  243. return false;
  244. }
  245. }
  246. /**
  247. * 获取账号信息(使用无头浏览器)
  248. */
  249. async fetchAccountInfo(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
  250. const browser = await chromium.launch({ headless: true });
  251. try {
  252. const context = await browser.newContext({
  253. viewport: { width: 1920, height: 1080 },
  254. locale: 'zh-CN',
  255. timezoneId: 'Asia/Shanghai',
  256. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  257. });
  258. await context.addCookies(cookies);
  259. const page = await context.newPage();
  260. let accountInfo: AccountInfo;
  261. switch (platform) {
  262. case 'douyin':
  263. accountInfo = await this.fetchDouyinAccountInfo(page, context, cookies);
  264. break;
  265. case 'bilibili':
  266. accountInfo = await this.fetchBilibiliAccountInfo(page, context, cookies);
  267. break;
  268. case 'kuaishou':
  269. accountInfo = await this.fetchKuaishouAccountInfo(page, context, cookies);
  270. break;
  271. case 'xiaohongshu':
  272. accountInfo = await this.fetchXiaohongshuAccountInfo(page, context, cookies);
  273. break;
  274. default:
  275. accountInfo = this.getDefaultAccountInfo(platform);
  276. }
  277. await page.close();
  278. await context.close();
  279. await browser.close();
  280. return accountInfo;
  281. } catch (error) {
  282. logger.error('HeadlessBrowser fetchAccountInfo error:', error);
  283. await browser.close();
  284. return this.getDefaultAccountInfo(platform);
  285. }
  286. }
  287. /**
  288. * 获取抖音账号信息 - 通过 API 方式获取
  289. * 1. 监听 check/user 接口验证登录状态
  290. * 2. 通过 work_list API 获取作品数和作品列表
  291. */
  292. private async fetchDouyinAccountInfo(
  293. page: Page,
  294. _context: BrowserContext,
  295. cookies: CookieData[]
  296. ): Promise<AccountInfo> {
  297. let accountId = `douyin_${Date.now()}`;
  298. let accountName = '抖音账号';
  299. let avatarUrl = '';
  300. let fansCount = 0;
  301. let worksCount = 0;
  302. let worksList: WorkItem[] = [];
  303. let isLoggedIn = false;
  304. // 用于存储从 API 捕获的数据
  305. const capturedData: {
  306. userInfo?: {
  307. nickname?: string;
  308. avatar?: string;
  309. uid?: string;
  310. sec_uid?: string;
  311. unique_id?: string; // 抖音号(如 Ethanfly9392)
  312. short_id?: string; // 短ID
  313. follower_count?: number;
  314. };
  315. worksList?: Array<{
  316. awemeId: string;
  317. title: string;
  318. coverUrl: string;
  319. duration: number;
  320. createTime: number;
  321. statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number };
  322. }>;
  323. total?: number;
  324. } = {};
  325. try {
  326. // 从 Cookie 获取用户 ID
  327. const uidCookie = cookies.find(c =>
  328. ['passport_uid', 'uid', 'ssid'].includes(c.name)
  329. );
  330. if (uidCookie?.value) {
  331. accountId = `douyin_${uidCookie.value}`;
  332. }
  333. // 设置 API 响应监听器
  334. page.on('response', async (response) => {
  335. const url = response.url();
  336. try {
  337. // 监听 check/user 接口 - 验证登录状态
  338. if (url.includes(DOUYIN_API.CHECK_USER)) {
  339. const data = await response.json();
  340. isLoggedIn = data?.result === true && data?.status_code === 0;
  341. logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
  342. }
  343. // 监听 work_list 接口 - 获取作品列表
  344. if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
  345. const data = await response.json();
  346. if (data?.aweme_list) {
  347. // 获取总数
  348. if (data.total !== undefined) {
  349. capturedData.total = data.total;
  350. }
  351. // 解析作品列表
  352. capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
  353. const statistics = aweme.statistics as Record<string, unknown> || {};
  354. const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
  355. const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';
  356. return {
  357. awemeId: String(aweme.aweme_id || ''),
  358. title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
  359. coverUrl,
  360. duration: Number(aweme.duration || 0),
  361. createTime: Number(aweme.create_time || 0),
  362. statistics: {
  363. play_count: Number(statistics.play_count || 0),
  364. digg_count: Number(statistics.digg_count || 0),
  365. comment_count: Number(statistics.comment_count || 0),
  366. share_count: Number(statistics.share_count || 0),
  367. },
  368. };
  369. });
  370. logger.info(`[Douyin API] work_list: total=${capturedData.total}, items=${capturedData.worksList?.length}`);
  371. }
  372. }
  373. // 监听账号信息接口 - 增加更多可能的接口
  374. if (url.includes('/account_base_info') ||
  375. url.includes('/user/info') ||
  376. url.includes('/creator/user') ||
  377. url.includes('/data/overview') ||
  378. url.includes('/creator-micro/data') ||
  379. url.includes('/home_data')) {
  380. const data = await response.json();
  381. logger.info(`[Douyin API] Captured response from: ${url.split('?')[0]}`);
  382. // 尝试多种数据结构
  383. const user = data?.user || data?.data?.user || data?.data || data;
  384. if (user) {
  385. const nickname = user.nickname || user.name || user.nick_name || user.user_name;
  386. const avatar = user.avatar_url || user.avatar_thumb?.url_list?.[0] || user.avatar || user.avatar_larger?.url_list?.[0];
  387. const uid = user.uid || user.user_id || user.id;
  388. const fans = user.follower_count || user.fans_count || user.mplatform_followers_count;
  389. // 获取抖音号(unique_id 或 short_id)
  390. const uniqueId = user.unique_id || user.short_id || user.douyin_id;
  391. if (nickname || uid || uniqueId) {
  392. capturedData.userInfo = {
  393. nickname: nickname,
  394. avatar: avatar,
  395. uid: uid,
  396. sec_uid: user.sec_uid,
  397. unique_id: uniqueId,
  398. short_id: user.short_id,
  399. follower_count: fans,
  400. };
  401. logger.info(`[Douyin API] user info captured: nickname=${capturedData.userInfo.nickname}, uid=${capturedData.userInfo.uid}, unique_id=${capturedData.userInfo.unique_id}`);
  402. }
  403. }
  404. }
  405. } catch (e) {
  406. // 忽略非 JSON 响应
  407. }
  408. });
  409. // 访问主页获取基本信息并触发 check/user 接口
  410. logger.info('[Douyin] Navigating to creator home...');
  411. await page.goto(DOUYIN_API.CREATOR_HOME, {
  412. waitUntil: 'domcontentloaded',
  413. timeout: 30000,
  414. });
  415. // 等待页面加载完成
  416. await page.waitForTimeout(3000);
  417. // 尝试等待网络空闲
  418. try {
  419. await page.waitForLoadState('networkidle', { timeout: 10000 });
  420. } catch {
  421. // 超时继续
  422. }
  423. // 额外等待确保 API 响应被捕获
  424. await page.waitForTimeout(2000);
  425. // 检查登录状态 - 如果没有从 API 获取到,通过 URL 判断
  426. if (!isLoggedIn) {
  427. const currentUrl = page.url();
  428. isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
  429. }
  430. if (!isLoggedIn) {
  431. logger.warn('[Douyin] Not logged in, returning default account info');
  432. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  433. }
  434. // 从页面提取基本账号信息(作为 API 数据的补充)
  435. const accountData = await page.evaluate(() => {
  436. const result: { name?: string; avatar?: string; fans?: number; douyinId?: string } = {};
  437. // 提取抖音号 - 多种方式
  438. // 方式1:通过选择器查找包含抖音号的元素
  439. const uniqueIdSelectors = [
  440. 'div[class*="unique"]',
  441. 'span[class*="unique"]',
  442. 'div[class*="douyin-id"]',
  443. 'span[class*="douyin-id"]',
  444. '[class*="account-id"]',
  445. '[class*="shortId"]',
  446. '[class*="short-id"]',
  447. ];
  448. for (const selector of uniqueIdSelectors) {
  449. const el = document.querySelector(selector);
  450. if (el) {
  451. const text = el.textContent?.trim() || '';
  452. const match = text.match(/抖音号[::]\s*(\S+)/) || text.match(/ID[::]\s*(\S+)/);
  453. if (match) {
  454. result.douyinId = match[1];
  455. break;
  456. }
  457. // 如果元素文本本身就是抖音号(无前缀)
  458. if (text && !text.includes('抖音号') && /^[a-zA-Z0-9_]+$/.test(text)) {
  459. result.douyinId = text;
  460. break;
  461. }
  462. }
  463. }
  464. // 方式2:全局搜索包含"抖音号"的文本
  465. if (!result.douyinId) {
  466. const allElements = Array.from(document.querySelectorAll('span, div, p'));
  467. for (const el of allElements) {
  468. const text = el.textContent?.trim() || '';
  469. // 匹配 "抖音号:xxx" 或 "抖音号: xxx"
  470. const match = text.match(/抖音号[::]\s*([a-zA-Z0-9_]+)/);
  471. if (match && match[1]) {
  472. result.douyinId = match[1];
  473. break;
  474. }
  475. }
  476. }
  477. // 查找头像 - 优先使用头像容器
  478. const avatarSelectors = [
  479. '[class*="avatar"] img',
  480. '[class*="user-avatar"] img',
  481. '[class*="profile"] img',
  482. 'img[class*="avatar"]',
  483. ];
  484. for (const selector of avatarSelectors) {
  485. const img = document.querySelector(selector) as HTMLImageElement;
  486. if (img?.src && (img.src.includes('aweme') || img.src.includes('douyinpic') || img.src.includes('bytedance'))) {
  487. result.avatar = img.src;
  488. break;
  489. }
  490. }
  491. // 备用方案:查找所有图片
  492. if (!result.avatar) {
  493. const avatarImgs = Array.from(document.querySelectorAll('img'));
  494. for (const img of avatarImgs) {
  495. const src = img.src || img.getAttribute('src') || '';
  496. if (src && (src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance'))) {
  497. const rect = img.getBoundingClientRect();
  498. if (rect.width > 30 && rect.width < 150 && rect.top < 300) {
  499. result.avatar = src;
  500. break;
  501. }
  502. }
  503. }
  504. }
  505. // 获取粉丝数 - 多种选择器
  506. const fansSelectors = [
  507. '#guide_home_fans',
  508. '[class*="fans"]',
  509. '[class*="follower"]',
  510. '[class*="data-item"]',
  511. ];
  512. for (const selector of fansSelectors) {
  513. const el = document.querySelector(selector);
  514. if (el) {
  515. const text = el.textContent?.trim() || '';
  516. // 匹配 "123" 或 "1.2万" 或 "粉丝 123"
  517. const match = text.match(/(\d+(?:\.\d+)?)\s*([万wW])?/);
  518. if (match) {
  519. let num = parseFloat(match[1]);
  520. if (match[2]) num *= 10000;
  521. result.fans = Math.floor(num);
  522. break;
  523. }
  524. }
  525. }
  526. // 查找用户名 - 更精确的选择器
  527. const nameSelectors = [
  528. '[class*="user-name"]',
  529. '[class*="nickname"]',
  530. '[class*="author-name"]',
  531. '[class*="profile-name"]',
  532. 'h1[class*="name"]',
  533. 'h2[class*="name"]',
  534. ];
  535. for (const selector of nameSelectors) {
  536. const el = document.querySelector(selector);
  537. if (el) {
  538. const text = el.textContent?.trim() || '';
  539. if (text && text.length >= 2 && text.length <= 30) {
  540. result.name = text;
  541. break;
  542. }
  543. }
  544. }
  545. // 备用方案:查找包含名字的容器
  546. if (!result.name) {
  547. const nameContainers = Array.from(document.querySelectorAll('[class*="name"], [class*="nick"], [class*="user"]'));
  548. for (const container of nameContainers) {
  549. const text = container.textContent?.trim() || '';
  550. if (text &&
  551. text.length >= 2 &&
  552. text.length <= 20 &&
  553. !text.includes('关注') &&
  554. !text.includes('粉丝') &&
  555. !text.includes('获赞') &&
  556. !text.includes('加载') &&
  557. !text.includes('创作') &&
  558. !text.includes('发布') &&
  559. !text.includes('抖音号') &&
  560. !text.match(/^\d+$/)) {
  561. const rect = container.getBoundingClientRect();
  562. if (rect.top < 400 && rect.left < 500) {
  563. result.name = text;
  564. break;
  565. }
  566. }
  567. }
  568. }
  569. return result;
  570. });
  571. // 优先使用抖音号作为 ID(unique_id),其次是页面提取的抖音号,最后是 uid
  572. if (capturedData.userInfo?.unique_id) {
  573. // 优先使用抖音号(如 Ethanfly9392)
  574. accountId = `douyin_${capturedData.userInfo.unique_id}`;
  575. logger.info(`[Douyin] Using unique_id as accountId: ${accountId}`);
  576. } else if (capturedData.userInfo?.short_id) {
  577. // 其次使用短ID
  578. accountId = `douyin_${capturedData.userInfo.short_id}`;
  579. logger.info(`[Douyin] Using short_id as accountId: ${accountId}`);
  580. } else if (accountData.douyinId) {
  581. // 使用页面提取的抖音号
  582. accountId = `douyin_${accountData.douyinId}`;
  583. logger.info(`[Douyin] Using page douyinId as accountId: ${accountId}`);
  584. } else if (capturedData.userInfo?.uid) {
  585. // 最后使用内部uid
  586. accountId = `douyin_${capturedData.userInfo.uid}`;
  587. logger.info(`[Douyin] Using uid as accountId: ${accountId}`);
  588. }
  589. accountName = capturedData.userInfo?.nickname || accountData.name || accountName;
  590. avatarUrl = capturedData.userInfo?.avatar || accountData.avatar || avatarUrl;
  591. fansCount = capturedData.userInfo?.follower_count || accountData.fans || fansCount;
  592. // 通过 API 获取作品列表
  593. logger.info('[Douyin] Fetching works via API...');
  594. const apiWorks = await this.fetchWorksDirectApi(page);
  595. if (apiWorks.length > 0) {
  596. worksCount = apiWorks.length;
  597. worksList = apiWorks.map(w => ({
  598. videoId: w.awemeId,
  599. title: w.title,
  600. coverUrl: w.coverUrl,
  601. duration: '00:00',
  602. publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
  603. status: 'published',
  604. playCount: 0,
  605. likeCount: 0,
  606. commentCount: w.commentCount,
  607. shareCount: 0,
  608. }));
  609. logger.info(`[Douyin] Got ${worksCount} works from API`);
  610. } else if (capturedData.worksList && capturedData.worksList.length > 0) {
  611. // 如果直接 API 调用失败,使用监听到的数据
  612. worksCount = capturedData.total || capturedData.worksList.length;
  613. worksList = capturedData.worksList.map(w => ({
  614. videoId: w.awemeId,
  615. title: w.title,
  616. coverUrl: w.coverUrl,
  617. duration: this.formatDuration(w.duration),
  618. publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
  619. status: 'published',
  620. playCount: w.statistics.play_count,
  621. likeCount: w.statistics.digg_count,
  622. commentCount: w.statistics.comment_count,
  623. shareCount: w.statistics.share_count,
  624. }));
  625. logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
  626. }
  627. } catch (error) {
  628. logger.warn('Failed to fetch Douyin account info:', error);
  629. }
  630. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  631. }
  632. /**
  633. * 格式化视频时长
  634. */
  635. private formatDuration(ms: number): string {
  636. if (!ms) return '00:00';
  637. const seconds = Math.floor(ms / 1000);
  638. const minutes = Math.floor(seconds / 60);
  639. const remainingSeconds = seconds % 60;
  640. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  641. }
  642. /**
  643. * 获取B站账号信息
  644. */
  645. private async fetchBilibiliAccountInfo(
  646. page: Page,
  647. _context: BrowserContext,
  648. cookies: CookieData[]
  649. ): Promise<AccountInfo> {
  650. let accountId = `bilibili_${Date.now()}`;
  651. let accountName = 'B站账号';
  652. let avatarUrl = '';
  653. let fansCount = 0;
  654. let worksCount = 0;
  655. try {
  656. const uidCookie = cookies.find(c => c.name === 'DedeUserID');
  657. if (uidCookie?.value) {
  658. accountId = `bilibili_${uidCookie.value}`;
  659. }
  660. await page.goto('https://member.bilibili.com/platform/home', {
  661. waitUntil: 'domcontentloaded',
  662. timeout: 30000,
  663. });
  664. await page.waitForTimeout(3000);
  665. // 获取用户名
  666. const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
  667. if (nameEl) {
  668. const text = await nameEl.textContent();
  669. if (text?.trim()) {
  670. accountName = text.trim();
  671. }
  672. }
  673. // 获取头像
  674. const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
  675. if (avatarEl) {
  676. const src = await avatarEl.getAttribute('src');
  677. if (src) {
  678. avatarUrl = src;
  679. }
  680. }
  681. } catch (error) {
  682. logger.warn('Failed to fetch Bilibili account info:', error);
  683. }
  684. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  685. }
  686. /**
  687. * 获取快手账号信息
  688. */
  689. private async fetchKuaishouAccountInfo(
  690. page: Page,
  691. _context: BrowserContext,
  692. cookies: CookieData[]
  693. ): Promise<AccountInfo> {
  694. let accountId = `kuaishou_${Date.now()}`;
  695. let accountName = '快手账号';
  696. let avatarUrl = '';
  697. let fansCount = 0;
  698. let worksCount = 0;
  699. try {
  700. const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
  701. if (uidCookie?.value) {
  702. accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
  703. }
  704. await page.goto('https://cp.kuaishou.com/profile', {
  705. waitUntil: 'domcontentloaded',
  706. timeout: 30000,
  707. });
  708. await page.waitForTimeout(3000);
  709. // 获取用户名
  710. const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
  711. if (nameEl) {
  712. const text = await nameEl.textContent();
  713. if (text?.trim()) {
  714. accountName = text.trim();
  715. }
  716. }
  717. // 获取头像
  718. const avatarEl = await page.$('[class*="avatar"] img');
  719. if (avatarEl) {
  720. const src = await avatarEl.getAttribute('src');
  721. if (src) {
  722. avatarUrl = src;
  723. }
  724. }
  725. } catch (error) {
  726. logger.warn('Failed to fetch Kuaishou account info:', error);
  727. }
  728. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  729. }
  730. /**
  731. * 获取小红书账号信息 - 通过 API 方式获取
  732. */
  733. private async fetchXiaohongshuAccountInfo(
  734. page: Page,
  735. _context: BrowserContext,
  736. cookies: CookieData[]
  737. ): Promise<AccountInfo> {
  738. let accountId = `xiaohongshu_${Date.now()}`;
  739. let accountName = '小红书账号';
  740. let avatarUrl = '';
  741. let fansCount = 0;
  742. let worksCount = 0;
  743. // 用于存储捕获的数据
  744. const capturedData: {
  745. userInfo?: {
  746. nickname?: string;
  747. avatar?: string;
  748. userId?: string;
  749. redId?: string;
  750. fans?: number;
  751. notes?: number;
  752. };
  753. } = {};
  754. try {
  755. // 从 Cookie 获取用户 ID
  756. const userIdCookie = cookies.find(c =>
  757. c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
  758. );
  759. if (userIdCookie?.value) {
  760. accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
  761. }
  762. // 设置 API 响应监听器
  763. page.on('response', async (response) => {
  764. const url = response.url();
  765. try {
  766. // 监听用户信息 API
  767. if (url.includes('/api/galaxy/creator/home/personal_info') ||
  768. url.includes('/api/sns/web/v1/user/selfinfo') ||
  769. url.includes('/user/selfinfo')) {
  770. const data = await response.json();
  771. logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));
  772. // 解析用户信息
  773. const userInfo = data?.data?.user_info || data?.data || data;
  774. if (userInfo) {
  775. capturedData.userInfo = {
  776. nickname: userInfo.nickname || userInfo.name || userInfo.userName,
  777. avatar: userInfo.image || userInfo.avatar || userInfo.images,
  778. userId: userInfo.user_id || userInfo.userId,
  779. redId: userInfo.red_id || userInfo.redId,
  780. fans: userInfo.fans || userInfo.fansCount,
  781. notes: userInfo.notes || userInfo.noteCount,
  782. };
  783. logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
  784. }
  785. }
  786. // 监听创作者主页数据
  787. if (url.includes('/api/galaxy/creator/home/home_page') ||
  788. url.includes('/api/galaxy/creator/data')) {
  789. const data = await response.json();
  790. logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));
  791. if (data?.data) {
  792. const homeData = data.data;
  793. // 获取粉丝数和笔记数
  794. if (homeData.fans_count !== undefined) {
  795. capturedData.userInfo = capturedData.userInfo || {};
  796. capturedData.userInfo.fans = homeData.fans_count;
  797. }
  798. if (homeData.note_count !== undefined) {
  799. capturedData.userInfo = capturedData.userInfo || {};
  800. capturedData.userInfo.notes = homeData.note_count;
  801. }
  802. }
  803. }
  804. } catch {
  805. // 忽略非 JSON 响应
  806. }
  807. });
  808. // 导航到小红书创作者中心
  809. logger.info('[Xiaohongshu] Navigating to creator center...');
  810. await page.goto('https://creator.xiaohongshu.com/creator/home', {
  811. waitUntil: 'domcontentloaded',
  812. timeout: 30000,
  813. });
  814. // 等待页面加载
  815. await page.waitForTimeout(3000);
  816. // 检查是否需要登录
  817. const currentUrl = page.url();
  818. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  819. logger.warn('[Xiaohongshu] Cookie expired, needs login');
  820. return this.getDefaultAccountInfo('xiaohongshu');
  821. }
  822. // 等待 API 响应
  823. await page.waitForTimeout(3000);
  824. // 如果 API 没有捕获到数据,尝试从页面提取
  825. if (!capturedData.userInfo?.nickname) {
  826. logger.info('[Xiaohongshu] API did not return data, extracting from page...');
  827. // 尝试获取用户名
  828. const nameSelectors = [
  829. '[class*="nickname"]',
  830. '[class*="user-name"]',
  831. '[class*="userName"]',
  832. '.user-info .name',
  833. '[class*="creator"] [class*="name"]',
  834. ];
  835. for (const selector of nameSelectors) {
  836. const el = await page.$(selector);
  837. if (el) {
  838. const text = await el.textContent();
  839. if (text?.trim() && text.trim().length < 50) {
  840. accountName = text.trim();
  841. logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
  842. break;
  843. }
  844. }
  845. }
  846. // 尝试获取头像
  847. const avatarSelectors = [
  848. '[class*="avatar"] img',
  849. '[class*="user-avatar"] img',
  850. '.user-info img',
  851. '[class*="creator"] img[src*="sns"]',
  852. ];
  853. for (const selector of avatarSelectors) {
  854. const el = await page.$(selector);
  855. if (el) {
  856. const src = await el.getAttribute('src');
  857. if (src && src.startsWith('http')) {
  858. avatarUrl = src;
  859. logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
  860. break;
  861. }
  862. }
  863. }
  864. // 尝试获取粉丝数
  865. const statsText = await page.textContent('body');
  866. const fansMatch = statsText?.match(/粉丝[::\s]*(\d+(?:\.\d+)?[万亿]?)/);
  867. if (fansMatch) {
  868. fansCount = this.parseChineseNumber(fansMatch[1]);
  869. logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
  870. }
  871. const notesMatch = statsText?.match(/笔记[::\s]*(\d+)/);
  872. if (notesMatch) {
  873. worksCount = parseInt(notesMatch[1], 10);
  874. logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
  875. }
  876. }
  877. // 使用捕获的数据
  878. if (capturedData.userInfo) {
  879. if (capturedData.userInfo.nickname) {
  880. accountName = capturedData.userInfo.nickname;
  881. }
  882. if (capturedData.userInfo.avatar) {
  883. avatarUrl = capturedData.userInfo.avatar;
  884. }
  885. if (capturedData.userInfo.userId) {
  886. accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
  887. } else if (capturedData.userInfo.redId) {
  888. accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
  889. }
  890. if (capturedData.userInfo.fans) {
  891. fansCount = capturedData.userInfo.fans;
  892. }
  893. if (capturedData.userInfo.notes) {
  894. worksCount = capturedData.userInfo.notes;
  895. }
  896. }
  897. logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
  898. // 获取作品列表 - 通过监听 API 接口
  899. const worksList: WorkItem[] = [];
  900. try {
  901. logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');
  902. // 存储所有捕获的笔记数据
  903. const allNotesData: Array<{
  904. noteId: string;
  905. title: string;
  906. coverUrl: string;
  907. status: number;
  908. publishTime: string;
  909. type: string;
  910. duration: number;
  911. likeCount: number;
  912. commentCount: number;
  913. collectCount: number;
  914. viewCount: number;
  915. shareCount: number;
  916. }> = [];
  917. let currentPage = 0;
  918. let hasMorePages = true;
  919. const maxPages = 20; // 最多获取20页,防止无限循环
  920. // 设置 API 响应监听器 - 在导航之前绑定
  921. let apiResponseReceived = false;
  922. let totalNotesCount = 0; // 从 tags 中获取的总作品数
  923. const notesApiHandler = async (response: import('playwright').Response) => {
  924. const url = response.url();
  925. try {
  926. // 监听小红书笔记列表 API
  927. // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
  928. if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
  929. url.includes('/api/sns/v5/creator/note/user/posted') ||
  930. url.includes('creator/note/user/posted')) {
  931. const data = await response.json();
  932. logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);
  933. if ((data?.success || data?.code === 0) && data?.data) {
  934. apiResponseReceived = true;
  935. // 从 tags 中获取总作品数
  936. // tags 数组中 id="special.note_time_desc" 的项("所有笔记")包含总数
  937. if (data.data.tags && Array.isArray(data.data.tags)) {
  938. const allNotesTag = data.data.tags.find((tag: { id?: string; notes_count?: number }) =>
  939. tag.id === 'special.note_time_desc'
  940. );
  941. if (allNotesTag?.notes_count !== undefined) {
  942. totalNotesCount = allNotesTag.notes_count;
  943. logger.info(`[Xiaohongshu API] Total notes count from tags: ${totalNotesCount}`);
  944. }
  945. }
  946. const notes = data.data.notes || [];
  947. for (const note of notes) {
  948. // 根据 API 返回格式解析数据
  949. // images_list 是数组,第一个元素包含 url
  950. // 将 http:// 转换为 https:// 以确保图片能正常加载
  951. let coverUrl = note.images_list?.[0]?.url || '';
  952. if (coverUrl.startsWith('http://')) {
  953. coverUrl = coverUrl.replace('http://', 'https://');
  954. }
  955. const duration = note.video_info?.duration || 0;
  956. logger.info(`[Xiaohongshu API] Note: id=${note.id}, title="${note.display_title}", cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
  957. allNotesData.push({
  958. noteId: note.id || '',
  959. title: note.display_title || '',
  960. coverUrl: coverUrl,
  961. status: note.tab_status || 1, // 1=已发布
  962. publishTime: note.time || '',
  963. type: note.type || 'normal', // video/normal
  964. duration: duration,
  965. likeCount: note.likes || 0,
  966. commentCount: note.comments_count || 0,
  967. collectCount: note.collected_count || 0,
  968. viewCount: note.view_count || 0,
  969. shareCount: note.shared_count || 0,
  970. });
  971. }
  972. // 检查是否还有更多页面
  973. // page=-1 表示没有更多数据
  974. if (data.data.page === -1 || notes.length === 0) {
  975. hasMorePages = false;
  976. logger.info(`[Xiaohongshu API] No more pages (page indicator: ${data.data.page})`);
  977. }
  978. } else {
  979. hasMorePages = false;
  980. }
  981. }
  982. } catch (e) {
  983. // 只在有相关 URL 时打印警告
  984. if (url.includes('creator/note')) {
  985. logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
  986. }
  987. }
  988. };
  989. // 先绑定监听器
  990. page.on('response', notesApiHandler);
  991. logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');
  992. // 导航到笔记管理页面
  993. await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
  994. waitUntil: 'networkidle', // 等待网络空闲,确保 API 已响应
  995. timeout: 30000,
  996. });
  997. // 等待初始页面加载和 API 响应
  998. await page.waitForTimeout(5000);
  999. logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);
  1000. // 如果监听器没有捕获到数据,尝试直接调用 API
  1001. if (allNotesData.length === 0) {
  1002. logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');
  1003. try {
  1004. // 直接在页面上下文中调用 API
  1005. const apiResponse = await page.evaluate(async () => {
  1006. const response = await fetch('https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=0', {
  1007. method: 'GET',
  1008. credentials: 'include',
  1009. headers: {
  1010. 'Accept': 'application/json',
  1011. },
  1012. });
  1013. return await response.json();
  1014. });
  1015. logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
  1016. if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
  1017. // 从 tags 中获取总作品数
  1018. if (apiResponse.data.tags && Array.isArray(apiResponse.data.tags)) {
  1019. const allNotesTag = apiResponse.data.tags.find((tag: { id?: string; notes_count?: number }) =>
  1020. tag.id === 'special.note_time_desc'
  1021. );
  1022. if (allNotesTag?.notes_count !== undefined) {
  1023. totalNotesCount = allNotesTag.notes_count;
  1024. logger.info(`[Xiaohongshu API Direct] Total notes count from tags: ${totalNotesCount}`);
  1025. }
  1026. }
  1027. const notes = apiResponse.data.notes || [];
  1028. for (const note of notes) {
  1029. // 将 http:// 转换为 https://
  1030. let coverUrl = note.images_list?.[0]?.url || '';
  1031. if (coverUrl.startsWith('http://')) {
  1032. coverUrl = coverUrl.replace('http://', 'https://');
  1033. }
  1034. const duration = note.video_info?.duration || 0;
  1035. logger.info(`[Xiaohongshu API Direct] Note: id=${note.id}, cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
  1036. allNotesData.push({
  1037. noteId: note.id || '',
  1038. title: note.display_title || '',
  1039. coverUrl: coverUrl,
  1040. status: note.tab_status || 1,
  1041. publishTime: note.time || '',
  1042. type: note.type || 'normal',
  1043. duration: duration,
  1044. likeCount: note.likes || 0,
  1045. commentCount: note.comments_count || 0,
  1046. collectCount: note.collected_count || 0,
  1047. viewCount: note.view_count || 0,
  1048. shareCount: note.shared_count || 0,
  1049. });
  1050. }
  1051. // 获取更多页面
  1052. let pageNum = 1;
  1053. let lastPage = apiResponse.data.page;
  1054. while (lastPage !== -1 && pageNum < maxPages) {
  1055. const nextResponse = await page.evaluate(async (p) => {
  1056. const response = await fetch(`https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}`, {
  1057. method: 'GET',
  1058. credentials: 'include',
  1059. });
  1060. return await response.json();
  1061. }, pageNum);
  1062. if (nextResponse?.data?.notes?.length > 0) {
  1063. for (const note of nextResponse.data.notes) {
  1064. // 将 http:// 转换为 https://
  1065. let coverUrl = note.images_list?.[0]?.url || '';
  1066. if (coverUrl.startsWith('http://')) {
  1067. coverUrl = coverUrl.replace('http://', 'https://');
  1068. }
  1069. const duration = note.video_info?.duration || 0;
  1070. allNotesData.push({
  1071. noteId: note.id || '',
  1072. title: note.display_title || '',
  1073. coverUrl: coverUrl,
  1074. status: note.tab_status || 1,
  1075. publishTime: note.time || '',
  1076. type: note.type || 'normal',
  1077. duration: duration,
  1078. likeCount: note.likes || 0,
  1079. commentCount: note.comments_count || 0,
  1080. collectCount: note.collected_count || 0,
  1081. viewCount: note.view_count || 0,
  1082. shareCount: note.shared_count || 0,
  1083. });
  1084. }
  1085. pageNum++;
  1086. lastPage = nextResponse.data.page;
  1087. if (lastPage === -1) break;
  1088. } else {
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. } catch (apiError) {
  1094. logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
  1095. }
  1096. }
  1097. // 如果还是没有数据,尝试滚动加载
  1098. if (allNotesData.length === 0) {
  1099. logger.info('[Xiaohongshu] Still no notes, trying scroll to trigger API...');
  1100. await page.waitForTimeout(2000);
  1101. }
  1102. // 滚动加载更多页面(如果通过监听器获取的数据)
  1103. while (hasMorePages && currentPage < maxPages && allNotesData.length > 0 && apiResponseReceived) {
  1104. currentPage++;
  1105. const previousCount = allNotesData.length;
  1106. // 滚动到页面底部触发加载更多
  1107. await page.evaluate(() => {
  1108. window.scrollTo(0, document.body.scrollHeight);
  1109. });
  1110. // 等待新数据加载
  1111. await page.waitForTimeout(2000);
  1112. // 如果没有新数据,退出循环
  1113. if (allNotesData.length === previousCount) {
  1114. logger.info(`[Xiaohongshu] No new notes loaded after scroll, stopping at page ${currentPage}`);
  1115. break;
  1116. }
  1117. logger.info(`[Xiaohongshu] Page ${currentPage}: total ${allNotesData.length} notes`);
  1118. }
  1119. // 移除监听器
  1120. page.off('response', notesApiHandler);
  1121. logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);
  1122. // 转换为 WorkItem 格式
  1123. for (const note of allNotesData) {
  1124. // 转换时长为 mm:ss 格式
  1125. const minutes = Math.floor(note.duration / 60);
  1126. const seconds = note.duration % 60;
  1127. const durationStr = note.duration > 0
  1128. ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  1129. : '';
  1130. // 转换状态
  1131. let statusStr = 'published';
  1132. if (note.status === 0) statusStr = 'draft';
  1133. else if (note.status === 2) statusStr = 'reviewing';
  1134. else if (note.status === 3) statusStr = 'rejected';
  1135. worksList.push({
  1136. videoId: note.noteId,
  1137. title: note.title || '无标题',
  1138. coverUrl: note.coverUrl,
  1139. duration: durationStr,
  1140. publishTime: note.publishTime,
  1141. status: statusStr,
  1142. playCount: note.viewCount,
  1143. likeCount: note.likeCount,
  1144. commentCount: note.commentCount,
  1145. shareCount: note.shareCount,
  1146. });
  1147. }
  1148. logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);
  1149. // 更新作品数:优先使用从 API tags 获取的总数
  1150. if (totalNotesCount > 0) {
  1151. worksCount = totalNotesCount;
  1152. logger.info(`[Xiaohongshu] Using total notes count from API: ${worksCount}`);
  1153. } else if (worksList.length > 0) {
  1154. worksCount = worksList.length;
  1155. logger.info(`[Xiaohongshu] Using works list length: ${worksCount}`);
  1156. }
  1157. } catch (worksError) {
  1158. logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
  1159. }
  1160. logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
  1161. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  1162. } catch (error) {
  1163. logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
  1164. }
  1165. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1166. }
  1167. /**
  1168. * 解析中文数字(如 1.2万 -> 12000)
  1169. */
  1170. private parseChineseNumber(str: string): number {
  1171. if (!str) return 0;
  1172. let num = parseFloat(str);
  1173. if (str.includes('万')) {
  1174. num *= 10000;
  1175. } else if (str.includes('亿')) {
  1176. num *= 100000000;
  1177. }
  1178. return Math.floor(num);
  1179. }
  1180. /**
  1181. * 获取平台配置
  1182. */
  1183. private getPlatformConfig(platform: PlatformType) {
  1184. const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
  1185. douyin: {
  1186. homeUrl: 'https://creator.douyin.com/creator-micro/home',
  1187. loginIndicators: ['login', 'passport', 'sso'],
  1188. },
  1189. bilibili: {
  1190. homeUrl: 'https://member.bilibili.com/platform/home',
  1191. loginIndicators: ['passport.bilibili.com', 'login'],
  1192. },
  1193. kuaishou: {
  1194. homeUrl: 'https://cp.kuaishou.com/profile',
  1195. loginIndicators: ['passport.kuaishou.com', 'login'],
  1196. },
  1197. xiaohongshu: {
  1198. homeUrl: 'https://creator.xiaohongshu.com/',
  1199. loginIndicators: ['login', 'passport'],
  1200. },
  1201. weixin: {
  1202. homeUrl: 'https://channels.weixin.qq.com/platform',
  1203. loginIndicators: ['login', 'passport'],
  1204. },
  1205. toutiao: {
  1206. homeUrl: 'https://mp.toutiao.com/profile_v4/index',
  1207. loginIndicators: ['login', 'passport', 'sso'],
  1208. },
  1209. weibo: {
  1210. homeUrl: 'https://weibo.com/u/',
  1211. loginIndicators: ['login', 'passport'],
  1212. },
  1213. dayu: {
  1214. homeUrl: 'https://mp.dayu.com/',
  1215. loginIndicators: ['login', 'passport'],
  1216. },
  1217. };
  1218. return configs[platform] || { homeUrl: '', loginIndicators: ['login'] };
  1219. }
  1220. /**
  1221. * 获取默认账号信息
  1222. */
  1223. private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
  1224. return {
  1225. accountId: `${platform}_${Date.now()}`,
  1226. accountName: `${platform}账号`,
  1227. avatarUrl: '',
  1228. fansCount: 0,
  1229. worksCount: 0,
  1230. };
  1231. }
  1232. /**
  1233. * 获取抖音评论 - 逐个选择作品获取评论
  1234. */
  1235. async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
  1236. const browser = await chromium.launch({
  1237. headless: true,
  1238. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  1239. });
  1240. const allWorkComments: WorkComments[] = [];
  1241. try {
  1242. const context = await browser.newContext({
  1243. viewport: { width: 1920, height: 1080 },
  1244. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  1245. });
  1246. // 设置 Cookie
  1247. const playwrightCookies = cookies.map(c => ({
  1248. name: c.name,
  1249. value: c.value,
  1250. domain: c.domain || '.douyin.com',
  1251. path: c.path || '/',
  1252. }));
  1253. await context.addCookies(playwrightCookies);
  1254. const page = await context.newPage();
  1255. // 导航到评论管理页面
  1256. logger.info('Navigating to Douyin comment management page...');
  1257. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  1258. waitUntil: 'domcontentloaded',
  1259. timeout: 30000,
  1260. });
  1261. await page.waitForTimeout(3000);
  1262. // 点击"选择作品"按钮
  1263. logger.info('Looking for "选择作品" button...');
  1264. const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');
  1265. if (selectWorkBtn) {
  1266. await selectWorkBtn.click();
  1267. await page.waitForTimeout(2000);
  1268. logger.info('Clicked "选择作品" button');
  1269. } else {
  1270. // 如果没有选择作品按钮,可能已经有作品被选中,直接获取当前评论
  1271. logger.info('No "选择作品" button found, fetching current comments...');
  1272. const currentComments = await this.extractCommentsFromPage(page);
  1273. if (currentComments.length > 0) {
  1274. allWorkComments.push({
  1275. videoId: 'current',
  1276. videoTitle: '当前作品',
  1277. videoCoverUrl: '',
  1278. comments: currentComments,
  1279. });
  1280. }
  1281. await page.close();
  1282. await context.close();
  1283. await browser.close();
  1284. return allWorkComments;
  1285. }
  1286. // 获取作品列表
  1287. const worksList = await page.evaluate(() => {
  1288. const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];
  1289. // 查找作品列表容器(弹窗中的作品选择列表)
  1290. const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');
  1291. workItems.forEach((item, index) => {
  1292. const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
  1293. const coverEl = item.querySelector('img, [class*="cover"]');
  1294. const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
  1295. let coverUrl = '';
  1296. if (coverEl) {
  1297. coverUrl = (coverEl as HTMLImageElement).src ||
  1298. coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
  1299. }
  1300. // 获取 video ID(从数据属性或其他方式)
  1301. const videoId = item.getAttribute('data-video-id') ||
  1302. item.getAttribute('data-id') ||
  1303. `video_${index}`;
  1304. works.push({ videoId, title, coverUrl });
  1305. });
  1306. return works;
  1307. });
  1308. logger.info(`Found ${worksList.length} works in the selector`);
  1309. // 如果有作品列表,逐个选择并获取评论
  1310. if (worksList.length > 0) {
  1311. for (let i = 0; i < worksList.length; i++) {
  1312. try {
  1313. logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);
  1314. // 点击选择该作品
  1315. const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
  1316. if (workItem) {
  1317. await workItem.click();
  1318. await page.waitForTimeout(2000);
  1319. // 点击确认按钮(如果有)
  1320. const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
  1321. if (confirmBtn) {
  1322. await confirmBtn.click();
  1323. await page.waitForTimeout(2000);
  1324. }
  1325. }
  1326. // 等待评论加载
  1327. await page.waitForTimeout(2000);
  1328. // 提取评论
  1329. const comments = await this.extractCommentsFromPage(page);
  1330. if (comments.length > 0) {
  1331. allWorkComments.push({
  1332. videoId: worksList[i].videoId,
  1333. videoTitle: worksList[i].title,
  1334. videoCoverUrl: worksList[i].coverUrl,
  1335. comments,
  1336. });
  1337. logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
  1338. }
  1339. // 重新打开选择作品弹窗(如果需要继续选择其他作品)
  1340. if (i < worksList.length - 1) {
  1341. const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
  1342. if (selectBtn) {
  1343. await selectBtn.click();
  1344. await page.waitForTimeout(2000);
  1345. }
  1346. }
  1347. } catch (workError) {
  1348. logger.warn(`Failed to process work ${i + 1}:`, workError);
  1349. }
  1350. }
  1351. } else {
  1352. // 没有找到作品列表,尝试直接从页面获取评论
  1353. const comments = await this.extractCommentsFromPage(page);
  1354. if (comments.length > 0) {
  1355. // 获取当前显示的作品信息
  1356. const currentWork = await page.evaluate(() => {
  1357. const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
  1358. const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');
  1359. return {
  1360. title: titleEl?.textContent?.trim() || '当前作品',
  1361. coverUrl: (coverEl as HTMLImageElement)?.src || '',
  1362. };
  1363. });
  1364. allWorkComments.push({
  1365. videoId: 'current',
  1366. videoTitle: currentWork.title,
  1367. videoCoverUrl: currentWork.coverUrl,
  1368. comments,
  1369. });
  1370. }
  1371. }
  1372. await page.close();
  1373. await context.close();
  1374. await browser.close();
  1375. logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
  1376. return allWorkComments;
  1377. } catch (error) {
  1378. logger.error('Error fetching Douyin comments:', error);
  1379. await browser.close();
  1380. return allWorkComments;
  1381. }
  1382. }
  1383. /**
  1384. * 从页面提取评论列表
  1385. * 使用抖音创作者中心的精确选择器
  1386. * 根据实际 HTML 结构:
  1387. * - 评论容器: container-sXKyMs (或类似 container-xxx)
  1388. * - 用户名: username-aLgaNB (或类似 username-xxx)
  1389. * - 时间: time-NRtTXO (或类似 time-xxx)
  1390. * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
  1391. * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
  1392. */
  1393. private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
  1394. return page.evaluate(() => {
  1395. const comments: Array<{
  1396. commentId: string;
  1397. authorId: string;
  1398. authorName: string;
  1399. authorAvatar: string;
  1400. content: string;
  1401. likeCount: number;
  1402. commentTime: string;
  1403. }> = [];
  1404. const seenContents = new Set<string>();
  1405. // 方法1: 直接查找所有评论容器 (container-xxx 类名)
  1406. // 评论容器通常包含 checkbox、avatar、content 等子元素
  1407. const allContainers = document.querySelectorAll('[class*="container-"]');
  1408. const commentContainers: Element[] = [];
  1409. allContainers.forEach(container => {
  1410. // 检查是否是评论容器:包含用户名和评论内容
  1411. const hasUsername = container.querySelector('[class*="username-"]');
  1412. const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
  1413. if (hasUsername && hasCommentContent) {
  1414. commentContainers.push(container);
  1415. }
  1416. });
  1417. console.log(`Found ${commentContainers.length} comment containers`);
  1418. // 如果方法1没找到,尝试方法2:通过评论内容元素向上查找
  1419. if (commentContainers.length === 0) {
  1420. const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
  1421. console.log(`Found ${contentElements.length} content elements, searching parents...`);
  1422. contentElements.forEach(contentEl => {
  1423. let parent = contentEl.parentElement;
  1424. // 向上查找最多 10 层
  1425. for (let i = 0; i < 10 && parent; i++) {
  1426. const className = parent.className || '';
  1427. // 查找包含 container- 的父元素
  1428. if (className.includes('container-')) {
  1429. if (!commentContainers.includes(parent)) {
  1430. commentContainers.push(parent);
  1431. }
  1432. break;
  1433. }
  1434. parent = parent.parentElement;
  1435. }
  1436. });
  1437. }
  1438. console.log(`Total comment containers: ${commentContainers.length}`);
  1439. commentContainers.forEach((container, index) => {
  1440. try {
  1441. // 提取用户名 - 使用 username-xxx 选择器
  1442. let authorName = '';
  1443. const usernameEl = container.querySelector('[class*="username-"]');
  1444. if (usernameEl && usernameEl.textContent) {
  1445. authorName = usernameEl.textContent.trim();
  1446. }
  1447. if (!authorName) authorName = '未知用户';
  1448. // 提取头像 - 从 avatar-xxx 容器内的 img 提取
  1449. let authorAvatar = '';
  1450. const avatarContainer = container.querySelector('[class*="avatar-"]');
  1451. if (avatarContainer) {
  1452. const avatarImg = avatarContainer.querySelector('img');
  1453. if (avatarImg) {
  1454. authorAvatar = avatarImg.src || '';
  1455. }
  1456. }
  1457. // 提取时间 - 使用 time-xxx 选择器
  1458. let commentTime = '';
  1459. const timeEl = container.querySelector('[class*="time-"]');
  1460. if (timeEl && timeEl.textContent) {
  1461. commentTime = timeEl.textContent.trim();
  1462. }
  1463. // 提取评论内容 - 使用 comment-content-text-xxx 选择器
  1464. let content = '';
  1465. const contentEl = container.querySelector('[class*="comment-content-text-"]');
  1466. if (contentEl && contentEl.textContent) {
  1467. content = contentEl.textContent.trim();
  1468. }
  1469. // 跳过空内容
  1470. if (!content || content.length < 1) {
  1471. console.log(`[${index}] Skipping empty content`);
  1472. return;
  1473. }
  1474. // 去重 (基于用户名+内容)
  1475. const contentKey = `${authorName}||${content}`;
  1476. if (seenContents.has(contentKey)) {
  1477. console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
  1478. return;
  1479. }
  1480. seenContents.add(contentKey);
  1481. // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
  1482. let likeCount = 0;
  1483. const operationsEl = container.querySelector('[class*="operations-"]');
  1484. if (operationsEl) {
  1485. // 查找第一个 item-xxx,通常是点赞数
  1486. const firstItem = operationsEl.querySelector('[class*="item-"]');
  1487. if (firstItem) {
  1488. const text = firstItem.textContent || '';
  1489. const match = text.match(/(\d+)/);
  1490. if (match) {
  1491. likeCount = parseInt(match[1], 10);
  1492. }
  1493. }
  1494. }
  1495. // 生成唯一 ID
  1496. const contentHash = content.slice(0, 30) + authorName + commentTime;
  1497. const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;
  1498. comments.push({
  1499. commentId,
  1500. authorId: authorName,
  1501. authorName,
  1502. authorAvatar,
  1503. content,
  1504. likeCount,
  1505. commentTime,
  1506. });
  1507. console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
  1508. } catch (err) {
  1509. console.error(`[${index}] Error extracting comment:`, err);
  1510. }
  1511. });
  1512. console.log(`Successfully extracted ${comments.length} comments`);
  1513. return comments;
  1514. });
  1515. }
  1516. /**
  1517. * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
  1518. * 使用无头浏览器,通过拦截网络请求直接获取 API 数据
  1519. * 更稳定、更高效
  1520. */
  1521. async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
  1522. const browser = await chromium.launch({
  1523. headless: true, // 无头模式
  1524. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  1525. });
  1526. const allWorkComments: WorkComments[] = [];
  1527. // 存储捕获的 API 数据
  1528. const capturedWorks: Array<{
  1529. awemeId: string;
  1530. title: string;
  1531. coverUrl: string;
  1532. commentCount: number;
  1533. }> = [];
  1534. const capturedComments: Map<string, CommentItem[]> = new Map();
  1535. try {
  1536. const context = await browser.newContext({
  1537. viewport: { width: 1920, height: 1080 },
  1538. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  1539. });
  1540. // 设置 Cookie
  1541. const playwrightCookies = cookies.map(c => ({
  1542. name: c.name,
  1543. value: c.value,
  1544. domain: c.domain || '.douyin.com',
  1545. path: c.path || '/',
  1546. }));
  1547. await context.addCookies(playwrightCookies);
  1548. logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);
  1549. const page = await context.newPage();
  1550. // 监听网络响应
  1551. page.on('response', async (response) => {
  1552. const url = response.url();
  1553. try {
  1554. // 监听作品列表 API - 支持新旧两种接口
  1555. // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
  1556. // 旧接口: /creator/item/list (item_info_list 字段)
  1557. if (url.includes('/work_list') || url.includes('/creator/item/list')) {
  1558. const data = await response.json();
  1559. // 新接口: aweme_list
  1560. if (data?.aweme_list && data.aweme_list.length > 0) {
  1561. for (const aweme of data.aweme_list) {
  1562. const awemeId = String(aweme.aweme_id || '');
  1563. if (!awemeId) continue;
  1564. const statistics = aweme.statistics || {};
  1565. const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
  1566. let title = aweme.item_title || '';
  1567. if (!title) {
  1568. const desc = aweme.desc || aweme.caption || '';
  1569. title = desc.split('\n')[0].slice(0, 50) || '无标题';
  1570. }
  1571. let coverUrl = '';
  1572. if (aweme.Cover?.url_list?.length > 0) {
  1573. coverUrl = aweme.Cover.url_list[0];
  1574. } else if (aweme.video?.cover?.url_list?.length > 0) {
  1575. coverUrl = aweme.video.cover.url_list[0];
  1576. }
  1577. capturedWorks.push({
  1578. awemeId,
  1579. title,
  1580. coverUrl,
  1581. commentCount,
  1582. });
  1583. }
  1584. logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
  1585. }
  1586. // 旧接口: item_info_list
  1587. const itemList = data?.item_info_list || data?.item_list || [];
  1588. if (itemList.length > 0) {
  1589. for (const item of itemList) {
  1590. capturedWorks.push({
  1591. awemeId: item.item_id_plain || item.aweme_id || '',
  1592. title: item.title || '无标题',
  1593. coverUrl: item.cover_image_url || '',
  1594. commentCount: item.comment_count || 0,
  1595. });
  1596. }
  1597. logger.info(`[API] Captured ${itemList.length} works from item/list API`);
  1598. }
  1599. }
  1600. // 监听评论列表 API(两种格式)
  1601. // 格式1: /comment/list/select/ - 初始加载,返回 { comments: [...] }
  1602. // 格式2: /creator/comment/list/ - 切换作品后,返回 { comment_info_list: [...] }
  1603. if (url.includes('/comment/list') || url.includes('/comment/read')) {
  1604. const data = await response.json();
  1605. // 从 URL 中提取 aweme_id
  1606. const awemeIdMatch = url.match(/aweme_id=(\d+)/);
  1607. const awemeId = awemeIdMatch?.[1] || '';
  1608. let comments: CommentItem[] = [];
  1609. // 格式1: 初始加载的评论 API (comment/list/select)
  1610. if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
  1611. comments = data.comments.map((c: Record<string, unknown>) => {
  1612. const user = c.user as Record<string, unknown> | undefined;
  1613. const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
  1614. const avatarUrls = avatarThumb?.url_list as string[] | undefined;
  1615. return {
  1616. commentId: String(c.cid || ''),
  1617. authorId: String(user?.uid || ''),
  1618. authorName: String(user?.nickname || '匿名'),
  1619. authorAvatar: avatarUrls?.[0] || '',
  1620. content: String(c.text || ''),
  1621. likeCount: Number(c.digg_count || 0),
  1622. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  1623. videoId: String(c.aweme_id || awemeId),
  1624. };
  1625. });
  1626. logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
  1627. }
  1628. // 格式2: 切换作品后的评论 API (creator/comment/list)
  1629. if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
  1630. comments = data.comment_info_list.map((c: Record<string, unknown>) => {
  1631. const userInfo = c.user_info as Record<string, unknown> | undefined;
  1632. return {
  1633. commentId: String(c.comment_id || ''),
  1634. authorId: String(userInfo?.user_id || ''),
  1635. authorName: String(userInfo?.screen_name || '匿名'),
  1636. authorAvatar: String(userInfo?.avatar_url || ''),
  1637. content: String(c.text || ''),
  1638. likeCount: Number(c.digg_count || 0),
  1639. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  1640. videoId: awemeId, // 这种格式没有直接返回 aweme_id
  1641. };
  1642. });
  1643. logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
  1644. }
  1645. if (comments.length > 0) {
  1646. const videoId = comments[0]?.videoId || awemeId;
  1647. if (videoId) {
  1648. const existing = capturedComments.get(videoId) || [];
  1649. capturedComments.set(videoId, [...existing, ...comments]);
  1650. logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
  1651. }
  1652. }
  1653. }
  1654. } catch {
  1655. // 忽略非 JSON 响应
  1656. }
  1657. });
  1658. // 导航到创作者中心页面(设置好 Cookie 后)
  1659. logger.info('[API Interception] Navigating to creator page...');
  1660. await page.goto('https://creator.douyin.com/creator-micro/home', {
  1661. waitUntil: 'domcontentloaded',
  1662. timeout: 60000,
  1663. });
  1664. // 等待页面加载
  1665. await page.waitForTimeout(3000);
  1666. // 检查是否需要登录
  1667. const currentUrl = page.url();
  1668. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  1669. logger.warn('[API Interception] Cookie expired');
  1670. return [];
  1671. }
  1672. // 方式1:直接调用 API 获取作品列表(优先)
  1673. logger.info('[API Interception] Fetching works via direct API...');
  1674. let works = await this.fetchWorksDirectApi(page);
  1675. // 方式2:如果直接调用失败,尝试通过页面触发 API
  1676. if (works.length === 0) {
  1677. logger.info('[API Interception] Direct API failed, trying page navigation...');
  1678. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  1679. waitUntil: 'networkidle',
  1680. timeout: 60000,
  1681. });
  1682. await page.waitForTimeout(3000);
  1683. // 点击"选择作品"按钮触发作品列表 API
  1684. const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
  1685. if (selectBtn) {
  1686. await selectBtn.click();
  1687. await page.waitForTimeout(3000);
  1688. }
  1689. // 使用监听到的数据
  1690. works = capturedWorks;
  1691. }
  1692. logger.info(`[API Interception] Total works: ${works.length}`);
  1693. // 获取有评论的作品
  1694. const worksWithComments = works.filter(w => w.commentCount > 0);
  1695. logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);
  1696. // 如果有评论的作品,需要导航到评论管理页面并逐个切换获取
  1697. if (worksWithComments.length > 0) {
  1698. // 先尝试直接调用 API 获取评论
  1699. for (const work of worksWithComments) {
  1700. logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);
  1701. let comments = capturedComments.get(work.awemeId) || [];
  1702. if (comments.length === 0) {
  1703. comments = await this.fetchCommentsDirectApi(page, work.awemeId);
  1704. }
  1705. if (comments.length > 0) {
  1706. allWorkComments.push({
  1707. videoId: work.awemeId,
  1708. videoTitle: work.title,
  1709. videoCoverUrl: work.coverUrl,
  1710. comments,
  1711. });
  1712. logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
  1713. }
  1714. }
  1715. // 如果直接 API 没有获取到足够的评论,使用页面交互方式
  1716. const worksNeedingPageMethod = worksWithComments.filter(w => {
  1717. const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
  1718. return !found || found.comments.length === 0;
  1719. });
  1720. if (worksNeedingPageMethod.length > 0) {
  1721. logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);
  1722. // works 是所有作品的列表(包括没有评论的),弹窗中的顺序应该和这个一致
  1723. // worksWithComments 是有评论的作品列表
  1724. logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
  1725. logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);
  1726. // 构建作品索引映射:在所有作品列表中,每个有评论的作品的索引是多少
  1727. const workIndexMap = new Map<string, number>();
  1728. works.forEach((w, idx) => {
  1729. if (w.commentCount > 0) {
  1730. workIndexMap.set(w.awemeId, idx);
  1731. }
  1732. });
  1733. logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);
  1734. // 导航到评论管理页面
  1735. logger.info('[Page Method] Navigating to comment management page...');
  1736. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  1737. waitUntil: 'domcontentloaded',
  1738. timeout: 60000,
  1739. });
  1740. // 等待页面加载
  1741. await page.waitForTimeout(5000);
  1742. // 用于存储最新捕获的评论和 aweme_id
  1743. const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };
  1744. // 设置监听器 - 捕获评论 API 响应
  1745. page.on('response', async (response) => {
  1746. const url = response.url();
  1747. if (url.includes('/comment/list') || url.includes('/comment/read')) {
  1748. try {
  1749. const jsonData = await response.json();
  1750. let parsedComments: CommentItem[] = [];
  1751. let capturedAwemeId = '';
  1752. // 从 URL 中提取 aweme_id(格式1有)
  1753. const awemeIdMatch = url.match(/aweme_id=(\d+)/);
  1754. capturedAwemeId = awemeIdMatch?.[1] || '';
  1755. // 格式1: { comments: [...] }
  1756. if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
  1757. // 从评论中提取 aweme_id
  1758. const firstComment = jsonData.comments[0] as Record<string, unknown>;
  1759. if (!capturedAwemeId && firstComment.aweme_id) {
  1760. capturedAwemeId = String(firstComment.aweme_id);
  1761. }
  1762. parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
  1763. commentId: String((c as { cid?: string }).cid || ''),
  1764. authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
  1765. authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
  1766. authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
  1767. content: String((c as { text?: string }).text || ''),
  1768. likeCount: Number((c as { digg_count?: number }).digg_count || 0),
  1769. commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
  1770. videoId: capturedAwemeId,
  1771. }));
  1772. logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
  1773. }
  1774. // 格式2: { comment_info_list: [...] }
  1775. if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
  1776. parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
  1777. const userInfo = c.user_info as Record<string, unknown> | undefined;
  1778. return {
  1779. commentId: String(c.comment_id || ''),
  1780. authorId: String(userInfo?.user_id || ''),
  1781. authorName: String(userInfo?.screen_name || '匿名'),
  1782. authorAvatar: String(userInfo?.avatar_url || ''),
  1783. content: String(c.text || ''),
  1784. likeCount: Number(c.digg_count || 0),
  1785. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  1786. videoId: '', // 格式2没有aweme_id,稍后填充
  1787. };
  1788. });
  1789. logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
  1790. }
  1791. if (parsedComments.length > 0) {
  1792. latestHolder.comments = parsedComments;
  1793. latestHolder.awemeId = capturedAwemeId;
  1794. }
  1795. } catch {
  1796. // 忽略
  1797. }
  1798. }
  1799. });
  1800. // 等待第一个作品的评论加载(格式1,有 aweme_id)
  1801. await page.waitForTimeout(4000);
  1802. // 处理第一个作品(页面加载时自动显示,格式1有aweme_id可以直接匹配)
  1803. if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
  1804. const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
  1805. if (matchedWork) {
  1806. allWorkComments.push({
  1807. videoId: matchedWork.awemeId,
  1808. videoTitle: matchedWork.title,
  1809. videoCoverUrl: matchedWork.coverUrl,
  1810. comments: latestHolder.comments,
  1811. });
  1812. logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
  1813. }
  1814. }
  1815. // 遍历其他有评论的作品
  1816. for (const work of worksWithComments) {
  1817. // 检查是否已获取
  1818. const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
  1819. if (existing) {
  1820. logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
  1821. continue;
  1822. }
  1823. // 获取该作品在所有作品列表中的索引
  1824. const workIndex = workIndexMap.get(work.awemeId);
  1825. if (workIndex === undefined) {
  1826. logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
  1827. continue;
  1828. }
  1829. logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);
  1830. try {
  1831. // 清空之前的数据
  1832. latestHolder.comments = [];
  1833. latestHolder.awemeId = '';
  1834. // 点击"选择作品"按钮
  1835. await page.click('button:has-text("选择作品")');
  1836. await page.waitForTimeout(2000);
  1837. // 找到弹窗中的作品图片列表
  1838. const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
  1839. logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);
  1840. if (workIndex < workImages.length) {
  1841. // 点击对应索引的作品
  1842. await workImages[workIndex].click();
  1843. logger.info(`[Page Method] Clicked work image at index ${workIndex}`);
  1844. // 等待评论 API 响应
  1845. await page.waitForTimeout(4000);
  1846. // 获取评论
  1847. if (latestHolder.comments.length > 0) {
  1848. // 使用当前 work 的 awemeId
  1849. const comments = latestHolder.comments.map(c => ({
  1850. ...c,
  1851. videoId: work.awemeId,
  1852. }));
  1853. allWorkComments.push({
  1854. videoId: work.awemeId,
  1855. videoTitle: work.title,
  1856. videoCoverUrl: work.coverUrl,
  1857. comments,
  1858. });
  1859. logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
  1860. } else {
  1861. // 尝试从页面提取
  1862. const pageComments = await this.extractCommentsFromPage(page);
  1863. if (pageComments.length > 0) {
  1864. const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
  1865. allWorkComments.push({
  1866. videoId: work.awemeId,
  1867. videoTitle: work.title,
  1868. videoCoverUrl: work.coverUrl,
  1869. comments,
  1870. });
  1871. logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
  1872. } else {
  1873. logger.warn(`[Page Method] No comments for ${work.awemeId}`);
  1874. }
  1875. }
  1876. } else {
  1877. logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
  1878. await page.keyboard.press('Escape');
  1879. }
  1880. await page.waitForTimeout(1000);
  1881. } catch (e) {
  1882. logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
  1883. await page.keyboard.press('Escape').catch(() => { });
  1884. await page.waitForTimeout(500);
  1885. }
  1886. }
  1887. }
  1888. }
  1889. logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
  1890. await context.close();
  1891. } catch (error) {
  1892. logger.error('[API Interception] Error:', error);
  1893. } finally {
  1894. await browser.close();
  1895. }
  1896. return allWorkComments;
  1897. }
  1898. /**
  1899. * 直接调用评论 API 获取数据(支持分页获取所有评论)
  1900. * 优先使用视频页面 API(获取全部评论),失败时才使用创作者 API
  1901. */
  1902. private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  1903. // 优先尝试视频页面 API(获取全部评论)
  1904. logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
  1905. let comments = await this.fetchVideoPageCommentsApi(page, awemeId);
  1906. if (comments.length > 0) {
  1907. logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
  1908. return comments;
  1909. }
  1910. // 如果视频页面 API 失败,尝试创作者评论 API(可能只返回部分评论)
  1911. logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
  1912. comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);
  1913. return comments;
  1914. }
  1915. /**
  1916. * 通过视频页面获取全部评论(主要方案)
  1917. * 这个 API 能获取视频的所有评论,不仅仅是创作者回复过的
  1918. */
  1919. private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  1920. const comments: CommentItem[] = [];
  1921. const maxPages = 50;
  1922. let cursor = 0;
  1923. let hasMore = true;
  1924. let pageCount = 0;
  1925. try {
  1926. // 导航到视频页面
  1927. logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
  1928. await page.goto(`https://www.douyin.com/video/${awemeId}`, {
  1929. waitUntil: 'domcontentloaded',
  1930. timeout: 30000,
  1931. });
  1932. await page.waitForTimeout(2000);
  1933. while (hasMore && pageCount < maxPages) {
  1934. pageCount++;
  1935. const data = await page.evaluate(async ({ videoId, cursorValue }) => {
  1936. try {
  1937. const url = `https://www.douyin.com/aweme/v1/web/comment/list/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&item_type=0&insert_ids=&whale_cut_token=&cut_version=1&rcFT=&aid=6383&device_platform=web_pc&verifyFp=&fp=&msToken=`;
  1938. const resp = await fetch(url, {
  1939. method: 'GET',
  1940. credentials: 'include',
  1941. headers: {
  1942. 'Accept': 'application/json, text/plain, */*',
  1943. 'Referer': `https://www.douyin.com/video/${videoId}`,
  1944. },
  1945. });
  1946. if (!resp.ok) {
  1947. return { error: `HTTP ${resp.status}`, comments: [] };
  1948. }
  1949. return resp.json();
  1950. } catch (e) {
  1951. return { error: String(e), comments: [] };
  1952. }
  1953. }, { videoId: awemeId, cursorValue: cursor });
  1954. if (data?.error) {
  1955. logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
  1956. }
  1957. if (data?.comments && Array.isArray(data.comments)) {
  1958. for (const c of data.comments) {
  1959. comments.push({
  1960. commentId: String(c.cid || ''),
  1961. authorId: String(c.user?.uid || c.user?.sec_uid || ''),
  1962. authorName: String(c.user?.nickname || '匿名'),
  1963. authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
  1964. content: String(c.text || ''),
  1965. likeCount: Number(c.digg_count || 0),
  1966. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  1967. videoId: String(c.aweme_id || awemeId),
  1968. });
  1969. }
  1970. logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
  1971. }
  1972. hasMore = data?.has_more === true || data?.has_more === 1;
  1973. cursor = data?.cursor || cursor + 50;
  1974. if (!data?.comments || data.comments.length === 0) {
  1975. hasMore = false;
  1976. }
  1977. }
  1978. logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
  1979. } catch (e) {
  1980. logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
  1981. }
  1982. return comments;
  1983. }
  1984. /**
  1985. * 创作者评论管理 API(备用方案)
  1986. * 获取的是需要回复的评论
  1987. */
  1988. private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  1989. const comments: CommentItem[] = [];
  1990. const maxPages = 50;
  1991. let cursor = 0;
  1992. let hasMore = true;
  1993. let pageCount = 0;
  1994. try {
  1995. while (hasMore && pageCount < maxPages) {
  1996. pageCount++;
  1997. const data = await page.evaluate(async ({ videoId, cursorValue }) => {
  1998. const url = `https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&comment_select_options=0&sort_options=0&channel_id=618&app_id=2906&aid=2906&device_platform=webapp`;
  1999. const resp = await fetch(url, {
  2000. credentials: 'include',
  2001. headers: {
  2002. 'Accept': 'application/json',
  2003. },
  2004. });
  2005. return resp.json();
  2006. }, { videoId: awemeId, cursorValue: cursor });
  2007. if (data?.comments && Array.isArray(data.comments)) {
  2008. for (const c of data.comments) {
  2009. comments.push({
  2010. commentId: String(c.cid || ''),
  2011. authorId: String(c.user?.uid || ''),
  2012. authorName: String(c.user?.nickname || '匿名'),
  2013. authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
  2014. content: String(c.text || ''),
  2015. likeCount: Number(c.digg_count || 0),
  2016. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2017. videoId: String(c.aweme_id || awemeId),
  2018. });
  2019. }
  2020. logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
  2021. }
  2022. hasMore = data?.has_more === true || data?.has_more === 1;
  2023. cursor = data?.cursor || cursor + 50;
  2024. if (!data?.comments || data.comments.length === 0) {
  2025. hasMore = false;
  2026. }
  2027. }
  2028. logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
  2029. } catch (e) {
  2030. logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
  2031. }
  2032. return comments;
  2033. }
  2034. /**
  2035. * 直接调用抖音 API 获取作品列表
  2036. * 使用新的 work_list 接口,支持分页加载
  2037. */
  2038. private async fetchWorksDirectApi(page: Page): Promise<Array<{
  2039. awemeId: string;
  2040. title: string;
  2041. coverUrl: string;
  2042. commentCount: number;
  2043. createTime?: number;
  2044. }>> {
  2045. const works: Array<{
  2046. awemeId: string;
  2047. title: string;
  2048. coverUrl: string;
  2049. commentCount: number;
  2050. createTime?: number;
  2051. }> = [];
  2052. try {
  2053. let hasMore = true;
  2054. let maxCursor = 0;
  2055. let pageCount = 0;
  2056. const maxPages = 20; // 最多加载20页,防止无限循环
  2057. while (hasMore && pageCount < maxPages) {
  2058. pageCount++;
  2059. logger.info(`[DirectAPI] Fetching works page ${pageCount}, cursor: ${maxCursor}`);
  2060. const data = await page.evaluate(async (cursor: number) => {
  2061. // 使用新的 work_list API 接口
  2062. // status: 不传或传空表示获取全部状态的作品
  2063. // count: 每页获取数量,增加到20减少请求次数
  2064. const url = `https://creator.douyin.com/janus/douyin/creator/pc/work_list?scene=star_atlas&device_platform=android&count=20&max_cursor=${cursor}&cookie_enabled=true&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_online=true&timezone_name=Asia%2FShanghai&aid=1128`;
  2065. const resp = await fetch(url, {
  2066. credentials: 'include',
  2067. headers: {
  2068. 'Accept': 'application/json',
  2069. },
  2070. });
  2071. return resp.json();
  2072. }, maxCursor);
  2073. logger.info(`[DirectAPI] API response: has_more=${data?.has_more}, max_cursor=${data?.max_cursor}, aweme_list_length=${data?.aweme_list?.length || 0}`);
  2074. // 解析 aweme_list 中的作品数据
  2075. const awemeList = data?.aweme_list || [];
  2076. logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);
  2077. for (const aweme of awemeList) {
  2078. const awemeId = String(aweme.aweme_id || '');
  2079. if (!awemeId) continue;
  2080. // 从 statistics 中获取评论数
  2081. const statistics = aweme.statistics || {};
  2082. const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
  2083. // 获取标题:优先使用 item_title,其次使用 desc(描述)
  2084. let title = aweme.item_title || '';
  2085. if (!title) {
  2086. // 从 desc 中提取标题(取第一行或前50个字符)
  2087. const desc = aweme.desc || aweme.caption || '';
  2088. title = desc.split('\n')[0].slice(0, 50) || '无标题';
  2089. }
  2090. // 获取封面 URL:从 Cover.url_list 或 video.cover.url_list 中获取
  2091. let coverUrl = '';
  2092. if (aweme.Cover?.url_list?.length > 0) {
  2093. coverUrl = aweme.Cover.url_list[0];
  2094. } else if (aweme.video?.cover?.url_list?.length > 0) {
  2095. coverUrl = aweme.video.cover.url_list[0];
  2096. }
  2097. works.push({
  2098. awemeId,
  2099. title,
  2100. coverUrl,
  2101. commentCount,
  2102. createTime: aweme.create_time,
  2103. });
  2104. }
  2105. // 检查是否有更多数据
  2106. // 注意: 抖音 API 返回的 has_more 可能不准确,我们额外判断
  2107. const apiHasMore = data?.has_more === true || data?.has_more === 1;
  2108. // 更新游标:使用返回的 max_cursor
  2109. if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
  2110. // 只有当 max_cursor 有变化时才继续
  2111. if (data.max_cursor !== maxCursor) {
  2112. maxCursor = data.max_cursor;
  2113. hasMore = apiHasMore && awemeList.length > 0;
  2114. } else {
  2115. // max_cursor 没变化,说明到底了
  2116. hasMore = false;
  2117. }
  2118. } else if (awemeList.length > 0) {
  2119. // 如果没有 max_cursor,使用最后一个作品的 create_time 作为游标
  2120. const lastAweme = awemeList[awemeList.length - 1];
  2121. if (lastAweme.create_time) {
  2122. const newCursor = lastAweme.create_time;
  2123. if (newCursor !== maxCursor) {
  2124. maxCursor = newCursor;
  2125. hasMore = apiHasMore;
  2126. } else {
  2127. hasMore = false;
  2128. }
  2129. } else {
  2130. hasMore = false;
  2131. }
  2132. } else {
  2133. // 没有获取到数据,停止循环
  2134. hasMore = false;
  2135. }
  2136. logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);
  2137. // 稍微延迟,避免请求过快
  2138. if (hasMore) {
  2139. await new Promise(resolve => setTimeout(resolve, 500));
  2140. }
  2141. }
  2142. logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages`);
  2143. } catch (e) {
  2144. logger.warn('[DirectAPI] Failed to fetch works:', e);
  2145. }
  2146. return works;
  2147. }
  2148. /**
  2149. * 获取抖音评论 (旧版 - DOM解析方式)
  2150. * 模拟点击"选择作品"按钮,依次点击作品获取评论
  2151. * 作为备用方案
  2152. */
  2153. async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  2154. // 优先使用 API 拦截方式
  2155. const result = await this.fetchDouyinCommentsByApiInterception(cookies);
  2156. if (result.length > 0) {
  2157. return result;
  2158. }
  2159. // 如果 API 方式失败,使用旧的 DOM 解析方式作为备用
  2160. logger.info('[Fallback] Using DOM parsing method...');
  2161. const browser = await chromium.launch({
  2162. headless: true, // 改为无头模式
  2163. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  2164. });
  2165. const allWorkComments: WorkComments[] = [];
  2166. try {
  2167. const context = await browser.newContext({
  2168. viewport: { width: 1920, height: 1080 },
  2169. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2170. });
  2171. // 设置 Cookie
  2172. const playwrightCookies = cookies.map(c => ({
  2173. name: c.name,
  2174. value: c.value,
  2175. domain: c.domain || '.douyin.com',
  2176. path: c.path || '/',
  2177. }));
  2178. await context.addCookies(playwrightCookies);
  2179. logger.info(`Set ${playwrightCookies.length} cookies`);
  2180. const page = await context.newPage();
  2181. // 导航到评论管理页面
  2182. logger.info('Navigating to Douyin comment management page...');
  2183. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  2184. waitUntil: 'domcontentloaded',
  2185. timeout: 60000,
  2186. });
  2187. // 等待页面完全加载
  2188. logger.info('Waiting for page to fully load...');
  2189. await page.waitForTimeout(5000);
  2190. // 检查是否需要登录
  2191. const currentUrl = page.url();
  2192. logger.info(`Current URL: ${currentUrl}`);
  2193. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  2194. logger.warn('Cookie expired, need re-login');
  2195. await browser.close();
  2196. return allWorkComments;
  2197. }
  2198. logger.info('Page loaded successfully');
  2199. // 等待评论列表加载
  2200. logger.info('Waiting for comments to load...');
  2201. try {
  2202. await page.waitForSelector('[class*="comment-content-text-"]', { timeout: 10000 });
  2203. logger.info('Comments loaded');
  2204. } catch {
  2205. logger.warn('No comments found on initial load, will try to select works');
  2206. }
  2207. // 辅助函数:从当前页面提取评论
  2208. const extractCommentsFromCurrentPage = async (): Promise<CommentItem[]> => {
  2209. logger.info('Extracting comments from current page...');
  2210. // 滚动页面加载所有评论
  2211. await page.evaluate(async () => {
  2212. // 滚动多次加载更多评论
  2213. for (let i = 0; i < 10; i++) {
  2214. window.scrollBy(0, 500);
  2215. await new Promise(r => setTimeout(r, 800));
  2216. }
  2217. window.scrollTo(0, 0);
  2218. });
  2219. await page.waitForTimeout(2000);
  2220. // 使用精确选择器提取评论
  2221. const comments = await page.evaluate(() => {
  2222. const result: Array<{
  2223. commentId: string;
  2224. authorId: string;
  2225. authorName: string;
  2226. authorAvatar: string;
  2227. content: string;
  2228. likeCount: number;
  2229. commentTime: string;
  2230. }> = [];
  2231. const seenContents = new Set<string>();
  2232. // 查找所有评论容器:包含 username 和 comment-content-text 的 container
  2233. const allContainers = document.querySelectorAll('[class*="container-"]');
  2234. const commentContainers: Element[] = [];
  2235. allContainers.forEach(container => {
  2236. const hasUsername = container.querySelector('[class*="username-"]');
  2237. const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
  2238. if (hasUsername && hasCommentContent) {
  2239. commentContainers.push(container);
  2240. }
  2241. });
  2242. console.log(`Found ${commentContainers.length} comment containers`);
  2243. commentContainers.forEach((container, index) => {
  2244. try {
  2245. // 用户名
  2246. const usernameEl = container.querySelector('[class*="username-"]');
  2247. const authorName = usernameEl?.textContent?.trim() || '未知用户';
  2248. // 时间
  2249. const timeEl = container.querySelector('[class*="time-"]');
  2250. const commentTime = timeEl?.textContent?.trim() || '';
  2251. // 评论内容
  2252. const contentEl = container.querySelector('[class*="comment-content-text-"]');
  2253. const content = contentEl?.textContent?.trim() || '';
  2254. if (!content) return;
  2255. // 头像
  2256. const avatarContainer = container.querySelector('[class*="avatar-"]');
  2257. const avatarImg = avatarContainer?.querySelector('img');
  2258. const authorAvatar = avatarImg?.src || '';
  2259. // 去重
  2260. const key = `${authorName}||${content}`;
  2261. if (seenContents.has(key)) return;
  2262. seenContents.add(key);
  2263. // 点赞数
  2264. let likeCount = 0;
  2265. const opsEl = container.querySelector('[class*="operations-"]');
  2266. if (opsEl) {
  2267. const itemEl = opsEl.querySelector('[class*="item-"]');
  2268. if (itemEl) {
  2269. const match = itemEl.textContent?.match(/(\d+)/);
  2270. if (match) likeCount = parseInt(match[1], 10);
  2271. }
  2272. }
  2273. // 生成 ID
  2274. const hash = content.slice(0, 30) + authorName + commentTime;
  2275. const commentId = `dy_${btoa(encodeURIComponent(hash)).slice(0, 20)}`;
  2276. result.push({
  2277. commentId,
  2278. authorId: authorName,
  2279. authorName,
  2280. authorAvatar,
  2281. content,
  2282. likeCount,
  2283. commentTime,
  2284. });
  2285. console.log(`[${index}] ${authorName}: ${content.slice(0, 30)}`);
  2286. } catch (e) {
  2287. console.error(`Error at ${index}:`, e);
  2288. }
  2289. });
  2290. return result;
  2291. });
  2292. logger.info(`Extracted ${comments.length} comments`);
  2293. return comments;
  2294. };
  2295. // 辅助函数:获取当前显示的作品标题
  2296. const getCurrentWorkTitle = async (): Promise<string> => {
  2297. return page.evaluate(() => {
  2298. // 查找作品标题 - 通常在页面顶部区域
  2299. // 排除筛选器和按钮中的文本
  2300. const excludeTexts = ['全部评论', '最新发布', '全部人群', '搜索', '选择作品', '评论管理'];
  2301. // 方法1: 查找视频信息区域
  2302. const videoInfoSelectors = [
  2303. '[class*="video-info"] [class*="title"]',
  2304. '[class*="work-info"] [class*="title"]',
  2305. '[class*="content-info"] [class*="title"]',
  2306. ];
  2307. for (const selector of videoInfoSelectors) {
  2308. const el = document.querySelector(selector);
  2309. if (el?.textContent) {
  2310. const text = el.textContent.trim();
  2311. if (text.length > 5 && !excludeTexts.some(e => text.includes(e))) {
  2312. return text;
  2313. }
  2314. }
  2315. }
  2316. // 方法2: 查找页面上较长的标题文本
  2317. const allTexts = document.querySelectorAll('div, span, p');
  2318. for (const el of Array.from(allTexts)) {
  2319. const text = el.textContent?.trim() || '';
  2320. if (text.length > 20 &&
  2321. text.length < 200 &&
  2322. !excludeTexts.some(e => text.includes(e)) &&
  2323. !el.closest('button') &&
  2324. !el.closest('[class*="select"]') &&
  2325. !el.closest('[class*="filter"]')) {
  2326. // 检查是否可能是作品标题(通常包含特定字符或格式)
  2327. if (text.includes('#') || text.match(/[,。!?、]/)) {
  2328. return text;
  2329. }
  2330. }
  2331. }
  2332. return '';
  2333. });
  2334. };
  2335. // 步骤1: 先获取当前页面显示的评论(默认显示的第一个作品)
  2336. logger.info('Step 1: Getting comments from default view...');
  2337. const defaultTitle = await getCurrentWorkTitle();
  2338. const defaultComments = await extractCommentsFromCurrentPage();
  2339. if (defaultComments.length > 0) {
  2340. allWorkComments.push({
  2341. videoId: `video_${Date.now()}`,
  2342. videoTitle: defaultTitle || '默认作品',
  2343. videoCoverUrl: '',
  2344. comments: defaultComments,
  2345. });
  2346. logger.info(`Got ${defaultComments.length} comments from default view, title: "${defaultTitle.slice(0, 50)}"`);
  2347. }
  2348. // 步骤2: 尝试点击"选择作品"按钮获取更多作品的评论
  2349. logger.info('Step 2: Looking for "选择作品" button...');
  2350. // 使用 locator 查找按钮
  2351. const selectBtn = page.locator('text=选择作品').first();
  2352. const btnCount = await selectBtn.count();
  2353. logger.info(`Found ${btnCount} "选择作品" button(s)`);
  2354. if (btnCount > 0) {
  2355. logger.info('Clicking "选择作品" button...');
  2356. await selectBtn.click();
  2357. // 等待更长时间,确保弹窗完全加载
  2358. logger.info('Waiting for work list modal to appear...');
  2359. await page.waitForTimeout(5000);
  2360. // 打印当前页面状态,帮助调试
  2361. const modalInfo = await page.evaluate(() => {
  2362. // 查找所有可能的弹窗元素
  2363. const modals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="drawer"], [class*="dialog"], [role="dialog"]');
  2364. const modalClasses = Array.from(modals).map(m => m.className).slice(0, 5);
  2365. // 查找所有图片(作品封面)
  2366. const images = document.querySelectorAll('img[src*="douyinpic"]');
  2367. // 查找所有可能的卡片元素
  2368. const cards = document.querySelectorAll('[class*="card"], [class*="item"]');
  2369. const cardClasses = Array.from(cards).map(c => c.className).slice(0, 10);
  2370. return {
  2371. modalCount: modals.length,
  2372. modalClasses,
  2373. imageCount: images.length,
  2374. cardCount: cards.length,
  2375. cardClasses,
  2376. };
  2377. });
  2378. logger.info(`Modal debug: ${JSON.stringify(modalInfo)}`);
  2379. // 尝试多种选择器查找作品列表
  2380. const workSelectors = [
  2381. '[class*="video-card"]',
  2382. '[class*="work-item"]',
  2383. '[class*="content-item"]',
  2384. '[class*="modal"] [class*="card"]',
  2385. '[class*="modal"] img',
  2386. '[class*="drawer"] [class*="card"]',
  2387. '[class*="drawer"] img',
  2388. '[role="dialog"] [class*="card"]',
  2389. '[role="dialog"] img',
  2390. '[class*="popup"] img',
  2391. 'img[src*="douyinpic"]', // 直接找抖音图片
  2392. ];
  2393. let workElements: Awaited<ReturnType<typeof page.$$>> = [];
  2394. let usedSelector = '';
  2395. for (const selector of workSelectors) {
  2396. const elements = await page.$$(selector);
  2397. logger.info(`Selector "${selector}" found ${elements.length} elements`);
  2398. if (elements.length > 0 && elements.length < 50) { // 避免选中太多无关元素
  2399. workElements = elements;
  2400. usedSelector = selector;
  2401. break;
  2402. }
  2403. }
  2404. logger.info(`Using selector "${usedSelector}", found ${workElements.length} work items`);
  2405. if (workElements.length > 0) {
  2406. // 首先获取所有作品的评论数信息
  2407. // 根据 HTML 结构:
  2408. // - 作品项容器: div.container-Lkxos9 (类名可能变化,使用 [class*="container-"])
  2409. // - 标题: div.title-LUOP3b (类名可能变化,使用 [class*="title-"])
  2410. // - 评论数: div.right-os7ZB9 > div (类名可能变化,使用 [class*="right-"] > div)
  2411. const workInfoList = await page.evaluate(() => {
  2412. const works: Array<{ index: number; title: string; commentCount: number }> = [];
  2413. // 查找作品列表容器中的所有作品项
  2414. // 根据用户提供的 HTML,作品项的类名是 container-Lkxos9
  2415. const workContainers = document.querySelectorAll('[role="dialog"] [class*="container-"]');
  2416. console.log(`Found ${workContainers.length} work containers`);
  2417. workContainers.forEach((container, index) => {
  2418. // 检查是否包含图片(确认是作品项而不是其他容器)
  2419. const img = container.querySelector('img[src*="douyinpic"]');
  2420. if (!img) {
  2421. console.log(`Container ${index} has no douyinpic image, skipping`);
  2422. return;
  2423. }
  2424. // 提取标题
  2425. const titleEl = container.querySelector('[class*="title-"]');
  2426. const title = titleEl?.textContent?.trim() || `作品 ${works.length + 1}`;
  2427. // 提取评论数 - 在 right- 容器的最后一个 div 中
  2428. let commentCount = 0;
  2429. const rightContainer = container.querySelector('[class*="right-"]');
  2430. if (rightContainer) {
  2431. // 获取 right 容器下的所有直接 div 子元素
  2432. const divs = rightContainer.querySelectorAll(':scope > div');
  2433. if (divs.length > 0) {
  2434. // 最后一个 div 包含评论数
  2435. const lastDiv = divs[divs.length - 1];
  2436. const text = lastDiv.textContent?.trim() || '0';
  2437. const num = parseInt(text, 10);
  2438. if (!isNaN(num)) {
  2439. commentCount = num;
  2440. }
  2441. }
  2442. }
  2443. console.log(`Work ${works.length}: title="${title.slice(0, 30)}...", commentCount=${commentCount}`);
  2444. works.push({
  2445. index: works.length,
  2446. title: title.slice(0, 100),
  2447. commentCount
  2448. });
  2449. });
  2450. // 如果上面的选择器没找到,尝试备用方法
  2451. if (works.length === 0) {
  2452. console.log('Primary selector failed, trying fallback...');
  2453. // 直接查找包含 douyinpic 图片的元素的父容器
  2454. const images = document.querySelectorAll('[role="dialog"] img[src*="douyinpic"]');
  2455. images.forEach((img, index) => {
  2456. // 向上查找到作品项容器
  2457. let container = img.parentElement;
  2458. while (container && !container.classList.toString().includes('container-')) {
  2459. container = container.parentElement;
  2460. }
  2461. if (container) {
  2462. const titleEl = container.querySelector('[class*="title-"]');
  2463. const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
  2464. // 查找评论数
  2465. let commentCount = 0;
  2466. const rightEl = container.querySelector('[class*="right-"]');
  2467. if (rightEl) {
  2468. const text = rightEl.textContent?.trim() || '';
  2469. // 提取最后出现的数字
  2470. const matches = text.match(/\d+/g);
  2471. if (matches && matches.length > 0) {
  2472. commentCount = parseInt(matches[matches.length - 1], 10);
  2473. }
  2474. }
  2475. works.push({ index, title: title.slice(0, 100), commentCount });
  2476. }
  2477. });
  2478. }
  2479. return works;
  2480. });
  2481. logger.info(`Work info list (${workInfoList.length} items): ${JSON.stringify(workInfoList)}`);
  2482. // 过滤出评论数 > 0 的作品,或者评论数未知(-1)的作品
  2483. const worksWithComments = workInfoList.filter(w => w.commentCount > 0 || w.commentCount === -1);
  2484. logger.info(`Found ${worksWithComments.length} works with comments > 0 or unknown (out of ${workInfoList.length})`);
  2485. // 如果所有作品评论数都是0,则不处理任何作品
  2486. const allZero = workInfoList.every(w => w.commentCount === 0);
  2487. if (allZero) {
  2488. logger.info('All works have 0 comments, skipping all');
  2489. }
  2490. // 如果没有找到评论数信息或有未知的,处理这些作品
  2491. const indicesToProcess = allZero
  2492. ? []
  2493. : (worksWithComments.length > 0
  2494. ? worksWithComments.map(w => w.index)
  2495. : Array.from({ length: Math.min(workElements.length, 10) }, (_, i) => i));
  2496. logger.info(`Will process work indices: ${indicesToProcess.join(', ')}`);
  2497. // 遍历每个有评论的作品
  2498. for (let idx = 0; idx < indicesToProcess.length; idx++) {
  2499. const i = indicesToProcess[idx];
  2500. try {
  2501. const workInfo = workInfoList.find(w => w.index === i);
  2502. logger.info(`Processing work ${idx + 1}/${indicesToProcess.length} (index=${i}, title="${workInfo?.title}", expectedComments=${workInfo?.commentCount})...`);
  2503. // 重新打开选择作品弹窗
  2504. if (idx > 0) {
  2505. await selectBtn.click();
  2506. await page.waitForTimeout(3000);
  2507. }
  2508. // 重新获取元素列表(因为 DOM 可能已变化)
  2509. const currentItems = await page.$$(usedSelector);
  2510. if (i < currentItems.length) {
  2511. // 滚动到元素可见
  2512. await currentItems[i].scrollIntoViewIfNeeded();
  2513. await page.waitForTimeout(500);
  2514. // 点击元素
  2515. await currentItems[i].click();
  2516. await page.waitForTimeout(4000);
  2517. // 获取评论
  2518. const title = await getCurrentWorkTitle();
  2519. const comments = await extractCommentsFromCurrentPage();
  2520. logger.info(`Work index=${i}: title="${title.slice(0, 50)}", comments=${comments.length}`);
  2521. // 检查是否已经获取过这个作品的评论
  2522. const exists = allWorkComments.some(w =>
  2523. w.videoTitle === title ||
  2524. (w.comments.length > 0 && comments.length > 0 &&
  2525. w.comments[0].content === comments[0].content)
  2526. );
  2527. if (!exists && (comments.length > 0 || title)) {
  2528. allWorkComments.push({
  2529. videoId: `video_${Date.now()}_${i}`,
  2530. videoTitle: title || workInfo?.title || `作品 ${i + 1}`,
  2531. videoCoverUrl: '',
  2532. comments,
  2533. });
  2534. logger.info(`Work index=${i}: Saved ${comments.length} comments`);
  2535. } else {
  2536. logger.info(`Work index=${i}: Skipped (duplicate or empty)`);
  2537. }
  2538. }
  2539. } catch (err) {
  2540. logger.warn(`Error processing work index=${i}:`, err);
  2541. }
  2542. }
  2543. } else {
  2544. logger.warn('No work items found in modal');
  2545. }
  2546. // 按 Escape 关闭弹窗
  2547. try {
  2548. await page.keyboard.press('Escape');
  2549. await page.waitForTimeout(500);
  2550. } catch { }
  2551. } else {
  2552. logger.warn('"选择作品" button not found, only default comments will be returned');
  2553. }
  2554. await page.close();
  2555. await context.close();
  2556. await browser.close();
  2557. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  2558. logger.info(`Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  2559. return allWorkComments;
  2560. } catch (error) {
  2561. logger.error('Error fetching Douyin comments:', error);
  2562. try {
  2563. await browser.close();
  2564. } catch { }
  2565. return allWorkComments;
  2566. }
  2567. }
  2568. /**
  2569. * 获取小红书评论
  2570. */
  2571. async fetchXiaohongshuCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  2572. const browser = await chromium.launch({
  2573. headless: true,
  2574. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  2575. });
  2576. const allWorkComments: WorkComments[] = [];
  2577. try {
  2578. const context = await browser.newContext({
  2579. viewport: { width: 1920, height: 1080 },
  2580. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2581. });
  2582. // 设置 Cookie
  2583. const playwrightCookies = cookies.map(c => ({
  2584. name: c.name,
  2585. value: c.value,
  2586. domain: c.domain || '.xiaohongshu.com',
  2587. path: c.path || '/',
  2588. }));
  2589. await context.addCookies(playwrightCookies);
  2590. logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);
  2591. const page = await context.newPage();
  2592. // 用于捕获评论数据
  2593. const capturedComments: Map<string, CommentItem[]> = new Map();
  2594. const capturedNotes: Array<{
  2595. noteId: string;
  2596. title: string;
  2597. coverUrl: string;
  2598. }> = [];
  2599. // 设置 API 响应监听器
  2600. page.on('response', async (response) => {
  2601. const url = response.url();
  2602. try {
  2603. // 监听笔记列表 API
  2604. if (url.includes('/api/galaxy/creator/content/note_list') ||
  2605. url.includes('/api/galaxy/creator/notes')) {
  2606. const data = await response.json();
  2607. logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
  2608. const notes = data?.data?.notes || data?.data?.list || [];
  2609. for (const note of notes) {
  2610. capturedNotes.push({
  2611. noteId: note.note_id || note.id || '',
  2612. title: note.title || note.desc || '',
  2613. coverUrl: note.cover?.url || note.cover || '',
  2614. });
  2615. }
  2616. }
  2617. // 监听评论列表 API
  2618. if (url.includes('/api/sns/web/v2/comment/page') ||
  2619. url.includes('/api/galaxy/creator/comment') ||
  2620. url.includes('/api/sns/v1/note/comment')) {
  2621. const data = await response.json();
  2622. logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
  2623. const comments: CommentItem[] = [];
  2624. const commentList = data?.data?.comments || data?.comments || [];
  2625. for (const comment of commentList) {
  2626. comments.push({
  2627. commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
  2628. authorId: comment.user_info?.user_id || comment.user_id || '',
  2629. authorName: comment.user_info?.nickname || comment.nickname || '',
  2630. authorAvatar: comment.user_info?.image || comment.avatar || '',
  2631. content: comment.content || '',
  2632. likeCount: comment.like_count || 0,
  2633. commentTime: comment.create_time || comment.time || '',
  2634. parentCommentId: comment.target_comment_id || undefined,
  2635. });
  2636. // 处理子评论
  2637. const subComments = comment.sub_comments || comment.replies || [];
  2638. for (const sub of subComments) {
  2639. comments.push({
  2640. commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
  2641. authorId: sub.user_info?.user_id || sub.user_id || '',
  2642. authorName: sub.user_info?.nickname || sub.nickname || '',
  2643. authorAvatar: sub.user_info?.image || sub.avatar || '',
  2644. content: sub.content || '',
  2645. likeCount: sub.like_count || 0,
  2646. commentTime: sub.create_time || sub.time || '',
  2647. parentCommentId: comment.id || comment.comment_id || undefined,
  2648. });
  2649. }
  2650. }
  2651. // 尝试从 URL 获取笔记 ID
  2652. const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
  2653. const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;
  2654. if (comments.length > 0) {
  2655. const existing = capturedComments.get(noteId) || [];
  2656. capturedComments.set(noteId, [...existing, ...comments]);
  2657. }
  2658. }
  2659. } catch { }
  2660. });
  2661. // 导航到评论管理页面
  2662. logger.info('[Xiaohongshu Comments] Navigating to comment management...');
  2663. await page.goto('https://creator.xiaohongshu.com/creator/comment', {
  2664. waitUntil: 'domcontentloaded',
  2665. timeout: 60000,
  2666. });
  2667. await page.waitForTimeout(5000);
  2668. // 检查是否需要登录
  2669. const currentUrl = page.url();
  2670. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  2671. logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
  2672. await browser.close();
  2673. return allWorkComments;
  2674. }
  2675. // 尝试加载更多评论
  2676. for (let i = 0; i < 5; i++) {
  2677. await page.evaluate(() => {
  2678. window.scrollBy(0, 500);
  2679. });
  2680. await page.waitForTimeout(1000);
  2681. }
  2682. // 等待 API 响应
  2683. await page.waitForTimeout(3000);
  2684. // 将捕获的评论转换为 WorkComments 格式
  2685. for (const [noteId, comments] of capturedComments) {
  2686. const noteInfo = capturedNotes.find(n => n.noteId === noteId);
  2687. allWorkComments.push({
  2688. videoId: noteId,
  2689. videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
  2690. videoCoverUrl: noteInfo?.coverUrl || '',
  2691. comments,
  2692. });
  2693. }
  2694. // 如果没有从 API 获取到评论,尝试从页面提取
  2695. if (allWorkComments.length === 0) {
  2696. logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');
  2697. const pageComments = await page.evaluate(() => {
  2698. const result: Array<{
  2699. commentId: string;
  2700. authorName: string;
  2701. authorAvatar: string;
  2702. content: string;
  2703. likeCount: number;
  2704. commentTime: string;
  2705. }> = [];
  2706. const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
  2707. commentItems.forEach((item, index) => {
  2708. try {
  2709. const authorEl = item.querySelector('[class*="author"], [class*="name"]');
  2710. const avatarEl = item.querySelector('img');
  2711. const contentEl = item.querySelector('[class*="content"]');
  2712. const timeEl = item.querySelector('[class*="time"]');
  2713. const likeEl = item.querySelector('[class*="like"] span');
  2714. result.push({
  2715. commentId: `xhs_page_${index}`,
  2716. authorName: authorEl?.textContent?.trim() || '',
  2717. authorAvatar: avatarEl?.src || '',
  2718. content: contentEl?.textContent?.trim() || '',
  2719. likeCount: parseInt(likeEl?.textContent || '0') || 0,
  2720. commentTime: timeEl?.textContent?.trim() || '',
  2721. });
  2722. } catch { }
  2723. });
  2724. return result;
  2725. });
  2726. if (pageComments.length > 0) {
  2727. allWorkComments.push({
  2728. videoId: 'page_comments',
  2729. videoTitle: '页面评论',
  2730. videoCoverUrl: '',
  2731. comments: pageComments.map(c => ({
  2732. ...c,
  2733. authorId: '',
  2734. })),
  2735. });
  2736. }
  2737. }
  2738. await page.close();
  2739. await context.close();
  2740. await browser.close();
  2741. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  2742. logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  2743. return allWorkComments;
  2744. } catch (error) {
  2745. logger.error('[Xiaohongshu Comments] Error:', error);
  2746. try {
  2747. await browser.close();
  2748. } catch { }
  2749. return allWorkComments;
  2750. }
  2751. }
  2752. }
  2753. export const headlessBrowserService = new HeadlessBrowserService();