HeadlessBrowserService.ts 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628
  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. // Python 服务配置
  6. const PYTHON_SERVICE_URL = process.env.PYTHON_PUBLISH_SERVICE_URL || process.env.XHS_SERVICE_URL || 'http://localhost:5005';
  7. // 抖音 API 接口配置
  8. const DOUYIN_API = {
  9. // 检查用户登录状态 - 返回 result: true 表示已登录(需要在浏览器上下文中调用)
  10. CHECK_USER: '/aweme/v1/creator/check/user/',
  11. // 获取作品列表(新接口,支持分页)
  12. WORK_LIST: 'https://creator.douyin.com/janus/douyin/creator/pc/work_list',
  13. // 获取评论列表
  14. COMMENT_LIST: 'https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/',
  15. // 创作者首页(用于触发登录检查)
  16. CREATOR_HOME: 'https://creator.douyin.com/creator-micro/home',
  17. };
  18. // 平台 API 配置(用于直接 HTTP 请求检查)
  19. const PLATFORM_API_CONFIG: Record<string, {
  20. checkUrl: string;
  21. isValidResponse: (data: unknown) => boolean;
  22. }> = {
  23. douyin: {
  24. // 使用账号基础信息接口检查 Cookie 有效性
  25. checkUrl: 'https://creator.douyin.com/web/api/creator/mcn/account_base_info?show_mcn_status=1',
  26. isValidResponse: (data: unknown) => {
  27. const resp = data as { status_code?: number; BaseResp?: { StatusCode?: number } };
  28. // status_code 为 0 表示 Cookie 有效
  29. return resp?.status_code === 0 || resp?.BaseResp?.StatusCode === 0;
  30. },
  31. },
  32. baijiahao: {
  33. // 使用 appinfo 接口检查 Cookie 有效性
  34. checkUrl: 'https://baijiahao.baidu.com/builder/app/appinfo',
  35. isValidResponse: (data: unknown) => {
  36. const resp = data as {
  37. errno?: number;
  38. errmsg?: string;
  39. data?: {
  40. user?: {
  41. name?: string;
  42. app_id?: string | number;
  43. userid?: number;
  44. status?: string;
  45. }
  46. }
  47. };
  48. logger.info(`[Baijiahao] API response: errno=${resp?.errno}, errmsg=${resp?.errmsg}, user.name=${resp?.data?.user?.name}, user.app_id=${resp?.data?.user?.app_id}, user.status=${resp?.data?.user?.status}`);
  49. // errno 为 0 表示请求成功
  50. const isErrnoOk = resp?.errno === 0;
  51. // 必须有用户信息(name 或 app_id)
  52. const hasUserInfo = !!(resp?.data?.user?.name || resp?.data?.user?.app_id);
  53. // 用户状态不能是 'banned' 或其他异常状态
  54. const userStatus = resp?.data?.user?.status;
  55. const isStatusOk = !userStatus || userStatus === 'audit' || userStatus === 'pass' || userStatus === 'active';
  56. const isValid = isErrnoOk && hasUserInfo && isStatusOk;
  57. if (!isValid) {
  58. logger.warn(`[Baijiahao] Cookie invalid: errno=${resp?.errno}, hasUserInfo=${hasUserInfo}, status=${userStatus}`);
  59. }
  60. return isValid;
  61. },
  62. },
  63. };
  64. export interface AccountInfo {
  65. accountId: string;
  66. accountName: string;
  67. avatarUrl: string;
  68. fansCount: number;
  69. worksCount: number;
  70. worksList?: WorkItem[];
  71. }
  72. export interface WorkItem {
  73. videoId?: string;
  74. title: string;
  75. coverUrl: string;
  76. duration: string;
  77. publishTime: string;
  78. status: string;
  79. playCount: number;
  80. likeCount: number;
  81. commentCount: number;
  82. shareCount: number;
  83. }
  84. export interface CommentItem {
  85. commentId: string;
  86. authorId: string;
  87. authorName: string;
  88. authorAvatar: string;
  89. content: string;
  90. likeCount: number;
  91. commentTime: string;
  92. parentCommentId?: string;
  93. videoId?: string;
  94. videoTitle?: string;
  95. videoCoverUrl?: string;
  96. }
  97. export interface WorkComments {
  98. videoId: string;
  99. videoTitle: string;
  100. videoCoverUrl: string;
  101. comments: CommentItem[];
  102. }
  103. export interface CookieData {
  104. name: string;
  105. value: string;
  106. domain: string;
  107. path: string;
  108. }
  109. /**
  110. * 无头浏览器服务 - 用于后台静默获取账号信息
  111. */
  112. class HeadlessBrowserService {
  113. /**
  114. * 检查 Cookie 是否有效
  115. * 优先使用 Python 服务(通过浏览器访问后台检测),回退到 API 检查
  116. */
  117. async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
  118. logger.info(`[checkCookieValid] Checking cookie for ${platform}, cookie count: ${cookies.length}`);
  119. // 优先使用 Python 服务检查(通过浏览器访问后台页面,检测是否被重定向到登录页)
  120. const pythonAvailable = await this.checkPythonServiceAvailable();
  121. if (pythonAvailable) {
  122. try {
  123. const result = await this.checkLoginViaPython(platform, cookies);
  124. logger.info(`[checkCookieValid] Python service result for ${platform}: ${result}`);
  125. return result;
  126. } catch (error) {
  127. logger.warn(`[Python API] Check login failed, falling back to API check:`, error);
  128. }
  129. } else {
  130. logger.info(`[checkCookieValid] Python service not available, using API check`);
  131. }
  132. // 回退到 API 检查
  133. const apiConfig = PLATFORM_API_CONFIG[platform];
  134. if (apiConfig) {
  135. const result = await this.checkCookieValidByApi(platform, cookies, apiConfig);
  136. logger.info(`[checkCookieValid] API check result for ${platform}: ${result}`);
  137. return result;
  138. }
  139. // 其他平台使用浏览器检查
  140. const result = await this.checkCookieValidByBrowser(platform, cookies);
  141. logger.info(`[checkCookieValid] Browser check result for ${platform}: ${result}`);
  142. return result;
  143. }
  144. /**
  145. * 通过 Python 服务检查登录状态(浏览器访问后台页面,检测是否需要登录)
  146. */
  147. private async checkLoginViaPython(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
  148. const pythonUrl = PYTHON_SERVICE_URL;
  149. // 构建 Cookie 字符串
  150. const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
  151. logger.info(`[Python API] Checking login status for ${platform}`);
  152. const response = await fetch(`${pythonUrl}/check_login`, {
  153. method: 'POST',
  154. headers: { 'Content-Type': 'application/json' },
  155. body: JSON.stringify({
  156. platform,
  157. cookie: cookieString,
  158. }),
  159. });
  160. if (!response.ok) {
  161. throw new Error(`Python API returned ${response.status}`);
  162. }
  163. const result = await response.json() as {
  164. success: boolean;
  165. valid: boolean;
  166. need_login: boolean;
  167. message?: string;
  168. error?: string;
  169. };
  170. logger.info(`[Python API] Check login result for ${platform}: valid=${result.valid}, need_login=${result.need_login}`);
  171. if (!result.success) {
  172. throw new Error(result.error || 'Check login failed');
  173. }
  174. return result.valid && !result.need_login;
  175. }
  176. /**
  177. * 通过 API 检查 Cookie 是否有效
  178. * 注意:API 返回不确定状态时会回退到浏览器检查,避免误判
  179. */
  180. private async checkCookieValidByApi(
  181. platform: PlatformType,
  182. cookies: CookieData[],
  183. apiConfig: typeof PLATFORM_API_CONFIG[string]
  184. ): Promise<boolean> {
  185. try {
  186. // 构建 Cookie 字符串(所有 Cookie 拼接)
  187. const cookieString = cookies
  188. .map(c => `${c.name}=${c.value}`)
  189. .join('; ');
  190. logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);
  191. // 发起 API 请求,模拟浏览器请求
  192. const response = await fetch(apiConfig.checkUrl, {
  193. method: 'GET',
  194. headers: {
  195. 'Accept': 'application/json, text/plain, */*',
  196. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  197. 'Cache-Control': 'no-cache',
  198. 'Cookie': cookieString,
  199. 'Pragma': 'no-cache',
  200. 'Referer': this.getPlatformReferer(platform),
  201. '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',
  202. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  203. 'sec-ch-ua-mobile': '?0',
  204. 'sec-ch-ua-platform': '"Windows"',
  205. 'sec-fetch-dest': 'empty',
  206. 'sec-fetch-mode': 'cors',
  207. 'sec-fetch-site': 'same-origin',
  208. },
  209. });
  210. const data = await response.json();
  211. logger.info(`[API] Raw response for ${platform}:`, JSON.stringify(data).substring(0, 500));
  212. const isValid = apiConfig.isValidResponse(data);
  213. const statusCode = (data as { status_code?: number; errno?: number; ret?: { errno?: number } })?.status_code
  214. ?? (data as { errno?: number })?.errno
  215. ?? (data as { ret?: { errno?: number } })?.ret?.errno;
  216. logger.info(`API check cookie for ${platform}: valid=${isValid}, statusCode=${statusCode}`);
  217. // 如果 API 明确返回有效,直接返回 true
  218. if (isValid) {
  219. return true;
  220. }
  221. // API 返回无效时,检查是否是明确的"未登录"状态
  222. // 抖音: status_code 为 2 或 8 通常表示未登录/登录过期
  223. // 百家号: errno 为非 0 可能表示未登录,但需要根据具体错误码判断
  224. const clearlyNotLoggedIn = statusCode === 2 || statusCode === 8;
  225. if (clearlyNotLoggedIn) {
  226. logger.info(`[API] Platform ${platform} clearly not logged in (statusCode=${statusCode})`);
  227. return false;
  228. }
  229. // 百家号特殊处理:根据 errno 判断
  230. if (platform === 'baijiahao') {
  231. const errno = (data as { errno?: number })?.errno;
  232. // errno 为 0 表示请求成功,但可能没有用户信息(已在 isValidResponse 中检查)
  233. if (errno === 0) {
  234. // 如果 isValid 为 false,说明虽然请求成功但没有用户信息,可能是 Cookie 无效
  235. if (!isValid) {
  236. logger.warn(`[API] Baijiahao errno=0 but no user info, cookie may be invalid`);
  237. return false;
  238. }
  239. return true;
  240. }
  241. // errno 非 0 表示请求失败,可能是 Cookie 无效
  242. // 常见错误码:
  243. // - 110: 未登录
  244. // - 其他非 0 值:可能是权限问题或其他错误
  245. logger.warn(`[API] Baijiahao errno=${errno}, cookie is invalid`);
  246. return false;
  247. }
  248. // 不确定的状态(如 status_code=7),回退到浏览器检查
  249. logger.info(`[API] Uncertain status for ${platform} (statusCode=${statusCode}), falling back to browser check`);
  250. return this.checkCookieValidByBrowser(platform, cookies);
  251. } catch (error) {
  252. logger.error(`API check cookie error for ${platform}:`, error);
  253. // API 检查失败时,回退到浏览器检查
  254. return this.checkCookieValidByBrowser(platform, cookies);
  255. }
  256. }
  257. /**
  258. * 获取平台 Referer
  259. */
  260. private getPlatformReferer(platform: PlatformType): string {
  261. const referers: Record<string, string> = {
  262. douyin: 'https://creator.douyin.com/',
  263. bilibili: 'https://member.bilibili.com/',
  264. kuaishou: 'https://cp.kuaishou.com/',
  265. baijiahao: 'https://baijiahao.baidu.com/',
  266. };
  267. return referers[platform] || '';
  268. }
  269. /**
  270. * 通过浏览器检查 Cookie 是否有效(检查是否被重定向到登录页)
  271. * 注意:网络错误或服务不可用时返回 true(保持原状态),避免误判为过期
  272. */
  273. private async checkCookieValidByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
  274. // 对于抖音平台,使用 check/user 接口检查
  275. if (platform === 'douyin') {
  276. return this.checkDouyinLoginByApi(cookies);
  277. }
  278. const browser = await chromium.launch({ headless: true });
  279. try {
  280. const context = await browser.newContext({
  281. viewport: { width: 1920, height: 1080 },
  282. locale: 'zh-CN',
  283. timezoneId: 'Asia/Shanghai',
  284. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  285. });
  286. await context.addCookies(cookies);
  287. const page = await context.newPage();
  288. const config = this.getPlatformConfig(platform);
  289. // 访问平台主页
  290. await page.goto(config.homeUrl, {
  291. waitUntil: 'domcontentloaded',
  292. timeout: 30000,
  293. });
  294. await page.waitForTimeout(3000);
  295. const url = page.url();
  296. logger.info(`Browser check cookie for ${platform}: URL=${url}`);
  297. // 检查是否被重定向到登录页
  298. const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));
  299. await page.close();
  300. await context.close();
  301. await browser.close();
  302. return !isLoginPage;
  303. } catch (error) {
  304. logger.error(`Browser check cookie error for ${platform}:`, error);
  305. await browser.close();
  306. // 网络错误或服务不可用时返回 true,避免误判为过期
  307. logger.warn(`[Browser] Check failed due to error, assuming valid to avoid false expiration`);
  308. return true;
  309. }
  310. }
  311. /**
  312. * 抖音登录状态检查 - 通过监听 check/user 接口
  313. * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
  314. */
  315. async checkDouyinLoginByApi(cookies: CookieData[]): Promise<boolean> {
  316. const browser = await chromium.launch({ headless: true });
  317. let isLoggedIn = false;
  318. let checkCompleted = false;
  319. try {
  320. const context = await browser.newContext({
  321. viewport: { width: 1920, height: 1080 },
  322. locale: 'zh-CN',
  323. timezoneId: 'Asia/Shanghai',
  324. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  325. });
  326. await context.addCookies(cookies);
  327. const page = await context.newPage();
  328. // 监听 check/user 接口响应
  329. page.on('response', async (response) => {
  330. const url = response.url();
  331. if (url.includes(DOUYIN_API.CHECK_USER)) {
  332. try {
  333. const data = await response.json();
  334. // result: true 表示已登录
  335. isLoggedIn = data?.result === true && data?.status_code === 0;
  336. checkCompleted = true;
  337. logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
  338. } catch {
  339. // 忽略解析错误
  340. }
  341. }
  342. });
  343. // 访问创作者首页,触发 check/user 接口
  344. await page.goto(DOUYIN_API.CREATOR_HOME, {
  345. waitUntil: 'domcontentloaded',
  346. timeout: 30000,
  347. });
  348. // 等待接口响应或超时
  349. const startTime = Date.now();
  350. while (!checkCompleted && Date.now() - startTime < 10000) {
  351. await page.waitForTimeout(500);
  352. }
  353. // 如果没有收到 check/user 响应,检查 URL 是否被重定向到登录页
  354. if (!checkCompleted) {
  355. const currentUrl = page.url();
  356. isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
  357. logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
  358. }
  359. await page.close();
  360. await context.close();
  361. await browser.close();
  362. return isLoggedIn;
  363. } catch (error) {
  364. logger.error('[Douyin] checkDouyinLoginByApi error:', error);
  365. try {
  366. await browser.close();
  367. } catch { }
  368. // 网络错误或服务不可用时返回 true,避免误判为过期
  369. logger.warn(`[Douyin] Check failed due to error, assuming valid to avoid false expiration`);
  370. return true;
  371. }
  372. }
  373. /**
  374. * 访问平台后台页面并截图(用于 AI 分析)
  375. * @param platform 平台类型
  376. * @param cookies Cookie 数据
  377. * @returns Base64 编码的截图,失败返回 null
  378. */
  379. async capturePageScreenshot(platform: PlatformType, cookies: CookieData[]): Promise<string | null> {
  380. const browser = await chromium.launch({ headless: true });
  381. try {
  382. const context = await browser.newContext({
  383. viewport: { width: 1920, height: 1080 },
  384. locale: 'zh-CN',
  385. timezoneId: 'Asia/Shanghai',
  386. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  387. });
  388. await context.addCookies(cookies);
  389. const page = await context.newPage();
  390. const config = this.getPlatformConfig(platform);
  391. logger.info(`[Screenshot] Navigating to ${platform} home page: ${config.homeUrl}`);
  392. // 访问平台主页
  393. await page.goto(config.homeUrl, {
  394. waitUntil: 'domcontentloaded',
  395. timeout: 30000,
  396. });
  397. // 等待页面加载
  398. await page.waitForTimeout(3000);
  399. const url = page.url();
  400. logger.info(`[Screenshot] Current URL: ${url}`);
  401. // 截图
  402. const screenshotBuffer = await page.screenshot({
  403. type: 'jpeg',
  404. quality: 80,
  405. fullPage: false,
  406. });
  407. const base64Screenshot = screenshotBuffer.toString('base64');
  408. await page.close();
  409. await context.close();
  410. await browser.close();
  411. logger.info(`[Screenshot] Captured screenshot for ${platform}, size: ${Math.round(base64Screenshot.length / 1024)}KB`);
  412. return base64Screenshot;
  413. } catch (error) {
  414. logger.error(`[Screenshot] Failed to capture screenshot for ${platform}:`, error);
  415. try {
  416. await browser.close();
  417. } catch { /* ignore */ }
  418. return null;
  419. }
  420. }
  421. /**
  422. * 检查 Python 服务是否可用
  423. */
  424. private async checkPythonServiceAvailable(): Promise<boolean> {
  425. try {
  426. const response = await fetch(`${PYTHON_SERVICE_URL}/health`, {
  427. method: 'GET',
  428. signal: AbortSignal.timeout(3000),
  429. });
  430. return response.ok;
  431. } catch {
  432. return false;
  433. }
  434. }
  435. /**
  436. * 通过 Python API 获取作品列表
  437. */
  438. private async fetchWorksViaPython(platform: PlatformType, cookies: CookieData[]): Promise<WorkItem[]> {
  439. logger.info(`[Python API] Fetching works for ${platform} (auto pagination)...`);
  440. const cookieString = JSON.stringify(cookies);
  441. const pythonPlatform = platform === 'weixin_video' ? 'weixin' : platform;
  442. const pageSize = 50;
  443. const maxPages = 30;
  444. const allWorks: WorkItem[] = [];
  445. const seenIds = new Set<string>();
  446. for (let page = 0; page < maxPages; page++) {
  447. logger.info(`[Python API] Fetching works page=${page}, page_size=${pageSize} for ${platform}`);
  448. const response = await fetch(`${PYTHON_SERVICE_URL}/works`, {
  449. method: 'POST',
  450. headers: {
  451. 'Content-Type': 'application/json',
  452. },
  453. body: JSON.stringify({
  454. platform: pythonPlatform,
  455. cookie: cookieString,
  456. page,
  457. page_size: pageSize,
  458. }),
  459. });
  460. if (!response.ok) {
  461. throw new Error(`Python API returned ${response.status}`);
  462. }
  463. const result = await response.json();
  464. if (!result.success) {
  465. throw new Error(result.error || 'Failed to get works');
  466. }
  467. const pageWorks: WorkItem[] = (result.works || []).map((work: {
  468. work_id: string;
  469. title: string;
  470. cover_url: string;
  471. duration: number;
  472. publish_time: string;
  473. status: string;
  474. play_count: number;
  475. like_count: number;
  476. comment_count: number;
  477. share_count: number;
  478. collect_count?: number;
  479. }) => ({
  480. videoId: work.work_id,
  481. title: work.title,
  482. coverUrl: work.cover_url,
  483. duration: String(work.duration || 0),
  484. publishTime: work.publish_time,
  485. status: work.status || 'published',
  486. playCount: work.play_count || 0,
  487. likeCount: work.like_count || 0,
  488. commentCount: work.comment_count || 0,
  489. shareCount: work.share_count || 0,
  490. }));
  491. let newCount = 0;
  492. for (const w of pageWorks) {
  493. const id = w.videoId || `${platform}_${w.title}_${w.publishTime}`;
  494. if (!seenIds.has(id)) {
  495. seenIds.add(id);
  496. allWorks.push(w);
  497. newCount++;
  498. }
  499. }
  500. logger.info(
  501. `[Python API] Page ${page} fetched=${pageWorks.length}, new=${newCount}, total=${allWorks.length}, has_more=${!!result.has_more}`
  502. );
  503. if (!result.has_more || pageWorks.length === 0 || newCount === 0) {
  504. break;
  505. }
  506. }
  507. logger.info(`[Python API] Total works fetched for ${platform}: ${allWorks.length}`);
  508. return allWorks;
  509. }
  510. /**
  511. * 获取账号信息(优先使用 Python API,回退到无头浏览器)
  512. */
  513. async fetchAccountInfo(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
  514. logger.info(`[fetchAccountInfo] Starting for platform: ${platform}`);
  515. // 百家号:优先走 Python 的 /account_info(包含粉丝数、作品数),避免 Node 直连分散认证问题
  516. if (platform === 'baijiahao') {
  517. const pythonAvailable = await this.checkPythonServiceAvailable();
  518. if (pythonAvailable) {
  519. logger.info(`[Python API] Service available, fetching account_info for baijiahao`);
  520. try {
  521. return await this.fetchAccountInfoViaPython(platform, cookies);
  522. } catch (error) {
  523. logger.warn(`[Python API] Failed to fetch account_info for baijiahao, falling back to direct API:`, error);
  524. }
  525. } else {
  526. logger.info(`[Python API] Service not available for baijiahao, falling back to direct API`);
  527. }
  528. // Python 不可用或失败时,回退到 Node 直连 API(可能仍会遇到分散认证问题)
  529. return this.fetchBaijiahaoAccountInfoDirectApi(cookies);
  530. }
  531. // 对于支持的平台,尝试使用 Python API 获取作品列表和账号信息
  532. // 同步作品需要全量:这里会通过 Python /works 自动分页拉取
  533. const supportedPlatforms: PlatformType[] = ['douyin', 'xiaohongshu', 'kuaishou', 'weixin_video', 'baijiahao'];
  534. if (supportedPlatforms.includes(platform)) {
  535. const pythonAvailable = await this.checkPythonServiceAvailable();
  536. if (pythonAvailable) {
  537. logger.info(`[Python API] Service available, trying to fetch works for ${platform}`);
  538. try {
  539. const worksList = await this.fetchWorksViaPython(platform, cookies);
  540. // 如果成功获取到作品,使用 Playwright 获取账号基本信息
  541. if (worksList.length > 0) {
  542. logger.info(`[Python API] Successfully fetched ${worksList.length} works for ${platform}`);
  543. try {
  544. const accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
  545. accountInfo.worksList = worksList;
  546. // 直接使用 Python API 获取的作品数量(最准确,排除了已删除/私密视频)
  547. accountInfo.worksCount = worksList.length;
  548. logger.info(`[fetchAccountInfo] Using Python API works count for ${platform}: ${accountInfo.worksCount}`);
  549. return accountInfo;
  550. } catch (playwrightError) {
  551. logger.warn(`[Playwright] Failed to get account info for ${platform}:`, playwrightError);
  552. const accountInfo = this.getDefaultAccountInfo(platform);
  553. accountInfo.worksList = worksList;
  554. accountInfo.worksCount = worksList.length;
  555. return accountInfo;
  556. }
  557. }
  558. // 作品列表为空,尝试用 Playwright 获取账号信息
  559. logger.info(`[Python API] Got empty works list for ${platform}, trying Playwright`);
  560. } catch (pythonError) {
  561. logger.warn(`[Python API] Failed to fetch works for ${platform}:`, pythonError);
  562. }
  563. } else {
  564. logger.info(`[Python API] Service not available for ${platform}`);
  565. }
  566. }
  567. // 使用 Playwright 获取账号信息
  568. logger.info(`[Playwright] Fetching account info for ${platform}`);
  569. return this.fetchAccountInfoWithPlaywright(platform, cookies);
  570. }
  571. /**
  572. * 使用 Playwright 获取账号信息(原方法)
  573. */
  574. private async fetchAccountInfoWithPlaywright(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
  575. const browser = await chromium.launch({ headless: true });
  576. try {
  577. const context = await browser.newContext({
  578. viewport: { width: 1920, height: 1080 },
  579. locale: 'zh-CN',
  580. timezoneId: 'Asia/Shanghai',
  581. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  582. });
  583. await context.addCookies(cookies);
  584. const page = await context.newPage();
  585. let accountInfo: AccountInfo;
  586. switch (platform) {
  587. case 'douyin':
  588. accountInfo = await this.fetchDouyinAccountInfo(page, context, cookies);
  589. break;
  590. case 'bilibili':
  591. accountInfo = await this.fetchBilibiliAccountInfo(page, context, cookies);
  592. break;
  593. case 'kuaishou':
  594. accountInfo = await this.fetchKuaishouAccountInfo(page, context, cookies);
  595. break;
  596. case 'xiaohongshu':
  597. accountInfo = await this.fetchXiaohongshuAccountInfo(page, context, cookies);
  598. break;
  599. case 'weixin_video':
  600. accountInfo = await this.fetchWeixinVideoAccountInfo(page, context, cookies);
  601. break;
  602. default:
  603. accountInfo = this.getDefaultAccountInfo(platform);
  604. }
  605. await page.close();
  606. await context.close();
  607. await browser.close();
  608. return accountInfo;
  609. } catch (error) {
  610. logger.error('HeadlessBrowser fetchAccountInfo error:', error);
  611. await browser.close();
  612. return this.getDefaultAccountInfo(platform);
  613. }
  614. }
  615. /**
  616. * 获取抖音账号信息 - 通过 API 方式获取
  617. * 1. 监听 check/user 接口验证登录状态
  618. * 2. 通过 work_list API 获取作品数和作品列表
  619. */
  620. private async fetchDouyinAccountInfo(
  621. page: Page,
  622. _context: BrowserContext,
  623. cookies: CookieData[]
  624. ): Promise<AccountInfo> {
  625. let accountId = `douyin_${Date.now()}`;
  626. let accountName = '抖音账号';
  627. let avatarUrl = '';
  628. let fansCount = 0;
  629. let worksCount = 0;
  630. let worksList: WorkItem[] = [];
  631. let isLoggedIn = false;
  632. // 用于存储从 API 捕获的数据
  633. const capturedData: {
  634. userInfo?: {
  635. nickname?: string;
  636. avatar?: string;
  637. uid?: string;
  638. sec_uid?: string;
  639. unique_id?: string; // 抖音号(如 Ethanfly9392)
  640. short_id?: string; // 短ID
  641. follower_count?: number;
  642. };
  643. worksList?: Array<{
  644. awemeId: string;
  645. title: string;
  646. coverUrl: string;
  647. duration: number;
  648. createTime: number;
  649. statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number };
  650. }>;
  651. total?: number;
  652. } = {};
  653. try {
  654. // 从 Cookie 获取用户 ID
  655. const uidCookie = cookies.find(c =>
  656. ['passport_uid', 'uid', 'ssid'].includes(c.name)
  657. );
  658. if (uidCookie?.value) {
  659. accountId = `douyin_${uidCookie.value}`;
  660. }
  661. // 设置 API 响应监听器
  662. page.on('response', async (response) => {
  663. const url = response.url();
  664. try {
  665. // 监听 check/user 接口 - 验证登录状态
  666. if (url.includes(DOUYIN_API.CHECK_USER)) {
  667. const data = await response.json();
  668. isLoggedIn = data?.result === true && data?.status_code === 0;
  669. logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
  670. }
  671. // 监听 work_list 接口 - 获取作品列表
  672. if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
  673. const data = await response.json();
  674. if (data?.aweme_list && data.aweme_list.length > 0) {
  675. // 优先从 author.aweme_count 获取真实的作品数(最准确)
  676. const firstAweme = data.aweme_list[0];
  677. const authorAwemeCount = firstAweme?.author?.aweme_count;
  678. if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
  679. capturedData.total = authorAwemeCount;
  680. logger.info(`[Douyin API] Using author.aweme_count as works count: ${authorAwemeCount}`);
  681. } else {
  682. // 备用方案:使用 items 数组长度
  683. const itemsCount = data?.items?.length || 0;
  684. if (itemsCount > 0) {
  685. capturedData.total = (capturedData.total || 0) + itemsCount;
  686. } else {
  687. // 如果没有 items,使用 aweme_list 长度
  688. capturedData.total = (capturedData.total || 0) + data.aweme_list.length;
  689. }
  690. }
  691. // 解析作品列表
  692. capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
  693. const statistics = aweme.statistics as Record<string, unknown> || {};
  694. const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
  695. const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';
  696. return {
  697. awemeId: String(aweme.aweme_id || ''),
  698. title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
  699. coverUrl,
  700. duration: Number(aweme.duration || 0),
  701. createTime: Number(aweme.create_time || 0),
  702. statistics: {
  703. play_count: Number(statistics.play_count || 0),
  704. digg_count: Number(statistics.digg_count || 0),
  705. comment_count: Number(statistics.comment_count || 0),
  706. share_count: Number(statistics.share_count || 0),
  707. },
  708. };
  709. });
  710. logger.info(`[Douyin API] work_list: itemsCount=${capturedData.total}, aweme_list_length=${capturedData.worksList?.length}`);
  711. }
  712. }
  713. // 监听账号信息接口 - 增加更多可能的接口
  714. if (url.includes('/account_base_info') ||
  715. url.includes('/user/info') ||
  716. url.includes('/creator/user') ||
  717. url.includes('/data/overview') ||
  718. url.includes('/creator-micro/data') ||
  719. url.includes('/home_data')) {
  720. const data = await response.json();
  721. logger.info(`[Douyin API] Captured response from: ${url.split('?')[0]}`);
  722. // 尝试多种数据结构
  723. const user = data?.user || data?.data?.user || data?.data || data;
  724. if (user) {
  725. const nickname = user.nickname || user.name || user.nick_name || user.user_name;
  726. const avatar = user.avatar_url || user.avatar_thumb?.url_list?.[0] || user.avatar || user.avatar_larger?.url_list?.[0];
  727. const uid = user.uid || user.user_id || user.id;
  728. const fans = user.follower_count || user.fans_count || user.mplatform_followers_count;
  729. // 获取抖音号(unique_id 或 short_id)
  730. const uniqueId = user.unique_id || user.short_id || user.douyin_id;
  731. if (nickname || uid || uniqueId) {
  732. capturedData.userInfo = {
  733. nickname: nickname,
  734. avatar: avatar,
  735. uid: uid,
  736. sec_uid: user.sec_uid,
  737. unique_id: uniqueId,
  738. short_id: user.short_id,
  739. follower_count: fans,
  740. };
  741. logger.info(`[Douyin API] user info captured: nickname=${capturedData.userInfo.nickname}, uid=${capturedData.userInfo.uid}, unique_id=${capturedData.userInfo.unique_id}`);
  742. }
  743. }
  744. }
  745. } catch (e) {
  746. // 忽略非 JSON 响应
  747. }
  748. });
  749. // 访问主页获取基本信息并触发 check/user 接口
  750. logger.info('[Douyin] Navigating to creator home...');
  751. await page.goto(DOUYIN_API.CREATOR_HOME, {
  752. waitUntil: 'domcontentloaded',
  753. timeout: 30000,
  754. });
  755. // 等待页面加载完成
  756. await page.waitForTimeout(3000);
  757. // 尝试等待网络空闲
  758. try {
  759. await page.waitForLoadState('networkidle', { timeout: 10000 });
  760. } catch {
  761. // 超时继续
  762. }
  763. // 额外等待确保 API 响应被捕获
  764. await page.waitForTimeout(2000);
  765. // 检查登录状态 - 如果没有从 API 获取到,通过 URL 判断
  766. if (!isLoggedIn) {
  767. const currentUrl = page.url();
  768. isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
  769. }
  770. if (!isLoggedIn) {
  771. logger.warn('[Douyin] Not logged in, returning default account info');
  772. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  773. }
  774. // 从页面提取基本账号信息(作为 API 数据的补充)
  775. const accountData = await page.evaluate(() => {
  776. const result: { name?: string; avatar?: string; fans?: number; douyinId?: string } = {};
  777. // 提取抖音号 - 多种方式
  778. // 方式1:通过选择器查找包含抖音号的元素
  779. const uniqueIdSelectors = [
  780. 'div[class*="unique"]',
  781. 'span[class*="unique"]',
  782. 'div[class*="douyin-id"]',
  783. 'span[class*="douyin-id"]',
  784. '[class*="account-id"]',
  785. '[class*="shortId"]',
  786. '[class*="short-id"]',
  787. ];
  788. for (const selector of uniqueIdSelectors) {
  789. const el = document.querySelector(selector);
  790. if (el) {
  791. const text = el.textContent?.trim() || '';
  792. const match = text.match(/抖音号[::]\s*(\S+)/) || text.match(/ID[::]\s*(\S+)/);
  793. if (match) {
  794. result.douyinId = match[1];
  795. break;
  796. }
  797. // 如果元素文本本身就是抖音号(无前缀)
  798. if (text && !text.includes('抖音号') && /^[a-zA-Z0-9_]+$/.test(text)) {
  799. result.douyinId = text;
  800. break;
  801. }
  802. }
  803. }
  804. // 方式2:全局搜索包含"抖音号"的文本
  805. if (!result.douyinId) {
  806. const allElements = Array.from(document.querySelectorAll('span, div, p'));
  807. for (const el of allElements) {
  808. const text = el.textContent?.trim() || '';
  809. // 匹配 "抖音号:xxx" 或 "抖音号: xxx"
  810. const match = text.match(/抖音号[::]\s*([a-zA-Z0-9_]+)/);
  811. if (match && match[1]) {
  812. result.douyinId = match[1];
  813. break;
  814. }
  815. }
  816. }
  817. // 查找头像 - 优先使用头像容器
  818. const avatarSelectors = [
  819. '[class*="avatar"] img',
  820. '[class*="user-avatar"] img',
  821. '[class*="profile"] img',
  822. 'img[class*="avatar"]',
  823. ];
  824. for (const selector of avatarSelectors) {
  825. const img = document.querySelector(selector) as HTMLImageElement;
  826. if (img?.src && (img.src.includes('aweme') || img.src.includes('douyinpic') || img.src.includes('bytedance'))) {
  827. result.avatar = img.src;
  828. break;
  829. }
  830. }
  831. // 备用方案:查找所有图片
  832. if (!result.avatar) {
  833. const avatarImgs = Array.from(document.querySelectorAll('img'));
  834. for (const img of avatarImgs) {
  835. const src = img.src || img.getAttribute('src') || '';
  836. if (src && (src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance'))) {
  837. const rect = img.getBoundingClientRect();
  838. if (rect.width > 30 && rect.width < 150 && rect.top < 300) {
  839. result.avatar = src;
  840. break;
  841. }
  842. }
  843. }
  844. }
  845. // 获取粉丝数 - 多种选择器
  846. const fansSelectors = [
  847. '#guide_home_fans',
  848. '[class*="fans"]',
  849. '[class*="follower"]',
  850. '[class*="data-item"]',
  851. ];
  852. for (const selector of fansSelectors) {
  853. const el = document.querySelector(selector);
  854. if (el) {
  855. const text = el.textContent?.trim() || '';
  856. // 匹配 "123" 或 "1.2万" 或 "粉丝 123"
  857. const match = text.match(/(\d+(?:\.\d+)?)\s*([万wW])?/);
  858. if (match) {
  859. let num = parseFloat(match[1]);
  860. if (match[2]) num *= 10000;
  861. result.fans = Math.floor(num);
  862. break;
  863. }
  864. }
  865. }
  866. // 查找用户名 - 更精确的选择器
  867. const nameSelectors = [
  868. '[class*="user-name"]',
  869. '[class*="nickname"]',
  870. '[class*="author-name"]',
  871. '[class*="profile-name"]',
  872. 'h1[class*="name"]',
  873. 'h2[class*="name"]',
  874. ];
  875. for (const selector of nameSelectors) {
  876. const el = document.querySelector(selector);
  877. if (el) {
  878. const text = el.textContent?.trim() || '';
  879. if (text && text.length >= 2 && text.length <= 30) {
  880. result.name = text;
  881. break;
  882. }
  883. }
  884. }
  885. // 备用方案:查找包含名字的容器
  886. if (!result.name) {
  887. const nameContainers = Array.from(document.querySelectorAll('[class*="name"], [class*="nick"], [class*="user"]'));
  888. for (const container of nameContainers) {
  889. const text = container.textContent?.trim() || '';
  890. if (text &&
  891. text.length >= 2 &&
  892. text.length <= 20 &&
  893. !text.includes('关注') &&
  894. !text.includes('粉丝') &&
  895. !text.includes('获赞') &&
  896. !text.includes('加载') &&
  897. !text.includes('创作') &&
  898. !text.includes('发布') &&
  899. !text.includes('抖音号') &&
  900. !text.match(/^\d+$/)) {
  901. const rect = container.getBoundingClientRect();
  902. if (rect.top < 400 && rect.left < 500) {
  903. result.name = text;
  904. break;
  905. }
  906. }
  907. }
  908. }
  909. return result;
  910. });
  911. // 优先使用抖音号作为 ID(unique_id),其次是页面提取的抖音号,最后是 uid
  912. if (capturedData.userInfo?.unique_id) {
  913. // 优先使用抖音号(如 Ethanfly9392)
  914. accountId = `douyin_${capturedData.userInfo.unique_id}`;
  915. logger.info(`[Douyin] Using unique_id as accountId: ${accountId}`);
  916. } else if (capturedData.userInfo?.short_id) {
  917. // 其次使用短ID
  918. accountId = `douyin_${capturedData.userInfo.short_id}`;
  919. logger.info(`[Douyin] Using short_id as accountId: ${accountId}`);
  920. } else if (accountData.douyinId) {
  921. // 使用页面提取的抖音号
  922. accountId = `douyin_${accountData.douyinId}`;
  923. logger.info(`[Douyin] Using page douyinId as accountId: ${accountId}`);
  924. } else if (capturedData.userInfo?.uid) {
  925. // 最后使用内部uid
  926. accountId = `douyin_${capturedData.userInfo.uid}`;
  927. logger.info(`[Douyin] Using uid as accountId: ${accountId}`);
  928. }
  929. accountName = capturedData.userInfo?.nickname || accountData.name || accountName;
  930. avatarUrl = capturedData.userInfo?.avatar || accountData.avatar || avatarUrl;
  931. fansCount = capturedData.userInfo?.follower_count || accountData.fans || fansCount;
  932. // 通过 API 获取作品列表
  933. logger.info('[Douyin] Fetching works via API...');
  934. const apiResult = await this.fetchWorksDirectApi(page);
  935. if (apiResult.works.length > 0) {
  936. // 使用 items 累计数量作为作品数(apiResult.total 现在是累计的 items.length)
  937. // 如果 total 为 0,则使用 works 列表长度
  938. worksCount = apiResult.total > 0 ? apiResult.total : apiResult.works.length;
  939. worksList = apiResult.works.map(w => ({
  940. videoId: w.awemeId,
  941. title: w.title,
  942. coverUrl: w.coverUrl,
  943. duration: '00:00',
  944. publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
  945. status: 'published',
  946. playCount: 0,
  947. likeCount: 0,
  948. commentCount: w.commentCount,
  949. shareCount: 0,
  950. }));
  951. logger.info(`[Douyin] Got ${apiResult.works.length} works from API, total count: ${worksCount}`);
  952. } else if (capturedData.worksList && capturedData.worksList.length > 0) {
  953. // 如果直接 API 调用失败,使用监听到的数据
  954. worksCount = capturedData.total || capturedData.worksList.length;
  955. worksList = capturedData.worksList.map(w => ({
  956. videoId: w.awemeId,
  957. title: w.title,
  958. coverUrl: w.coverUrl,
  959. duration: this.formatDuration(w.duration),
  960. publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
  961. status: 'published',
  962. playCount: w.statistics.play_count,
  963. likeCount: w.statistics.digg_count,
  964. commentCount: w.statistics.comment_count,
  965. shareCount: w.statistics.share_count,
  966. }));
  967. logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
  968. }
  969. } catch (error) {
  970. logger.warn('Failed to fetch Douyin account info:', error);
  971. }
  972. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  973. }
  974. /**
  975. * 格式化视频时长
  976. */
  977. private formatDuration(ms: number): string {
  978. if (!ms) return '00:00';
  979. const seconds = Math.floor(ms / 1000);
  980. const minutes = Math.floor(seconds / 60);
  981. const remainingSeconds = seconds % 60;
  982. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  983. }
  984. /**
  985. * 获取B站账号信息
  986. */
  987. private async fetchBilibiliAccountInfo(
  988. page: Page,
  989. _context: BrowserContext,
  990. cookies: CookieData[]
  991. ): Promise<AccountInfo> {
  992. let accountId = `bilibili_${Date.now()}`;
  993. let accountName = 'B站账号';
  994. let avatarUrl = '';
  995. let fansCount = 0;
  996. let worksCount = 0;
  997. try {
  998. const uidCookie = cookies.find(c => c.name === 'DedeUserID');
  999. if (uidCookie?.value) {
  1000. accountId = `bilibili_${uidCookie.value}`;
  1001. }
  1002. await page.goto('https://member.bilibili.com/platform/home', {
  1003. waitUntil: 'domcontentloaded',
  1004. timeout: 30000,
  1005. });
  1006. await page.waitForTimeout(3000);
  1007. // 获取用户名
  1008. const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
  1009. if (nameEl) {
  1010. const text = await nameEl.textContent();
  1011. if (text?.trim()) {
  1012. accountName = text.trim();
  1013. }
  1014. }
  1015. // 获取头像
  1016. const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
  1017. if (avatarEl) {
  1018. const src = await avatarEl.getAttribute('src');
  1019. if (src) {
  1020. avatarUrl = src;
  1021. }
  1022. }
  1023. } catch (error) {
  1024. logger.warn('Failed to fetch Bilibili account info:', error);
  1025. }
  1026. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1027. }
  1028. /**
  1029. * 获取快手账号信息
  1030. */
  1031. private async fetchKuaishouAccountInfo(
  1032. page: Page,
  1033. _context: BrowserContext,
  1034. cookies: CookieData[]
  1035. ): Promise<AccountInfo> {
  1036. let accountId = `kuaishou_${Date.now()}`;
  1037. let accountName = '快手账号';
  1038. let avatarUrl = '';
  1039. let fansCount = 0;
  1040. let worksCount = 0;
  1041. try {
  1042. const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
  1043. if (uidCookie?.value) {
  1044. accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
  1045. }
  1046. await page.goto('https://cp.kuaishou.com/profile', {
  1047. waitUntil: 'domcontentloaded',
  1048. timeout: 30000,
  1049. });
  1050. await page.waitForTimeout(3000);
  1051. // 获取用户名
  1052. const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
  1053. if (nameEl) {
  1054. const text = await nameEl.textContent();
  1055. if (text?.trim()) {
  1056. accountName = text.trim();
  1057. }
  1058. }
  1059. // 获取头像
  1060. const avatarEl = await page.$('[class*="avatar"] img');
  1061. if (avatarEl) {
  1062. const src = await avatarEl.getAttribute('src');
  1063. if (src) {
  1064. avatarUrl = src;
  1065. }
  1066. }
  1067. } catch (error) {
  1068. logger.warn('Failed to fetch Kuaishou account info:', error);
  1069. }
  1070. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1071. }
  1072. /**
  1073. * 获取微信视频号账号信息
  1074. */
  1075. private async fetchWeixinVideoAccountInfo(
  1076. page: Page,
  1077. _context: BrowserContext,
  1078. cookies: CookieData[]
  1079. ): Promise<AccountInfo> {
  1080. let accountId = `weixin_video_${Date.now()}`;
  1081. let accountName = '视频号账号';
  1082. let avatarUrl = '';
  1083. let fansCount = 0;
  1084. let worksCount = 0;
  1085. let finderId = '';
  1086. try {
  1087. // 从 Cookie 中提取用户标识
  1088. // 优先使用 finder_username(视频号唯一标识)
  1089. const finderUsernameCookie = cookies.find(c => c.name === 'finder_username');
  1090. if (finderUsernameCookie?.value) {
  1091. finderId = finderUsernameCookie.value;
  1092. accountId = `weixin_video_${finderId}`;
  1093. logger.info(`[WeixinVideo] Found finder_username from cookie: ${finderId}`);
  1094. }
  1095. // 备选:使用 wxuin 或 uin
  1096. if (!finderId) {
  1097. const uinCookie = cookies.find(c => c.name === 'wxuin' || c.name === 'uin');
  1098. if (uinCookie?.value) {
  1099. // 仍然保持时间戳格式,后续会尝试从页面获取真实 ID
  1100. accountId = `weixin_video_${uinCookie.value}`;
  1101. logger.info(`[WeixinVideo] Using uin from cookie: ${uinCookie.value}`);
  1102. }
  1103. }
  1104. // 访问视频号创作者平台首页
  1105. await page.goto('https://channels.weixin.qq.com/platform/home', {
  1106. waitUntil: 'domcontentloaded',
  1107. timeout: 30000,
  1108. });
  1109. await page.waitForTimeout(3000);
  1110. // 检查是否需要登录
  1111. const currentUrl = page.url();
  1112. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  1113. logger.warn('[WeixinVideo] Cookie expired, needs login');
  1114. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1115. }
  1116. // 从页面提取账号信息
  1117. const accountData = await page.evaluate(() => {
  1118. const result: { name?: string; avatar?: string; fans?: number; works?: number; finderId?: string } = {};
  1119. try {
  1120. // ===== 1. 优先使用精确选择器获取视频号 ID =====
  1121. // 方法1: 通过 #finder-uid-copy 的 data-clipboard-text 属性获取
  1122. const finderIdCopyEl = document.querySelector('#finder-uid-copy');
  1123. if (finderIdCopyEl) {
  1124. const clipboardText = finderIdCopyEl.getAttribute('data-clipboard-text');
  1125. if (clipboardText && clipboardText.length >= 10) {
  1126. result.finderId = clipboardText;
  1127. console.log('[WeixinVideo] Found finder ID from data-clipboard-text:', result.finderId);
  1128. } else {
  1129. // 备选:获取元素文本内容
  1130. const text = finderIdCopyEl.textContent?.trim();
  1131. if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
  1132. result.finderId = text;
  1133. console.log('[WeixinVideo] Found finder ID from #finder-uid-copy text:', result.finderId);
  1134. }
  1135. }
  1136. }
  1137. // 方法2: 通过 .finder-uniq-id 选择器获取
  1138. if (!result.finderId) {
  1139. const finderUniqIdEl = document.querySelector('.finder-uniq-id');
  1140. if (finderUniqIdEl) {
  1141. const clipboardText = finderUniqIdEl.getAttribute('data-clipboard-text');
  1142. if (clipboardText && clipboardText.length >= 10) {
  1143. result.finderId = clipboardText;
  1144. console.log('[WeixinVideo] Found finder ID from .finder-uniq-id data-clipboard-text:', result.finderId);
  1145. } else {
  1146. const text = finderUniqIdEl.textContent?.trim();
  1147. if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
  1148. result.finderId = text;
  1149. console.log('[WeixinVideo] Found finder ID from .finder-uniq-id text:', result.finderId);
  1150. }
  1151. }
  1152. }
  1153. }
  1154. // 方法3: 从页面文本中正则匹配
  1155. if (!result.finderId) {
  1156. const bodyText = document.body.innerText || '';
  1157. const finderIdPatterns = [
  1158. /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
  1159. /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
  1160. ];
  1161. for (const pattern of finderIdPatterns) {
  1162. const match = bodyText.match(pattern);
  1163. if (match && match[1] && match[1].length >= 10) {
  1164. result.finderId = match[1];
  1165. console.log('[WeixinVideo] Found finder ID from regex:', result.finderId);
  1166. break;
  1167. }
  1168. }
  1169. }
  1170. // ===== 2. 获取账号名称 =====
  1171. // 优先使用 h2.finder-nickname
  1172. const nicknameEl = document.querySelector('h2.finder-nickname') ||
  1173. document.querySelector('.finder-nickname');
  1174. if (nicknameEl) {
  1175. const text = nicknameEl.textContent?.trim();
  1176. if (text && text.length >= 2 && text.length <= 30) {
  1177. result.name = text;
  1178. console.log('[WeixinVideo] Found name from .finder-nickname:', result.name);
  1179. }
  1180. }
  1181. // 备选选择器
  1182. if (!result.name) {
  1183. const nameSelectors = [
  1184. '.account-name',
  1185. '[class*="nickname"]',
  1186. '[class*="userName"]',
  1187. ];
  1188. for (const selector of nameSelectors) {
  1189. const el = document.querySelector(selector);
  1190. const text = el?.textContent?.trim();
  1191. if (text && text.length >= 2 && text.length <= 30) {
  1192. result.name = text;
  1193. console.log('[WeixinVideo] Found name from selector:', selector, result.name);
  1194. break;
  1195. }
  1196. }
  1197. }
  1198. // ===== 3. 获取头像 =====
  1199. // 优先使用 img.avatar
  1200. const avatarEl = document.querySelector('img.avatar') as HTMLImageElement;
  1201. if (avatarEl?.src && avatarEl.src.startsWith('http')) {
  1202. result.avatar = avatarEl.src;
  1203. console.log('[WeixinVideo] Found avatar from img.avatar:', result.avatar);
  1204. }
  1205. // 备选选择器
  1206. if (!result.avatar) {
  1207. const avatarSelectors = [
  1208. '.finder-info-container img.avatar',
  1209. 'img[alt="视频号头像"]',
  1210. 'img[src*="wx.qlogo.cn/finderhead"]',
  1211. 'img[src*="wx.qlogo"]',
  1212. ];
  1213. for (const selector of avatarSelectors) {
  1214. const el = document.querySelector(selector) as HTMLImageElement;
  1215. if (el?.src && el.src.startsWith('http')) {
  1216. result.avatar = el.src;
  1217. console.log('[WeixinVideo] Found avatar from selector:', selector);
  1218. break;
  1219. }
  1220. }
  1221. }
  1222. // ===== 4. 获取视频数和关注者数 =====
  1223. // 使用 .finder-content-info 中的 .finder-info-num
  1224. const contentInfo = document.querySelector('.finder-content-info');
  1225. if (contentInfo) {
  1226. const infoDivs = contentInfo.querySelectorAll('div');
  1227. infoDivs.forEach(div => {
  1228. const text = div.textContent || '';
  1229. const numEl = div.querySelector('.finder-info-num');
  1230. if (numEl) {
  1231. const num = parseInt(numEl.textContent?.trim() || '0', 10);
  1232. if (text.includes('视频') || text.includes('作品')) {
  1233. result.works = num;
  1234. console.log('[WeixinVideo] Found works from .finder-info-num:', result.works);
  1235. } else if (text.includes('关注者') || text.includes('粉丝')) {
  1236. result.fans = num;
  1237. console.log('[WeixinVideo] Found fans from .finder-info-num:', result.fans);
  1238. }
  1239. }
  1240. });
  1241. }
  1242. // 备选:从页面整体文本中匹配
  1243. if (result.fans === undefined || result.works === undefined) {
  1244. const bodyText = document.body.innerText || '';
  1245. if (result.fans === undefined) {
  1246. const fansMatch = bodyText.match(/关注者\s*(\d+(?:\.\d+)?[万wW]?)/) ||
  1247. bodyText.match(/粉丝\s*(\d+(?:\.\d+)?[万wW]?)/);
  1248. if (fansMatch) {
  1249. let count = parseFloat(fansMatch[1]);
  1250. if (fansMatch[1].includes('万') || fansMatch[1].toLowerCase().includes('w')) {
  1251. count = count * 10000;
  1252. }
  1253. result.fans = Math.floor(count);
  1254. console.log('[WeixinVideo] Found fans from text:', result.fans);
  1255. }
  1256. }
  1257. if (result.works === undefined) {
  1258. const worksMatch = bodyText.match(/视频\s*(\d+)/) ||
  1259. bodyText.match(/作品\s*(\d+)/);
  1260. if (worksMatch) {
  1261. result.works = parseInt(worksMatch[1], 10);
  1262. console.log('[WeixinVideo] Found works from text:', result.works);
  1263. }
  1264. }
  1265. }
  1266. } catch (e) {
  1267. console.error('[WeixinVideo] Extract error:', e);
  1268. }
  1269. return result;
  1270. });
  1271. logger.info(`[WeixinVideo] Extracted account data from home page:`, accountData);
  1272. // 更新账号信息
  1273. if (accountData.name) {
  1274. accountName = accountData.name;
  1275. }
  1276. if (accountData.avatar) {
  1277. avatarUrl = accountData.avatar;
  1278. }
  1279. if (accountData.fans !== undefined) {
  1280. fansCount = accountData.fans;
  1281. }
  1282. if (accountData.works !== undefined) {
  1283. worksCount = accountData.works;
  1284. }
  1285. if (accountData.finderId) {
  1286. finderId = accountData.finderId;
  1287. accountId = `weixin_video_${accountData.finderId}`;
  1288. }
  1289. // 如果首页没有获取到视频号 ID,尝试访问账号设置页面
  1290. if (!finderId || finderId.length < 10) {
  1291. logger.info('[WeixinVideo] Finder ID not found on home page, trying account settings page...');
  1292. try {
  1293. // 访问账号设置页面
  1294. await page.goto('https://channels.weixin.qq.com/platform/account', {
  1295. waitUntil: 'domcontentloaded',
  1296. timeout: 30000,
  1297. });
  1298. await page.waitForTimeout(2000);
  1299. // 从账号设置页面提取视频号 ID
  1300. const settingsData = await page.evaluate(() => {
  1301. const result: { finderId?: string; name?: string } = {};
  1302. const bodyText = document.body.innerText || '';
  1303. // 尝试多种匹配模式
  1304. const patterns = [
  1305. /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
  1306. /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
  1307. /视频号[::\s]+([a-zA-Z0-9_]{10,})/,
  1308. /Finder\s*ID[::\s]*([a-zA-Z0-9_]+)/i,
  1309. /finder_username[::\s]*([a-zA-Z0-9_]+)/i,
  1310. /唯一标识[::\s]*([a-zA-Z0-9_]+)/,
  1311. ];
  1312. for (const pattern of patterns) {
  1313. const match = bodyText.match(pattern);
  1314. if (match && match[1]) {
  1315. result.finderId = match[1];
  1316. console.log('[WeixinVideo] Found finder ID from settings page:', result.finderId);
  1317. break;
  1318. }
  1319. }
  1320. // 从元素中查找
  1321. if (!result.finderId) {
  1322. const idSelectors = [
  1323. '[class*="finder-id"]',
  1324. '[class*="account-id"]',
  1325. '[class*="unique-id"]',
  1326. '.finder-uniq-id',
  1327. 'span.finder-uniq-id',
  1328. '[class*="copy-id"]',
  1329. ];
  1330. for (const selector of idSelectors) {
  1331. const el = document.querySelector(selector);
  1332. const text = el?.textContent?.trim();
  1333. if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10 && text.length <= 30) {
  1334. result.finderId = text;
  1335. console.log('[WeixinVideo] Found ID from settings selector:', result.finderId);
  1336. break;
  1337. }
  1338. }
  1339. }
  1340. return result;
  1341. });
  1342. logger.info(`[WeixinVideo] Extracted data from settings page:`, settingsData);
  1343. if (settingsData.finderId) {
  1344. finderId = settingsData.finderId;
  1345. accountId = `weixin_video_${settingsData.finderId}`;
  1346. }
  1347. } catch (settingsError) {
  1348. logger.warn('[WeixinVideo] Failed to fetch from settings page:', settingsError);
  1349. }
  1350. }
  1351. logger.info(`[WeixinVideo] Final account info: id=${accountId}, name=${accountName}, avatar=${avatarUrl ? 'yes' : 'no'}, fans=${fansCount}`);
  1352. } catch (error) {
  1353. logger.warn('Failed to fetch WeixinVideo account info:', error);
  1354. }
  1355. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1356. }
  1357. /**
  1358. * 获取小红书账号信息 - 通过 API 方式获取
  1359. */
  1360. private async fetchXiaohongshuAccountInfo(
  1361. page: Page,
  1362. _context: BrowserContext,
  1363. cookies: CookieData[]
  1364. ): Promise<AccountInfo> {
  1365. let accountId = `xiaohongshu_${Date.now()}`;
  1366. let accountName = '小红书账号';
  1367. let avatarUrl = '';
  1368. let fansCount = 0;
  1369. let worksCount = 0;
  1370. // 用于存储捕获的数据
  1371. const capturedData: {
  1372. userInfo?: {
  1373. nickname?: string;
  1374. avatar?: string;
  1375. userId?: string;
  1376. redId?: string;
  1377. fans?: number;
  1378. notes?: number;
  1379. };
  1380. } = {};
  1381. try {
  1382. // 从 Cookie 获取用户 ID
  1383. const userIdCookie = cookies.find(c =>
  1384. c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
  1385. );
  1386. if (userIdCookie?.value) {
  1387. accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
  1388. }
  1389. // 设置 API 响应监听器
  1390. page.on('response', async (response) => {
  1391. const url = response.url();
  1392. try {
  1393. // 监听用户信息 API
  1394. if (url.includes('/api/galaxy/creator/home/personal_info') ||
  1395. url.includes('/api/sns/web/v1/user/selfinfo') ||
  1396. url.includes('/user/selfinfo')) {
  1397. const data = await response.json();
  1398. logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));
  1399. // 解析用户信息
  1400. const userInfo = data?.data?.user_info || data?.data || data;
  1401. if (userInfo) {
  1402. capturedData.userInfo = {
  1403. nickname: userInfo.nickname || userInfo.name || userInfo.userName,
  1404. avatar: userInfo.image || userInfo.avatar || userInfo.images,
  1405. userId: userInfo.user_id || userInfo.userId,
  1406. redId: userInfo.red_id || userInfo.redId,
  1407. fans: userInfo.fans || userInfo.fansCount,
  1408. notes: userInfo.notes || userInfo.noteCount,
  1409. };
  1410. logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
  1411. }
  1412. }
  1413. // 监听创作者主页数据
  1414. if (url.includes('/api/galaxy/creator/home/home_page') ||
  1415. url.includes('/api/galaxy/creator/data')) {
  1416. const data = await response.json();
  1417. logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));
  1418. if (data?.data) {
  1419. const homeData = data.data;
  1420. // 获取粉丝数和笔记数
  1421. if (homeData.fans_count !== undefined) {
  1422. capturedData.userInfo = capturedData.userInfo || {};
  1423. capturedData.userInfo.fans = homeData.fans_count;
  1424. }
  1425. if (homeData.note_count !== undefined) {
  1426. capturedData.userInfo = capturedData.userInfo || {};
  1427. capturedData.userInfo.notes = homeData.note_count;
  1428. }
  1429. }
  1430. }
  1431. } catch {
  1432. // 忽略非 JSON 响应
  1433. }
  1434. });
  1435. // 导航到小红书创作者中心
  1436. logger.info('[Xiaohongshu] Navigating to creator center...');
  1437. await page.goto('https://creator.xiaohongshu.com/creator/home', {
  1438. waitUntil: 'domcontentloaded',
  1439. timeout: 30000,
  1440. });
  1441. // 等待页面加载
  1442. await page.waitForTimeout(3000);
  1443. // 检查是否需要登录
  1444. const currentUrl = page.url();
  1445. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  1446. logger.warn('[Xiaohongshu] Cookie expired, needs login');
  1447. return this.getDefaultAccountInfo('xiaohongshu');
  1448. }
  1449. // 等待 API 响应
  1450. await page.waitForTimeout(3000);
  1451. // 如果 API 没有捕获到数据,尝试从页面提取
  1452. if (!capturedData.userInfo?.nickname) {
  1453. logger.info('[Xiaohongshu] API did not return data, extracting from page...');
  1454. // 尝试获取用户名
  1455. const nameSelectors = [
  1456. '[class*="nickname"]',
  1457. '[class*="user-name"]',
  1458. '[class*="userName"]',
  1459. '.user-info .name',
  1460. '[class*="creator"] [class*="name"]',
  1461. ];
  1462. for (const selector of nameSelectors) {
  1463. const el = await page.$(selector);
  1464. if (el) {
  1465. const text = await el.textContent();
  1466. if (text?.trim() && text.trim().length < 50) {
  1467. accountName = text.trim();
  1468. logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
  1469. break;
  1470. }
  1471. }
  1472. }
  1473. // 尝试获取头像
  1474. const avatarSelectors = [
  1475. '[class*="avatar"] img',
  1476. '[class*="user-avatar"] img',
  1477. '.user-info img',
  1478. '[class*="creator"] img[src*="sns"]',
  1479. ];
  1480. for (const selector of avatarSelectors) {
  1481. const el = await page.$(selector);
  1482. if (el) {
  1483. const src = await el.getAttribute('src');
  1484. if (src && src.startsWith('http')) {
  1485. avatarUrl = src;
  1486. logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
  1487. break;
  1488. }
  1489. }
  1490. }
  1491. // 尝试获取粉丝数
  1492. const statsText = await page.textContent('body');
  1493. const fansMatch = statsText?.match(/粉丝[::\s]*(\d+(?:\.\d+)?[万亿]?)/);
  1494. if (fansMatch) {
  1495. fansCount = this.parseChineseNumber(fansMatch[1]);
  1496. logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
  1497. }
  1498. const notesMatch = statsText?.match(/笔记[::\s]*(\d+)/);
  1499. if (notesMatch) {
  1500. worksCount = parseInt(notesMatch[1], 10);
  1501. logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
  1502. }
  1503. }
  1504. // 使用捕获的数据
  1505. if (capturedData.userInfo) {
  1506. if (capturedData.userInfo.nickname) {
  1507. accountName = capturedData.userInfo.nickname;
  1508. }
  1509. if (capturedData.userInfo.avatar) {
  1510. avatarUrl = capturedData.userInfo.avatar;
  1511. }
  1512. // 优先使用小红书号(redId)作为 accountId
  1513. if (capturedData.userInfo.redId) {
  1514. accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
  1515. logger.info(`[Xiaohongshu] Using redId as accountId: ${accountId}`);
  1516. } else if (capturedData.userInfo.userId) {
  1517. accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
  1518. }
  1519. if (capturedData.userInfo.fans) {
  1520. fansCount = capturedData.userInfo.fans;
  1521. }
  1522. if (capturedData.userInfo.notes) {
  1523. worksCount = capturedData.userInfo.notes;
  1524. }
  1525. }
  1526. // 如果还没获取到小红书号,尝试从页面文本中提取
  1527. if (!accountId.match(/xiaohongshu_[a-zA-Z0-9_]+/) || accountId.includes('_' + Date.now().toString().slice(0, 8))) {
  1528. const bodyText = await page.textContent('body');
  1529. // 匹配小红书号格式:小红书号:xxxxxxx
  1530. const xhsIdMatch = bodyText?.match(/小红书号[::]\s*([a-zA-Z0-9_]+)/) ||
  1531. bodyText?.match(/红书号[::]\s*([a-zA-Z0-9_]+)/);
  1532. if (xhsIdMatch) {
  1533. accountId = `xiaohongshu_${xhsIdMatch[1]}`;
  1534. logger.info(`[Xiaohongshu] Found 小红书号 from page text: ${accountId}`);
  1535. }
  1536. }
  1537. logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
  1538. // 获取作品列表 - 通过监听 API 接口
  1539. const worksList: WorkItem[] = [];
  1540. try {
  1541. logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');
  1542. // 存储所有捕获的笔记数据
  1543. const allNotesData: Array<{
  1544. noteId: string;
  1545. title: string;
  1546. coverUrl: string;
  1547. status: number;
  1548. publishTime: string;
  1549. type: string;
  1550. duration: number;
  1551. likeCount: number;
  1552. commentCount: number;
  1553. collectCount: number;
  1554. viewCount: number;
  1555. shareCount: number;
  1556. }> = [];
  1557. let currentPage = 0;
  1558. let hasMorePages = true;
  1559. const maxPages = 20; // 最多获取20页,防止无限循环
  1560. // 设置 API 响应监听器 - 在导航之前绑定
  1561. let apiResponseReceived = false;
  1562. let totalNotesCount = 0; // 从 tags 中获取的总作品数
  1563. const notesApiHandler = async (response: import('playwright').Response) => {
  1564. const url = response.url();
  1565. try {
  1566. // 监听小红书笔记列表 API
  1567. // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
  1568. if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
  1569. url.includes('/api/sns/v5/creator/note/user/posted') ||
  1570. url.includes('creator/note/user/posted')) {
  1571. const data = await response.json();
  1572. logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);
  1573. if ((data?.success || data?.code === 0) && data?.data) {
  1574. apiResponseReceived = true;
  1575. // 从 tags 中获取总作品数
  1576. // tags 数组中 id="special.note_time_desc" 的项("所有笔记")包含总数
  1577. if (data.data.tags && Array.isArray(data.data.tags)) {
  1578. const allNotesTag = data.data.tags.find((tag: { id?: string; notes_count?: number }) =>
  1579. tag.id === 'special.note_time_desc'
  1580. );
  1581. if (allNotesTag?.notes_count !== undefined) {
  1582. totalNotesCount = allNotesTag.notes_count;
  1583. logger.info(`[Xiaohongshu API] Total notes count from tags: ${totalNotesCount}`);
  1584. }
  1585. }
  1586. const notes = data.data.notes || [];
  1587. for (const note of notes) {
  1588. // 根据 API 返回格式解析数据
  1589. // images_list 是数组,第一个元素包含 url
  1590. // 将 http:// 转换为 https:// 以确保图片能正常加载
  1591. let coverUrl = note.images_list?.[0]?.url || '';
  1592. if (coverUrl.startsWith('http://')) {
  1593. coverUrl = coverUrl.replace('http://', 'https://');
  1594. }
  1595. const duration = note.video_info?.duration || 0;
  1596. logger.info(`[Xiaohongshu API] Note: id=${note.id}, title="${note.display_title}", cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
  1597. allNotesData.push({
  1598. noteId: note.id || '',
  1599. title: note.display_title || '',
  1600. coverUrl: coverUrl,
  1601. status: note.tab_status || 1, // 1=已发布
  1602. publishTime: note.time || '',
  1603. type: note.type || 'normal', // video/normal
  1604. duration: duration,
  1605. likeCount: note.likes || 0,
  1606. commentCount: note.comments_count || 0,
  1607. collectCount: note.collected_count || 0,
  1608. viewCount: note.view_count || 0,
  1609. shareCount: note.shared_count || 0,
  1610. });
  1611. }
  1612. // 检查是否还有更多页面
  1613. // page=-1 表示没有更多数据
  1614. if (data.data.page === -1 || notes.length === 0) {
  1615. hasMorePages = false;
  1616. logger.info(`[Xiaohongshu API] No more pages (page indicator: ${data.data.page})`);
  1617. }
  1618. } else {
  1619. hasMorePages = false;
  1620. }
  1621. }
  1622. } catch (e) {
  1623. // 只在有相关 URL 时打印警告
  1624. if (url.includes('creator/note')) {
  1625. logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
  1626. }
  1627. }
  1628. };
  1629. // 先绑定监听器
  1630. page.on('response', notesApiHandler);
  1631. logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');
  1632. // 导航到笔记管理页面 - 使用 domcontentloaded 加快加载,避免 networkidle 超时
  1633. try {
  1634. await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
  1635. waitUntil: 'domcontentloaded',
  1636. timeout: 30000,
  1637. });
  1638. } catch (navError) {
  1639. // 导航超时不影响已捕获的 API 数据
  1640. logger.warn('[Xiaohongshu] Navigation timeout, but API data may have been captured');
  1641. }
  1642. // 等待 API 响应
  1643. await page.waitForTimeout(5000);
  1644. logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);
  1645. // 如果监听器没有捕获到数据,尝试直接调用 API
  1646. if (allNotesData.length === 0) {
  1647. logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');
  1648. try {
  1649. // 直接在页面上下文中调用 API
  1650. const apiResponse = await page.evaluate(async () => {
  1651. const response = await fetch('https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=0', {
  1652. method: 'GET',
  1653. credentials: 'include',
  1654. headers: {
  1655. 'Accept': 'application/json',
  1656. },
  1657. });
  1658. return await response.json();
  1659. });
  1660. logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
  1661. if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
  1662. // 从 tags 中获取总作品数
  1663. if (apiResponse.data.tags && Array.isArray(apiResponse.data.tags)) {
  1664. const allNotesTag = apiResponse.data.tags.find((tag: { id?: string; notes_count?: number }) =>
  1665. tag.id === 'special.note_time_desc'
  1666. );
  1667. if (allNotesTag?.notes_count !== undefined) {
  1668. totalNotesCount = allNotesTag.notes_count;
  1669. logger.info(`[Xiaohongshu API Direct] Total notes count from tags: ${totalNotesCount}`);
  1670. }
  1671. }
  1672. const notes = apiResponse.data.notes || [];
  1673. for (const note of notes) {
  1674. // 将 http:// 转换为 https://
  1675. let coverUrl = note.images_list?.[0]?.url || '';
  1676. if (coverUrl.startsWith('http://')) {
  1677. coverUrl = coverUrl.replace('http://', 'https://');
  1678. }
  1679. const duration = note.video_info?.duration || 0;
  1680. logger.info(`[Xiaohongshu API Direct] Note: id=${note.id}, cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
  1681. allNotesData.push({
  1682. noteId: note.id || '',
  1683. title: note.display_title || '',
  1684. coverUrl: coverUrl,
  1685. status: note.tab_status || 1,
  1686. publishTime: note.time || '',
  1687. type: note.type || 'normal',
  1688. duration: duration,
  1689. likeCount: note.likes || 0,
  1690. commentCount: note.comments_count || 0,
  1691. collectCount: note.collected_count || 0,
  1692. viewCount: note.view_count || 0,
  1693. shareCount: note.shared_count || 0,
  1694. });
  1695. }
  1696. // 获取更多页面
  1697. let pageNum = 1;
  1698. let lastPage = apiResponse.data.page;
  1699. while (lastPage !== -1 && pageNum < maxPages) {
  1700. const nextResponse = await page.evaluate(async (p) => {
  1701. const response = await fetch(`https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}`, {
  1702. method: 'GET',
  1703. credentials: 'include',
  1704. });
  1705. return await response.json();
  1706. }, pageNum);
  1707. if (nextResponse?.data?.notes?.length > 0) {
  1708. for (const note of nextResponse.data.notes) {
  1709. // 将 http:// 转换为 https://
  1710. let coverUrl = note.images_list?.[0]?.url || '';
  1711. if (coverUrl.startsWith('http://')) {
  1712. coverUrl = coverUrl.replace('http://', 'https://');
  1713. }
  1714. const duration = note.video_info?.duration || 0;
  1715. allNotesData.push({
  1716. noteId: note.id || '',
  1717. title: note.display_title || '',
  1718. coverUrl: coverUrl,
  1719. status: note.tab_status || 1,
  1720. publishTime: note.time || '',
  1721. type: note.type || 'normal',
  1722. duration: duration,
  1723. likeCount: note.likes || 0,
  1724. commentCount: note.comments_count || 0,
  1725. collectCount: note.collected_count || 0,
  1726. viewCount: note.view_count || 0,
  1727. shareCount: note.shared_count || 0,
  1728. });
  1729. }
  1730. pageNum++;
  1731. lastPage = nextResponse.data.page;
  1732. if (lastPage === -1) break;
  1733. } else {
  1734. break;
  1735. }
  1736. }
  1737. }
  1738. } catch (apiError) {
  1739. logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
  1740. }
  1741. }
  1742. // 如果还是没有数据,尝试滚动加载
  1743. if (allNotesData.length === 0) {
  1744. logger.info('[Xiaohongshu] Still no notes, trying scroll to trigger API...');
  1745. await page.waitForTimeout(2000);
  1746. }
  1747. // 滚动加载更多页面(如果通过监听器获取的数据)
  1748. while (hasMorePages && currentPage < maxPages && allNotesData.length > 0 && apiResponseReceived) {
  1749. currentPage++;
  1750. const previousCount = allNotesData.length;
  1751. // 滚动到页面底部触发加载更多
  1752. await page.evaluate(() => {
  1753. window.scrollTo(0, document.body.scrollHeight);
  1754. });
  1755. // 等待新数据加载
  1756. await page.waitForTimeout(2000);
  1757. // 如果没有新数据,退出循环
  1758. if (allNotesData.length === previousCount) {
  1759. logger.info(`[Xiaohongshu] No new notes loaded after scroll, stopping at page ${currentPage}`);
  1760. break;
  1761. }
  1762. logger.info(`[Xiaohongshu] Page ${currentPage}: total ${allNotesData.length} notes`);
  1763. }
  1764. // 移除监听器
  1765. page.off('response', notesApiHandler);
  1766. logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);
  1767. // 转换为 WorkItem 格式
  1768. for (const note of allNotesData) {
  1769. // 转换时长为 mm:ss 格式
  1770. const minutes = Math.floor(note.duration / 60);
  1771. const seconds = note.duration % 60;
  1772. const durationStr = note.duration > 0
  1773. ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  1774. : '';
  1775. // 转换状态
  1776. let statusStr = 'published';
  1777. if (note.status === 0) statusStr = 'draft';
  1778. else if (note.status === 2) statusStr = 'reviewing';
  1779. else if (note.status === 3) statusStr = 'rejected';
  1780. worksList.push({
  1781. videoId: note.noteId,
  1782. title: note.title || '无标题',
  1783. coverUrl: note.coverUrl,
  1784. duration: durationStr,
  1785. publishTime: note.publishTime,
  1786. status: statusStr,
  1787. playCount: note.viewCount,
  1788. likeCount: note.likeCount,
  1789. commentCount: note.commentCount,
  1790. shareCount: note.shareCount,
  1791. });
  1792. }
  1793. logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);
  1794. // 更新作品数:直接使用获取到的 notes 数量(更准确)
  1795. // 只有当 notes 为空时才使用 tags 中的 notes_count
  1796. if (worksList.length > 0) {
  1797. worksCount = worksList.length;
  1798. logger.info(`[Xiaohongshu] Using actual notes count: ${worksCount}`);
  1799. } else if (totalNotesCount > 0) {
  1800. worksCount = totalNotesCount;
  1801. logger.info(`[Xiaohongshu] Using notes count from tags: ${worksCount}`);
  1802. }
  1803. } catch (worksError) {
  1804. logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
  1805. }
  1806. logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
  1807. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  1808. } catch (error) {
  1809. logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
  1810. }
  1811. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1812. }
  1813. /**
  1814. * 解析中文数字(如 1.2万 -> 12000)
  1815. */
  1816. private parseChineseNumber(str: string): number {
  1817. if (!str) return 0;
  1818. let num = parseFloat(str);
  1819. if (str.includes('万')) {
  1820. num *= 10000;
  1821. } else if (str.includes('亿')) {
  1822. num *= 100000000;
  1823. }
  1824. return Math.floor(num);
  1825. }
  1826. /**
  1827. * 获取平台配置
  1828. */
  1829. private getPlatformConfig(platform: PlatformType) {
  1830. const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
  1831. douyin: {
  1832. homeUrl: 'https://creator.douyin.com/creator-micro/home',
  1833. loginIndicators: ['login', 'passport', 'sso'],
  1834. },
  1835. bilibili: {
  1836. homeUrl: 'https://member.bilibili.com/platform/home',
  1837. loginIndicators: ['passport.bilibili.com', 'login'],
  1838. },
  1839. kuaishou: {
  1840. homeUrl: 'https://cp.kuaishou.com/profile',
  1841. loginIndicators: ['passport.kuaishou.com', 'login'],
  1842. },
  1843. xiaohongshu: {
  1844. homeUrl: 'https://creator.xiaohongshu.com/',
  1845. loginIndicators: ['login', 'passport'],
  1846. },
  1847. weixin_video: {
  1848. homeUrl: 'https://channels.weixin.qq.com/platform',
  1849. loginIndicators: ['login', 'passport'],
  1850. },
  1851. baijiahao: {
  1852. homeUrl: 'https://baijiahao.baidu.com/builder/rc/home',
  1853. loginIndicators: ['login', 'passport'],
  1854. },
  1855. toutiao: {
  1856. homeUrl: 'https://mp.toutiao.com/profile_v4/index',
  1857. loginIndicators: ['login', 'passport', 'sso'],
  1858. },
  1859. weibo: {
  1860. homeUrl: 'https://weibo.com/u/',
  1861. loginIndicators: ['login', 'passport'],
  1862. },
  1863. dayu: {
  1864. homeUrl: 'https://mp.dayu.com/',
  1865. loginIndicators: ['login', 'passport'],
  1866. },
  1867. };
  1868. return configs[platform] || { homeUrl: '', loginIndicators: ['login'] };
  1869. }
  1870. /**
  1871. * 百家号 - 直接通过 API 获取账号信息和作品列表
  1872. */
  1873. private async fetchBaijiahaoAccountInfoDirectApi(cookies: CookieData[]): Promise<AccountInfo> {
  1874. logger.info(`[Baijiahao API] Fetching account info via direct API...`);
  1875. // 构建 Cookie 字符串,确保格式正确
  1876. const cookieString = cookies
  1877. .map(c => `${c.name.trim()}=${c.value.trim()}`)
  1878. .filter(c => c.includes('=')) // 过滤掉无效的 cookie
  1879. .join('; ');
  1880. logger.debug(`[Baijiahao API] Cookie string length: ${cookieString.length}, cookie count: ${cookies.length}`);
  1881. const headers: Record<string, string> = {
  1882. 'Accept': '*/*',
  1883. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  1884. 'Accept-Encoding': 'gzip, deflate, br',
  1885. 'Connection': 'keep-alive',
  1886. 'Cookie': cookieString,
  1887. // 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
  1888. // 'Origin': 'https://baijiahao.baidu.com',
  1889. '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',
  1890. // 'Sec-Fetch-Dest': 'empty',
  1891. // 'Sec-Fetch-Mode': 'cors',
  1892. // 'Sec-Fetch-Site': 'same-origin',
  1893. };
  1894. let accountInfo: AccountInfo = this.getDefaultAccountInfo('baijiahao');
  1895. // 标记哪些字段已成功获取
  1896. let fansCountFetched = false;
  1897. let worksCountFetched = false;
  1898. try {
  1899. // 1. 获取账号基本信息 (appinfo API)
  1900. logger.info(`[Baijiahao API] Step 1: Fetching appinfo...`);
  1901. const appInfoResponse = await fetch('https://baijiahao.baidu.com/builder/app/appinfo', {
  1902. method: 'GET',
  1903. headers,
  1904. });
  1905. if (!appInfoResponse.ok) {
  1906. logger.error(`[Baijiahao API] appinfo request failed: ${appInfoResponse.status}`);
  1907. throw new Error(`appinfo request failed: ${appInfoResponse.status}`);
  1908. }
  1909. const appInfoData = await appInfoResponse.json() as {
  1910. errno?: number;
  1911. errmsg?: string;
  1912. data?: {
  1913. user?: {
  1914. name?: string;
  1915. avatar?: string;
  1916. app_id?: string | number;
  1917. userid?: number;
  1918. status?: string;
  1919. };
  1920. };
  1921. };
  1922. logger.info(`[Baijiahao API] appinfo response: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
  1923. if (appInfoData.errno !== 0) {
  1924. logger.error(`[Baijiahao API] appinfo API error: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
  1925. throw new Error(`appinfo API error: ${appInfoData.errmsg || 'Unknown error'}`);
  1926. }
  1927. if (!appInfoData.data?.user) {
  1928. logger.error(`[Baijiahao API] No user data in appinfo response`);
  1929. throw new Error('No user data in appinfo response');
  1930. }
  1931. const user = appInfoData.data.user;
  1932. accountInfo.accountId = user.app_id ? `bjh_${user.app_id}` : accountInfo.accountId;
  1933. accountInfo.accountName = user.name || accountInfo.accountName;
  1934. // 处理头像 URL(可能是相对路径)
  1935. if (user.avatar) {
  1936. accountInfo.avatarUrl = user.avatar.startsWith('http')
  1937. ? user.avatar
  1938. : `https:${user.avatar}`;
  1939. }
  1940. logger.info(`[Baijiahao API] Got account info: name=${accountInfo.accountName}, id=${accountInfo.accountId}, avatar=${accountInfo.avatarUrl}`);
  1941. // 2. 获取粉丝数 (growthInfo API)
  1942. logger.info(`[Baijiahao API] Step 2: Fetching growth info...`);
  1943. try {
  1944. const growthInfoResponse = await fetch('https://baijiahao.baidu.com/cms-ui/rights/growth/get_info', {
  1945. method: 'GET',
  1946. headers,
  1947. });
  1948. if (growthInfoResponse.ok) {
  1949. const growthData = await growthInfoResponse.json() as {
  1950. errno?: number;
  1951. errmsg?: string;
  1952. data?: {
  1953. total_fans?: number;
  1954. };
  1955. };
  1956. logger.info(`[Baijiahao API] growth info response: errno=${growthData.errno}`);
  1957. if (growthData.errno === 0 && growthData.data) {
  1958. const fansCount = growthData.data.total_fans;
  1959. if (fansCount !== undefined && fansCount !== null) {
  1960. accountInfo.fansCount = fansCount;
  1961. fansCountFetched = true;
  1962. logger.info(`[Baijiahao API] Got fans count: ${accountInfo.fansCount}`);
  1963. } else {
  1964. logger.warn(`[Baijiahao API] growth info API returned no fans count`);
  1965. }
  1966. } else {
  1967. logger.warn(`[Baijiahao API] growth info API error: errno=${growthData.errno}, errmsg=${growthData.errmsg}`);
  1968. }
  1969. } else {
  1970. logger.warn(`[Baijiahao API] growth info request failed: ${growthInfoResponse.status}`);
  1971. }
  1972. } catch (growthError) {
  1973. logger.warn(`[Baijiahao API] Failed to fetch growth info (non-critical):`, growthError);
  1974. // 粉丝数获取失败不影响整体流程
  1975. }
  1976. // 3. 获取作品列表 (分页获取所有作品)
  1977. logger.info(`[Baijiahao API] Step 3: Fetching works list...`);
  1978. setTimeout(() => {
  1979. console.log('1000ms');
  1980. }, 1000);
  1981. const worksList: WorkItem[] = [];
  1982. let currentPage = 1;
  1983. const pageSize = 20;
  1984. let hasMore = true;
  1985. let totalWorks = 0;
  1986. let worksListError = false;
  1987. while (hasMore && !worksListError) {
  1988. try {
  1989. const listUrl = `https://baijiahao.baidu.com/pcui/article/lists?currentPage=${currentPage}&pageSize=${pageSize}&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0`;
  1990. logger.info(`[Baijiahao API] Fetching works page ${currentPage}...`);
  1991. logger.debug(`[Baijiahao API] Request headers include Cookie: ${!!headers.Cookie}, Cookie length: ${headers.Cookie?.length || 0}`);
  1992. const listResponse = await fetch(listUrl, {
  1993. method: 'GET',
  1994. headers,
  1995. });
  1996. if (!listResponse.ok) {
  1997. const errorText = await listResponse.text();
  1998. logger.warn(`[Baijiahao API] Failed to fetch works list page ${currentPage}: ${listResponse.status}`);
  1999. logger.warn(`[Baijiahao API] Error response body: ${errorText}`);
  2000. break;
  2001. }
  2002. const responseText = await listResponse.text();
  2003. logger.info(`[Baijiahao API] ========== Works API Response (Page ${currentPage}) ==========`);
  2004. logger.info(`[Baijiahao API] Full response: ${responseText}`);
  2005. logger.info(`[Baijiahao API] ============================================================`);
  2006. const listData = JSON.parse(responseText) as {
  2007. errno?: number;
  2008. errmsg?: string;
  2009. data?: {
  2010. list?: Array<{
  2011. id?: string;
  2012. article_id?: string;
  2013. title?: string;
  2014. cover_images?: string | string[];
  2015. created_at?: string;
  2016. create_time?: string;
  2017. status?: string;
  2018. read_amount?: number;
  2019. read_count?: number;
  2020. like_amount?: number;
  2021. like_count?: number;
  2022. comment_amount?: number;
  2023. comment_count?: number;
  2024. share_amount?: number;
  2025. share_count?: number;
  2026. }>;
  2027. page?: {
  2028. currentPage?: number;
  2029. pageSize?: number;
  2030. totalCount?: number;
  2031. totalPage?: number;
  2032. };
  2033. total?: number; // 兼容旧格式
  2034. };
  2035. };
  2036. // 处理分散认证问题 (errno=10001402),重试一次
  2037. if (listData.errno === 10001402) {
  2038. logger.warn(`[Baijiahao API] Dispersed authentication issue (errno=10001402) on page ${currentPage}, retrying after 3 seconds...`);
  2039. logger.debug(`[Baijiahao API] Request URL: ${listUrl}`);
  2040. logger.debug(`[Baijiahao API] Cookie header present: ${!!headers.Cookie}, length: ${headers.Cookie?.length || 0}`);
  2041. await new Promise(resolve => setTimeout(resolve, 3000));
  2042. // 重试一次,确保 headers 包含 Cookie
  2043. const retryResponse = await fetch(listUrl, {
  2044. method: 'GET',
  2045. headers: {
  2046. ...headers,
  2047. 'Cookie': cookieString, // 确保 Cookie 被正确传递
  2048. },
  2049. });
  2050. if (retryResponse.ok) {
  2051. const retryResponseText = await retryResponse.text();
  2052. logger.info(`[Baijiahao API] ========== Works API Retry Response (Page ${currentPage}) ==========`);
  2053. logger.info(`[Baijiahao API] Full retry response: ${retryResponseText}`);
  2054. logger.info(`[Baijiahao API] ============================================================`);
  2055. const retryData = JSON.parse(retryResponseText) as typeof listData;
  2056. if (retryData.errno === 0) {
  2057. logger.info(`[Baijiahao API] Retry successful for page ${currentPage}`);
  2058. Object.assign(listData, retryData);
  2059. } else if (retryData.errno === 10001402) {
  2060. logger.error(`[Baijiahao API] Retry still failed with errno=10001402, cookie may be invalid or expired`);
  2061. logger.error(`[Baijiahao API] Retry response data: ${JSON.stringify(retryData, null, 2)}`);
  2062. // 如果重试仍然失败,可能是 Cookie 问题,记录详细信息
  2063. logger.error(`[Baijiahao API] Cookie info: ${cookieString.substring(0, 200)}...`);
  2064. // 标记错误,但不完全失败,继续返回已获取的账号信息
  2065. worksListError = true;
  2066. logger.warn(`[Baijiahao API] Works list fetch failed, but will return other account info (name, fans count)`);
  2067. break;
  2068. } else {
  2069. logger.warn(`[Baijiahao API] Retry still failed: errno=${retryData.errno}, errmsg=${retryData.errmsg}`);
  2070. break;
  2071. }
  2072. } else {
  2073. logger.warn(`[Baijiahao API] Retry request failed: ${retryResponse.status}`);
  2074. break;
  2075. }
  2076. }
  2077. if (listData.errno !== 0) {
  2078. logger.warn(`[Baijiahao API] API returned error on page ${currentPage}: errno=${listData.errno}, errmsg=${listData.errmsg}`);
  2079. logger.warn(`[Baijiahao API] Error response data: ${JSON.stringify(listData, null, 2)}`);
  2080. // 如果不是 10001402 错误,标记为错误但继续返回其他信息
  2081. if (listData.errno !== 10001402) {
  2082. worksListError = true;
  2083. logger.warn(`[Baijiahao API] Works list fetch failed with errno=${listData.errno}, but will return other account info`);
  2084. }
  2085. break;
  2086. }
  2087. const list = listData.data?.list || [];
  2088. // 优先使用 data.page.totalCount,如果没有则使用 data.total(兼容旧格式)
  2089. totalWorks = listData.data?.page?.totalCount || listData.data?.total || 0;
  2090. logger.info(`[Baijiahao API] Got ${list.length} works on page ${currentPage}, total: ${totalWorks}`);
  2091. for (const item of list) {
  2092. // 处理 cover_images 可能是字符串(JSON)或数组
  2093. let coverUrl = '';
  2094. if (item.cover_images) {
  2095. if (Array.isArray(item.cover_images)) {
  2096. coverUrl = item.cover_images[0] || '';
  2097. } else if (typeof item.cover_images === 'string') {
  2098. try {
  2099. const coverArray = JSON.parse(item.cover_images);
  2100. if (Array.isArray(coverArray) && coverArray.length > 0) {
  2101. coverUrl = typeof coverArray[0] === 'string' ? coverArray[0] : coverArray[0]?.src || coverArray[0]?.ori_src || '';
  2102. }
  2103. } catch {
  2104. coverUrl = item.cover_images;
  2105. }
  2106. }
  2107. }
  2108. worksList.push({
  2109. videoId: item.id || item.article_id || `bjh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
  2110. title: item.title || '',
  2111. coverUrl: coverUrl,
  2112. duration: '00:00',
  2113. publishTime: item.created_at || item.create_time || new Date().toISOString(),
  2114. status: item.status || 'published',
  2115. playCount: item.read_amount || item.read_count || 0,
  2116. likeCount: item.like_amount || item.like_count || 0,
  2117. commentCount: item.comment_amount || item.comment_count || 0,
  2118. shareCount: item.share_amount || item.share_count || 0,
  2119. });
  2120. }
  2121. // 检查是否还有更多
  2122. if (list.length < pageSize) {
  2123. hasMore = false;
  2124. logger.info(`[Baijiahao API] No more works, stopping at page ${currentPage}`);
  2125. } else {
  2126. currentPage++;
  2127. // 防止无限循环,最多获取 10 页(200 个作品)
  2128. if (currentPage > 10) {
  2129. logger.warn(`[Baijiahao API] Reached max pages (10), stopping. Total fetched: ${worksList.length}, API total: ${totalWorks}`);
  2130. hasMore = false;
  2131. }
  2132. }
  2133. } catch (pageError) {
  2134. logger.error(`[Baijiahao API] Error fetching page ${currentPage}:`, pageError);
  2135. break;
  2136. }
  2137. }
  2138. accountInfo.worksList = worksList;
  2139. // 使用 API 返回的 total 字段作为作品总数,而不是已获取的作品列表长度
  2140. // 因为可能只获取了部分作品(最多 10 页),但 total 是真实的总数
  2141. if (totalWorks > 0) {
  2142. accountInfo.worksCount = totalWorks;
  2143. worksCountFetched = true;
  2144. } else if (worksList.length > 0) {
  2145. // 如果 API 没有返回 total,但获取到了作品列表,使用列表长度
  2146. accountInfo.worksCount = worksList.length;
  2147. worksCountFetched = true;
  2148. }
  2149. if (worksListError) {
  2150. logger.warn(`[Baijiahao API] Works list fetch encountered errors, but returning partial account info`);
  2151. logger.info(`[Baijiahao API] Account info (partial): name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched})`);
  2152. } else {
  2153. logger.info(`[Baijiahao API] Successfully fetched account info: name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched}, API total: ${totalWorks}, fetched list: ${worksList.length})`);
  2154. }
  2155. return accountInfo;
  2156. } catch (error) {
  2157. logger.error(`[Baijiahao API] Failed to fetch account info:`, error);
  2158. // 返回默认信息,但保留已获取的部分数据
  2159. return accountInfo;
  2160. }
  2161. }
  2162. /**
  2163. * 通过 Python API 获取账号信息
  2164. */
  2165. private async fetchAccountInfoViaPython(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
  2166. logger.info(`[Python API] Fetching account info for ${platform}...`);
  2167. try {
  2168. // 检查 Python 服务是否可用
  2169. const pythonAvailable = await this.checkPythonServiceAvailable();
  2170. if (!pythonAvailable) {
  2171. logger.warn(`[Python API] Service not available, returning default info`);
  2172. return this.getDefaultAccountInfo(platform);
  2173. }
  2174. // 构建 Cookie 字符串
  2175. const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
  2176. // 调用 Python API
  2177. const response = await fetch(`${PYTHON_SERVICE_URL}/account_info`, {
  2178. method: 'POST',
  2179. headers: {
  2180. 'Content-Type': 'application/json',
  2181. },
  2182. body: JSON.stringify({
  2183. platform,
  2184. cookie: cookieString,
  2185. }),
  2186. });
  2187. if (!response.ok) {
  2188. logger.warn(`[Python API] account_info returned ${response.status}`);
  2189. return this.getDefaultAccountInfo(platform);
  2190. }
  2191. const result = await response.json() as {
  2192. success: boolean;
  2193. account_id?: string;
  2194. account_name?: string;
  2195. avatar_url?: string;
  2196. fans_count?: number;
  2197. works_count?: number;
  2198. error?: string;
  2199. need_login?: boolean;
  2200. };
  2201. logger.info(`[Python API] account_info result: success=${result.success}, name=${result.account_name}`);
  2202. if (result.success && result.account_name) {
  2203. return {
  2204. accountId: result.account_id || `${platform}_${Date.now()}`,
  2205. accountName: result.account_name,
  2206. avatarUrl: result.avatar_url || '',
  2207. fansCount: result.fans_count || 0,
  2208. worksCount: result.works_count || 0,
  2209. };
  2210. }
  2211. if (result.need_login) {
  2212. logger.warn(`[Python API] Account needs re-login`);
  2213. }
  2214. logger.warn(`[Python API] Failed to get account info: ${result.error}`);
  2215. return this.getDefaultAccountInfo(platform);
  2216. } catch (error) {
  2217. logger.error(`[Python API] Failed to fetch account info for ${platform}:`, error);
  2218. return this.getDefaultAccountInfo(platform);
  2219. }
  2220. }
  2221. /**
  2222. * 获取默认账号信息
  2223. */
  2224. private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
  2225. // 平台友好名称映射
  2226. const platformNames: Record<string, string> = {
  2227. douyin: '抖音',
  2228. xiaohongshu: '小红书',
  2229. kuaishou: '快手',
  2230. weixin_video: '视频号',
  2231. bilibili: 'B站',
  2232. toutiao: '头条',
  2233. baijiahao: '百家号',
  2234. };
  2235. const name = platformNames[platform] || platform;
  2236. return {
  2237. accountId: `${platform}_${Date.now()}`,
  2238. accountName: `${name}账号`,
  2239. avatarUrl: '',
  2240. fansCount: 0,
  2241. worksCount: 0,
  2242. };
  2243. }
  2244. /**
  2245. * 获取抖音评论 - 逐个选择作品获取评论
  2246. */
  2247. async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
  2248. const browser = await chromium.launch({
  2249. headless: true,
  2250. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  2251. });
  2252. const allWorkComments: WorkComments[] = [];
  2253. try {
  2254. const context = await browser.newContext({
  2255. viewport: { width: 1920, height: 1080 },
  2256. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2257. });
  2258. // 设置 Cookie
  2259. const playwrightCookies = cookies.map(c => ({
  2260. name: c.name,
  2261. value: c.value,
  2262. domain: c.domain || '.douyin.com',
  2263. path: c.path || '/',
  2264. }));
  2265. await context.addCookies(playwrightCookies);
  2266. const page = await context.newPage();
  2267. // 导航到评论管理页面
  2268. logger.info('Navigating to Douyin comment management page...');
  2269. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  2270. waitUntil: 'domcontentloaded',
  2271. timeout: 30000,
  2272. });
  2273. await page.waitForTimeout(3000);
  2274. // 点击"选择作品"按钮
  2275. logger.info('Looking for "选择作品" button...');
  2276. const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');
  2277. if (selectWorkBtn) {
  2278. await selectWorkBtn.click();
  2279. await page.waitForTimeout(2000);
  2280. logger.info('Clicked "选择作品" button');
  2281. } else {
  2282. // 如果没有选择作品按钮,可能已经有作品被选中,直接获取当前评论
  2283. logger.info('No "选择作品" button found, fetching current comments...');
  2284. const currentComments = await this.extractCommentsFromPage(page);
  2285. if (currentComments.length > 0) {
  2286. allWorkComments.push({
  2287. videoId: 'current',
  2288. videoTitle: '当前作品',
  2289. videoCoverUrl: '',
  2290. comments: currentComments,
  2291. });
  2292. }
  2293. await page.close();
  2294. await context.close();
  2295. await browser.close();
  2296. return allWorkComments;
  2297. }
  2298. // 获取作品列表
  2299. const worksList = await page.evaluate(() => {
  2300. const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];
  2301. // 查找作品列表容器(弹窗中的作品选择列表)
  2302. const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');
  2303. workItems.forEach((item, index) => {
  2304. const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
  2305. const coverEl = item.querySelector('img, [class*="cover"]');
  2306. const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
  2307. let coverUrl = '';
  2308. if (coverEl) {
  2309. coverUrl = (coverEl as HTMLImageElement).src ||
  2310. coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
  2311. }
  2312. // 获取 video ID(从数据属性或其他方式)
  2313. const videoId = item.getAttribute('data-video-id') ||
  2314. item.getAttribute('data-id') ||
  2315. `video_${index}`;
  2316. works.push({ videoId, title, coverUrl });
  2317. });
  2318. return works;
  2319. });
  2320. logger.info(`Found ${worksList.length} works in the selector`);
  2321. // 如果有作品列表,逐个选择并获取评论
  2322. if (worksList.length > 0) {
  2323. for (let i = 0; i < worksList.length; i++) {
  2324. try {
  2325. logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);
  2326. // 点击选择该作品
  2327. const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
  2328. if (workItem) {
  2329. await workItem.click();
  2330. await page.waitForTimeout(2000);
  2331. // 点击确认按钮(如果有)
  2332. const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
  2333. if (confirmBtn) {
  2334. await confirmBtn.click();
  2335. await page.waitForTimeout(2000);
  2336. }
  2337. }
  2338. // 等待评论加载
  2339. await page.waitForTimeout(2000);
  2340. // 提取评论
  2341. const comments = await this.extractCommentsFromPage(page);
  2342. if (comments.length > 0) {
  2343. allWorkComments.push({
  2344. videoId: worksList[i].videoId,
  2345. videoTitle: worksList[i].title,
  2346. videoCoverUrl: worksList[i].coverUrl,
  2347. comments,
  2348. });
  2349. logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
  2350. }
  2351. // 重新打开选择作品弹窗(如果需要继续选择其他作品)
  2352. if (i < worksList.length - 1) {
  2353. const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
  2354. if (selectBtn) {
  2355. await selectBtn.click();
  2356. await page.waitForTimeout(2000);
  2357. }
  2358. }
  2359. } catch (workError) {
  2360. logger.warn(`Failed to process work ${i + 1}:`, workError);
  2361. }
  2362. }
  2363. } else {
  2364. // 没有找到作品列表,尝试直接从页面获取评论
  2365. const comments = await this.extractCommentsFromPage(page);
  2366. if (comments.length > 0) {
  2367. // 获取当前显示的作品信息
  2368. const currentWork = await page.evaluate(() => {
  2369. const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
  2370. const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');
  2371. return {
  2372. title: titleEl?.textContent?.trim() || '当前作品',
  2373. coverUrl: (coverEl as HTMLImageElement)?.src || '',
  2374. };
  2375. });
  2376. allWorkComments.push({
  2377. videoId: 'current',
  2378. videoTitle: currentWork.title,
  2379. videoCoverUrl: currentWork.coverUrl,
  2380. comments,
  2381. });
  2382. }
  2383. }
  2384. await page.close();
  2385. await context.close();
  2386. await browser.close();
  2387. logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
  2388. return allWorkComments;
  2389. } catch (error) {
  2390. logger.error('Error fetching Douyin comments:', error);
  2391. await browser.close();
  2392. return allWorkComments;
  2393. }
  2394. }
  2395. /**
  2396. * 从页面提取评论列表
  2397. * 使用抖音创作者中心的精确选择器
  2398. * 根据实际 HTML 结构:
  2399. * - 评论容器: container-sXKyMs (或类似 container-xxx)
  2400. * - 用户名: username-aLgaNB (或类似 username-xxx)
  2401. * - 时间: time-NRtTXO (或类似 time-xxx)
  2402. * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
  2403. * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
  2404. */
  2405. private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
  2406. return page.evaluate(() => {
  2407. const comments: Array<{
  2408. commentId: string;
  2409. authorId: string;
  2410. authorName: string;
  2411. authorAvatar: string;
  2412. content: string;
  2413. likeCount: number;
  2414. commentTime: string;
  2415. }> = [];
  2416. const seenContents = new Set<string>();
  2417. // 方法1: 直接查找所有评论容器 (container-xxx 类名)
  2418. // 评论容器通常包含 checkbox、avatar、content 等子元素
  2419. const allContainers = document.querySelectorAll('[class*="container-"]');
  2420. const commentContainers: Element[] = [];
  2421. allContainers.forEach(container => {
  2422. // 检查是否是评论容器:包含用户名和评论内容
  2423. const hasUsername = container.querySelector('[class*="username-"]');
  2424. const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
  2425. if (hasUsername && hasCommentContent) {
  2426. commentContainers.push(container);
  2427. }
  2428. });
  2429. console.log(`Found ${commentContainers.length} comment containers`);
  2430. // 如果方法1没找到,尝试方法2:通过评论内容元素向上查找
  2431. if (commentContainers.length === 0) {
  2432. const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
  2433. console.log(`Found ${contentElements.length} content elements, searching parents...`);
  2434. contentElements.forEach(contentEl => {
  2435. let parent = contentEl.parentElement;
  2436. // 向上查找最多 10 层
  2437. for (let i = 0; i < 10 && parent; i++) {
  2438. const className = parent.className || '';
  2439. // 查找包含 container- 的父元素
  2440. if (className.includes('container-')) {
  2441. if (!commentContainers.includes(parent)) {
  2442. commentContainers.push(parent);
  2443. }
  2444. break;
  2445. }
  2446. parent = parent.parentElement;
  2447. }
  2448. });
  2449. }
  2450. console.log(`Total comment containers: ${commentContainers.length}`);
  2451. commentContainers.forEach((container, index) => {
  2452. try {
  2453. // 提取用户名 - 使用 username-xxx 选择器
  2454. let authorName = '';
  2455. const usernameEl = container.querySelector('[class*="username-"]');
  2456. if (usernameEl && usernameEl.textContent) {
  2457. authorName = usernameEl.textContent.trim();
  2458. }
  2459. if (!authorName) authorName = '未知用户';
  2460. // 提取头像 - 从 avatar-xxx 容器内的 img 提取
  2461. let authorAvatar = '';
  2462. const avatarContainer = container.querySelector('[class*="avatar-"]');
  2463. if (avatarContainer) {
  2464. const avatarImg = avatarContainer.querySelector('img');
  2465. if (avatarImg) {
  2466. authorAvatar = avatarImg.src || '';
  2467. }
  2468. }
  2469. // 提取时间 - 使用 time-xxx 选择器
  2470. let commentTime = '';
  2471. const timeEl = container.querySelector('[class*="time-"]');
  2472. if (timeEl && timeEl.textContent) {
  2473. commentTime = timeEl.textContent.trim();
  2474. }
  2475. // 提取评论内容 - 使用 comment-content-text-xxx 选择器
  2476. let content = '';
  2477. const contentEl = container.querySelector('[class*="comment-content-text-"]');
  2478. if (contentEl && contentEl.textContent) {
  2479. content = contentEl.textContent.trim();
  2480. }
  2481. // 跳过空内容
  2482. if (!content || content.length < 1) {
  2483. console.log(`[${index}] Skipping empty content`);
  2484. return;
  2485. }
  2486. // 去重 (基于用户名+内容)
  2487. const contentKey = `${authorName}||${content}`;
  2488. if (seenContents.has(contentKey)) {
  2489. console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
  2490. return;
  2491. }
  2492. seenContents.add(contentKey);
  2493. // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
  2494. let likeCount = 0;
  2495. const operationsEl = container.querySelector('[class*="operations-"]');
  2496. if (operationsEl) {
  2497. // 查找第一个 item-xxx,通常是点赞数
  2498. const firstItem = operationsEl.querySelector('[class*="item-"]');
  2499. if (firstItem) {
  2500. const text = firstItem.textContent || '';
  2501. const match = text.match(/(\d+)/);
  2502. if (match) {
  2503. likeCount = parseInt(match[1], 10);
  2504. }
  2505. }
  2506. }
  2507. // 生成唯一 ID
  2508. const contentHash = content.slice(0, 30) + authorName + commentTime;
  2509. const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;
  2510. comments.push({
  2511. commentId,
  2512. authorId: authorName,
  2513. authorName,
  2514. authorAvatar,
  2515. content,
  2516. likeCount,
  2517. commentTime,
  2518. });
  2519. console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
  2520. } catch (err) {
  2521. console.error(`[${index}] Error extracting comment:`, err);
  2522. }
  2523. });
  2524. console.log(`Successfully extracted ${comments.length} comments`);
  2525. return comments;
  2526. });
  2527. }
  2528. /**
  2529. * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
  2530. * 使用无头浏览器,通过拦截网络请求直接获取 API 数据
  2531. * 更稳定、更高效
  2532. */
  2533. async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
  2534. const browser = await chromium.launch({
  2535. headless: true, // 无头模式
  2536. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  2537. });
  2538. const allWorkComments: WorkComments[] = [];
  2539. // 存储捕获的 API 数据
  2540. const capturedWorks: Array<{
  2541. awemeId: string;
  2542. title: string;
  2543. coverUrl: string;
  2544. commentCount: number;
  2545. }> = [];
  2546. const capturedComments: Map<string, CommentItem[]> = new Map();
  2547. try {
  2548. const context = await browser.newContext({
  2549. viewport: { width: 1920, height: 1080 },
  2550. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2551. });
  2552. // 设置 Cookie
  2553. const playwrightCookies = cookies.map(c => ({
  2554. name: c.name,
  2555. value: c.value,
  2556. domain: c.domain || '.douyin.com',
  2557. path: c.path || '/',
  2558. }));
  2559. await context.addCookies(playwrightCookies);
  2560. logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);
  2561. const page = await context.newPage();
  2562. // 监听网络响应
  2563. page.on('response', async (response) => {
  2564. const url = response.url();
  2565. try {
  2566. // 监听作品列表 API - 支持新旧两种接口
  2567. // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
  2568. // 旧接口: /creator/item/list (item_info_list 字段)
  2569. if (url.includes('/work_list') || url.includes('/creator/item/list')) {
  2570. const data = await response.json();
  2571. // 新接口: aweme_list
  2572. if (data?.aweme_list && data.aweme_list.length > 0) {
  2573. for (const aweme of data.aweme_list) {
  2574. const awemeId = String(aweme.aweme_id || '');
  2575. if (!awemeId) continue;
  2576. const statistics = aweme.statistics || {};
  2577. const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
  2578. let title = aweme.item_title || '';
  2579. if (!title) {
  2580. const desc = aweme.desc || aweme.caption || '';
  2581. title = desc.split('\n')[0].slice(0, 50) || '无标题';
  2582. }
  2583. let coverUrl = '';
  2584. if (aweme.Cover?.url_list?.length > 0) {
  2585. coverUrl = aweme.Cover.url_list[0];
  2586. } else if (aweme.video?.cover?.url_list?.length > 0) {
  2587. coverUrl = aweme.video.cover.url_list[0];
  2588. }
  2589. capturedWorks.push({
  2590. awemeId,
  2591. title,
  2592. coverUrl,
  2593. commentCount,
  2594. });
  2595. }
  2596. logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
  2597. }
  2598. // 旧接口: item_info_list
  2599. const itemList = data?.item_info_list || data?.item_list || [];
  2600. if (itemList.length > 0) {
  2601. for (const item of itemList) {
  2602. capturedWorks.push({
  2603. awemeId: item.item_id_plain || item.aweme_id || '',
  2604. title: item.title || '无标题',
  2605. coverUrl: item.cover_image_url || '',
  2606. commentCount: item.comment_count || 0,
  2607. });
  2608. }
  2609. logger.info(`[API] Captured ${itemList.length} works from item/list API`);
  2610. }
  2611. }
  2612. // 监听评论列表 API(两种格式)
  2613. // 格式1: /comment/list/select/ - 初始加载,返回 { comments: [...] }
  2614. // 格式2: /creator/comment/list/ - 切换作品后,返回 { comment_info_list: [...] }
  2615. if (url.includes('/comment/list') || url.includes('/comment/read')) {
  2616. const data = await response.json();
  2617. // 从 URL 中提取 aweme_id
  2618. const awemeIdMatch = url.match(/aweme_id=(\d+)/);
  2619. const awemeId = awemeIdMatch?.[1] || '';
  2620. let comments: CommentItem[] = [];
  2621. // 格式1: 初始加载的评论 API (comment/list/select)
  2622. if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
  2623. comments = data.comments.map((c: Record<string, unknown>) => {
  2624. const user = c.user as Record<string, unknown> | undefined;
  2625. const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
  2626. const avatarUrls = avatarThumb?.url_list as string[] | undefined;
  2627. return {
  2628. commentId: String(c.cid || ''),
  2629. authorId: String(user?.uid || ''),
  2630. authorName: String(user?.nickname || '匿名'),
  2631. authorAvatar: avatarUrls?.[0] || '',
  2632. content: String(c.text || ''),
  2633. likeCount: Number(c.digg_count || 0),
  2634. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2635. videoId: String(c.aweme_id || awemeId),
  2636. };
  2637. });
  2638. logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
  2639. }
  2640. // 格式2: 切换作品后的评论 API (creator/comment/list)
  2641. if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
  2642. comments = data.comment_info_list.map((c: Record<string, unknown>) => {
  2643. const userInfo = c.user_info as Record<string, unknown> | undefined;
  2644. return {
  2645. commentId: String(c.comment_id || ''),
  2646. authorId: String(userInfo?.user_id || ''),
  2647. authorName: String(userInfo?.screen_name || '匿名'),
  2648. authorAvatar: String(userInfo?.avatar_url || ''),
  2649. content: String(c.text || ''),
  2650. likeCount: Number(c.digg_count || 0),
  2651. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2652. videoId: awemeId, // 这种格式没有直接返回 aweme_id
  2653. };
  2654. });
  2655. logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
  2656. }
  2657. if (comments.length > 0) {
  2658. const videoId = comments[0]?.videoId || awemeId;
  2659. if (videoId) {
  2660. const existing = capturedComments.get(videoId) || [];
  2661. capturedComments.set(videoId, [...existing, ...comments]);
  2662. logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
  2663. }
  2664. }
  2665. }
  2666. } catch {
  2667. // 忽略非 JSON 响应
  2668. }
  2669. });
  2670. // 导航到创作者中心页面(设置好 Cookie 后)
  2671. logger.info('[API Interception] Navigating to creator page...');
  2672. await page.goto('https://creator.douyin.com/creator-micro/home', {
  2673. waitUntil: 'domcontentloaded',
  2674. timeout: 60000,
  2675. });
  2676. // 等待页面加载
  2677. await page.waitForTimeout(3000);
  2678. // 检查是否需要登录
  2679. const currentUrl = page.url();
  2680. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  2681. logger.warn('[API Interception] Cookie expired');
  2682. return [];
  2683. }
  2684. // 方式1:直接调用 API 获取作品列表(优先)
  2685. logger.info('[API Interception] Fetching works via direct API...');
  2686. let works = await this.fetchWorksDirectApi(page);
  2687. // 方式2:如果直接调用失败,尝试通过页面触发 API
  2688. if (works.length === 0) {
  2689. logger.info('[API Interception] Direct API failed, trying page navigation...');
  2690. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  2691. waitUntil: 'networkidle',
  2692. timeout: 60000,
  2693. });
  2694. await page.waitForTimeout(3000);
  2695. // 点击"选择作品"按钮触发作品列表 API
  2696. const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
  2697. if (selectBtn) {
  2698. await selectBtn.click();
  2699. await page.waitForTimeout(3000);
  2700. }
  2701. // 使用监听到的数据
  2702. works = capturedWorks;
  2703. }
  2704. logger.info(`[API Interception] Total works: ${works.length}`);
  2705. // 获取有评论的作品
  2706. const worksWithComments = works.filter(w => w.commentCount > 0);
  2707. logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);
  2708. // 如果有评论的作品,需要导航到评论管理页面并逐个切换获取
  2709. if (worksWithComments.length > 0) {
  2710. // 先尝试直接调用 API 获取评论
  2711. for (const work of worksWithComments) {
  2712. logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);
  2713. let comments = capturedComments.get(work.awemeId) || [];
  2714. if (comments.length === 0) {
  2715. comments = await this.fetchCommentsDirectApi(page, work.awemeId);
  2716. }
  2717. if (comments.length > 0) {
  2718. allWorkComments.push({
  2719. videoId: work.awemeId,
  2720. videoTitle: work.title,
  2721. videoCoverUrl: work.coverUrl,
  2722. comments,
  2723. });
  2724. logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
  2725. }
  2726. }
  2727. // 如果直接 API 没有获取到足够的评论,使用页面交互方式
  2728. const worksNeedingPageMethod = worksWithComments.filter(w => {
  2729. const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
  2730. return !found || found.comments.length === 0;
  2731. });
  2732. if (worksNeedingPageMethod.length > 0) {
  2733. logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);
  2734. // works 是所有作品的列表(包括没有评论的),弹窗中的顺序应该和这个一致
  2735. // worksWithComments 是有评论的作品列表
  2736. logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
  2737. logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);
  2738. // 构建作品索引映射:在所有作品列表中,每个有评论的作品的索引是多少
  2739. const workIndexMap = new Map<string, number>();
  2740. works.forEach((w, idx) => {
  2741. if (w.commentCount > 0) {
  2742. workIndexMap.set(w.awemeId, idx);
  2743. }
  2744. });
  2745. logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);
  2746. // 导航到评论管理页面
  2747. logger.info('[Page Method] Navigating to comment management page...');
  2748. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  2749. waitUntil: 'domcontentloaded',
  2750. timeout: 60000,
  2751. });
  2752. // 等待页面加载
  2753. await page.waitForTimeout(5000);
  2754. // 用于存储最新捕获的评论和 aweme_id
  2755. const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };
  2756. // 设置监听器 - 捕获评论 API 响应
  2757. page.on('response', async (response) => {
  2758. const url = response.url();
  2759. if (url.includes('/comment/list') || url.includes('/comment/read')) {
  2760. try {
  2761. const jsonData = await response.json();
  2762. let parsedComments: CommentItem[] = [];
  2763. let capturedAwemeId = '';
  2764. // 从 URL 中提取 aweme_id(格式1有)
  2765. const awemeIdMatch = url.match(/aweme_id=(\d+)/);
  2766. capturedAwemeId = awemeIdMatch?.[1] || '';
  2767. // 格式1: { comments: [...] }
  2768. if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
  2769. // 从评论中提取 aweme_id
  2770. const firstComment = jsonData.comments[0] as Record<string, unknown>;
  2771. if (!capturedAwemeId && firstComment.aweme_id) {
  2772. capturedAwemeId = String(firstComment.aweme_id);
  2773. }
  2774. parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
  2775. commentId: String((c as { cid?: string }).cid || ''),
  2776. authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
  2777. authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
  2778. authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
  2779. content: String((c as { text?: string }).text || ''),
  2780. likeCount: Number((c as { digg_count?: number }).digg_count || 0),
  2781. commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
  2782. videoId: capturedAwemeId,
  2783. }));
  2784. logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
  2785. }
  2786. // 格式2: { comment_info_list: [...] }
  2787. if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
  2788. parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
  2789. const userInfo = c.user_info as Record<string, unknown> | undefined;
  2790. return {
  2791. commentId: String(c.comment_id || ''),
  2792. authorId: String(userInfo?.user_id || ''),
  2793. authorName: String(userInfo?.screen_name || '匿名'),
  2794. authorAvatar: String(userInfo?.avatar_url || ''),
  2795. content: String(c.text || ''),
  2796. likeCount: Number(c.digg_count || 0),
  2797. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2798. videoId: '', // 格式2没有aweme_id,稍后填充
  2799. };
  2800. });
  2801. logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
  2802. }
  2803. if (parsedComments.length > 0) {
  2804. latestHolder.comments = parsedComments;
  2805. latestHolder.awemeId = capturedAwemeId;
  2806. }
  2807. } catch {
  2808. // 忽略
  2809. }
  2810. }
  2811. });
  2812. // 等待第一个作品的评论加载(格式1,有 aweme_id)
  2813. await page.waitForTimeout(4000);
  2814. // 处理第一个作品(页面加载时自动显示,格式1有aweme_id可以直接匹配)
  2815. if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
  2816. const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
  2817. if (matchedWork) {
  2818. allWorkComments.push({
  2819. videoId: matchedWork.awemeId,
  2820. videoTitle: matchedWork.title,
  2821. videoCoverUrl: matchedWork.coverUrl,
  2822. comments: latestHolder.comments,
  2823. });
  2824. logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
  2825. }
  2826. }
  2827. // 遍历其他有评论的作品
  2828. for (const work of worksWithComments) {
  2829. // 检查是否已获取
  2830. const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
  2831. if (existing) {
  2832. logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
  2833. continue;
  2834. }
  2835. // 获取该作品在所有作品列表中的索引
  2836. const workIndex = workIndexMap.get(work.awemeId);
  2837. if (workIndex === undefined) {
  2838. logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
  2839. continue;
  2840. }
  2841. logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);
  2842. try {
  2843. // 清空之前的数据
  2844. latestHolder.comments = [];
  2845. latestHolder.awemeId = '';
  2846. // 点击"选择作品"按钮
  2847. await page.click('button:has-text("选择作品")');
  2848. await page.waitForTimeout(2000);
  2849. // 找到弹窗中的作品图片列表
  2850. const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
  2851. logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);
  2852. if (workIndex < workImages.length) {
  2853. // 点击对应索引的作品
  2854. await workImages[workIndex].click();
  2855. logger.info(`[Page Method] Clicked work image at index ${workIndex}`);
  2856. // 等待评论 API 响应
  2857. await page.waitForTimeout(4000);
  2858. // 获取评论
  2859. if (latestHolder.comments.length > 0) {
  2860. // 使用当前 work 的 awemeId
  2861. const comments = latestHolder.comments.map(c => ({
  2862. ...c,
  2863. videoId: work.awemeId,
  2864. }));
  2865. allWorkComments.push({
  2866. videoId: work.awemeId,
  2867. videoTitle: work.title,
  2868. videoCoverUrl: work.coverUrl,
  2869. comments,
  2870. });
  2871. logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
  2872. } else {
  2873. // 尝试从页面提取
  2874. const pageComments = await this.extractCommentsFromPage(page);
  2875. if (pageComments.length > 0) {
  2876. const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
  2877. allWorkComments.push({
  2878. videoId: work.awemeId,
  2879. videoTitle: work.title,
  2880. videoCoverUrl: work.coverUrl,
  2881. comments,
  2882. });
  2883. logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
  2884. } else {
  2885. logger.warn(`[Page Method] No comments for ${work.awemeId}`);
  2886. }
  2887. }
  2888. } else {
  2889. logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
  2890. await page.keyboard.press('Escape');
  2891. }
  2892. await page.waitForTimeout(1000);
  2893. } catch (e) {
  2894. logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
  2895. await page.keyboard.press('Escape').catch(() => { });
  2896. await page.waitForTimeout(500);
  2897. }
  2898. }
  2899. }
  2900. }
  2901. logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
  2902. await context.close();
  2903. } catch (error) {
  2904. logger.error('[API Interception] Error:', error);
  2905. } finally {
  2906. await browser.close();
  2907. }
  2908. return allWorkComments;
  2909. }
  2910. /**
  2911. * 直接调用评论 API 获取数据(支持分页获取所有评论)
  2912. * 优先使用视频页面 API(获取全部评论),失败时才使用创作者 API
  2913. */
  2914. private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  2915. // 优先尝试视频页面 API(获取全部评论)
  2916. logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
  2917. let comments = await this.fetchVideoPageCommentsApi(page, awemeId);
  2918. if (comments.length > 0) {
  2919. logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
  2920. return comments;
  2921. }
  2922. // 如果视频页面 API 失败,尝试创作者评论 API(可能只返回部分评论)
  2923. logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
  2924. comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);
  2925. return comments;
  2926. }
  2927. /**
  2928. * 通过视频页面获取全部评论(主要方案)
  2929. * 这个 API 能获取视频的所有评论,不仅仅是创作者回复过的
  2930. */
  2931. private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  2932. const comments: CommentItem[] = [];
  2933. const maxPages = 50;
  2934. let cursor = 0;
  2935. let hasMore = true;
  2936. let pageCount = 0;
  2937. try {
  2938. // 导航到视频页面
  2939. logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
  2940. await page.goto(`https://www.douyin.com/video/${awemeId}`, {
  2941. waitUntil: 'domcontentloaded',
  2942. timeout: 30000,
  2943. });
  2944. await page.waitForTimeout(2000);
  2945. while (hasMore && pageCount < maxPages) {
  2946. pageCount++;
  2947. const data = await page.evaluate(async ({ videoId, cursorValue }) => {
  2948. try {
  2949. 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=`;
  2950. const resp = await fetch(url, {
  2951. method: 'GET',
  2952. credentials: 'include',
  2953. headers: {
  2954. 'Accept': 'application/json, text/plain, */*',
  2955. 'Referer': `https://www.douyin.com/video/${videoId}`,
  2956. },
  2957. });
  2958. if (!resp.ok) {
  2959. return { error: `HTTP ${resp.status}`, comments: [] };
  2960. }
  2961. return resp.json();
  2962. } catch (e) {
  2963. return { error: String(e), comments: [] };
  2964. }
  2965. }, { videoId: awemeId, cursorValue: cursor });
  2966. if (data?.error) {
  2967. logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
  2968. }
  2969. if (data?.comments && Array.isArray(data.comments)) {
  2970. for (const c of data.comments) {
  2971. comments.push({
  2972. commentId: String(c.cid || ''),
  2973. authorId: String(c.user?.uid || c.user?.sec_uid || ''),
  2974. authorName: String(c.user?.nickname || '匿名'),
  2975. authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
  2976. content: String(c.text || ''),
  2977. likeCount: Number(c.digg_count || 0),
  2978. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2979. videoId: String(c.aweme_id || awemeId),
  2980. });
  2981. }
  2982. logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
  2983. }
  2984. hasMore = data?.has_more === true || data?.has_more === 1;
  2985. cursor = data?.cursor || cursor + 50;
  2986. if (!data?.comments || data.comments.length === 0) {
  2987. hasMore = false;
  2988. }
  2989. }
  2990. logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
  2991. } catch (e) {
  2992. logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
  2993. }
  2994. return comments;
  2995. }
  2996. /**
  2997. * 创作者评论管理 API(备用方案)
  2998. * 获取的是需要回复的评论
  2999. */
  3000. private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  3001. const comments: CommentItem[] = [];
  3002. const maxPages = 50;
  3003. let cursor = 0;
  3004. let hasMore = true;
  3005. let pageCount = 0;
  3006. try {
  3007. while (hasMore && pageCount < maxPages) {
  3008. pageCount++;
  3009. const data = await page.evaluate(async ({ videoId, cursorValue }) => {
  3010. 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`;
  3011. const resp = await fetch(url, {
  3012. credentials: 'include',
  3013. headers: {
  3014. 'Accept': 'application/json',
  3015. },
  3016. });
  3017. return resp.json();
  3018. }, { videoId: awemeId, cursorValue: cursor });
  3019. if (data?.comments && Array.isArray(data.comments)) {
  3020. for (const c of data.comments) {
  3021. comments.push({
  3022. commentId: String(c.cid || ''),
  3023. authorId: String(c.user?.uid || ''),
  3024. authorName: String(c.user?.nickname || '匿名'),
  3025. authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
  3026. content: String(c.text || ''),
  3027. likeCount: Number(c.digg_count || 0),
  3028. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  3029. videoId: String(c.aweme_id || awemeId),
  3030. });
  3031. }
  3032. logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
  3033. }
  3034. hasMore = data?.has_more === true || data?.has_more === 1;
  3035. cursor = data?.cursor || cursor + 50;
  3036. if (!data?.comments || data.comments.length === 0) {
  3037. hasMore = false;
  3038. }
  3039. }
  3040. logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
  3041. } catch (e) {
  3042. logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
  3043. }
  3044. return comments;
  3045. }
  3046. /**
  3047. * 直接调用抖音 API 获取作品列表
  3048. * 使用新的 work_list 接口,支持分页加载
  3049. * 返回作品列表和总作品数
  3050. *
  3051. * 注意:需要先导航到作品管理页面才能正确调用 API
  3052. */
  3053. private async fetchWorksDirectApi(page: Page): Promise<{
  3054. works: Array<{
  3055. awemeId: string;
  3056. title: string;
  3057. coverUrl: string;
  3058. commentCount: number;
  3059. createTime?: number;
  3060. }>;
  3061. total: number;
  3062. }> {
  3063. const works: Array<{
  3064. awemeId: string;
  3065. title: string;
  3066. coverUrl: string;
  3067. commentCount: number;
  3068. createTime?: number;
  3069. }> = [];
  3070. let totalCount = 0; // 从 API 获取的总作品数
  3071. try {
  3072. // 首先导航到作品管理页面,确保 API 有正确的上下文和权限
  3073. const contentManageUrl = 'https://creator.douyin.com/creator-micro/content/manage';
  3074. const currentUrl = page.url();
  3075. if (!currentUrl.includes('/content/manage')) {
  3076. logger.info(`[DirectAPI] Navigating to content manage page...`);
  3077. await page.goto(contentManageUrl, {
  3078. waitUntil: 'domcontentloaded',
  3079. timeout: 30000,
  3080. });
  3081. await page.waitForTimeout(2000);
  3082. // 检查是否需要登录
  3083. const newUrl = page.url();
  3084. if (newUrl.includes('login') || newUrl.includes('passport')) {
  3085. logger.warn('[DirectAPI] Not logged in, cannot fetch works');
  3086. return { works, total: 0 };
  3087. }
  3088. }
  3089. let hasMore = true;
  3090. let maxCursor = 0;
  3091. let pageCount = 0;
  3092. const maxPages = 20; // 最多加载20页,防止无限循环
  3093. while (hasMore && pageCount < maxPages) {
  3094. pageCount++;
  3095. logger.info(`[DirectAPI] Fetching works page ${pageCount}, cursor: ${maxCursor}`);
  3096. const data = await page.evaluate(async (cursor: number) => {
  3097. // 使用新的 work_list API 接口
  3098. // status: 0 表示获取全部已发布的作品
  3099. // count: 每页获取数量
  3100. const url = `https://creator.douyin.com/janus/douyin/creator/pc/work_list?status=0&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`;
  3101. const resp = await fetch(url, {
  3102. credentials: 'include',
  3103. headers: {
  3104. 'Accept': 'application/json',
  3105. },
  3106. });
  3107. return resp.json();
  3108. }, maxCursor);
  3109. // 获取作品数
  3110. const awemeList = data?.aweme_list || [];
  3111. logger.info(`[DirectAPI] API response: status_code=${data?.status_code}, has_more=${data?.has_more}, max_cursor=${data?.max_cursor}, aweme_list_length=${awemeList.length}`);
  3112. // 检查 API 返回状态
  3113. if (data?.status_code !== 0 && data?.status_code !== undefined) {
  3114. logger.warn(`[DirectAPI] API returned error status_code: ${data.status_code}`);
  3115. // status_code: 8 表示未授权,可能需要重新登录
  3116. if (data.status_code === 8) {
  3117. logger.warn('[DirectAPI] status_code 8: Not authorized, may need re-login');
  3118. }
  3119. break;
  3120. }
  3121. // 优先从第一个作品的 author.aweme_count 获取真实作品数(只在第一页获取)
  3122. if (pageCount === 1 && awemeList.length > 0) {
  3123. const firstAweme = awemeList[0];
  3124. const authorAwemeCount = firstAweme?.author?.aweme_count;
  3125. if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
  3126. totalCount = authorAwemeCount;
  3127. logger.info(`[DirectAPI] Using author.aweme_count as total works: ${totalCount}`);
  3128. }
  3129. }
  3130. // 解析 aweme_list 中的作品数据
  3131. logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);
  3132. for (const aweme of awemeList) {
  3133. const awemeId = String(aweme.aweme_id || '');
  3134. if (!awemeId) continue;
  3135. // 从 statistics 中获取评论数
  3136. const statistics = aweme.statistics || {};
  3137. const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
  3138. // 获取标题:优先使用 item_title,其次使用 desc(描述)
  3139. let title = aweme.item_title || '';
  3140. if (!title) {
  3141. // 从 desc 中提取标题(取第一行或前50个字符)
  3142. const desc = aweme.desc || aweme.caption || '';
  3143. title = desc.split('\n')[0].slice(0, 50) || '无标题';
  3144. }
  3145. // 获取封面 URL:从 Cover.url_list 或 video.cover.url_list 中获取
  3146. let coverUrl = '';
  3147. if (aweme.Cover?.url_list?.length > 0) {
  3148. coverUrl = aweme.Cover.url_list[0];
  3149. } else if (aweme.video?.cover?.url_list?.length > 0) {
  3150. coverUrl = aweme.video.cover.url_list[0];
  3151. }
  3152. works.push({
  3153. awemeId,
  3154. title,
  3155. coverUrl,
  3156. commentCount,
  3157. createTime: aweme.create_time,
  3158. });
  3159. }
  3160. // 检查是否有更多数据
  3161. // 注意: 抖音 API 返回的 has_more 可能不准确,我们额外判断
  3162. const apiHasMore = data?.has_more === true || data?.has_more === 1;
  3163. // 更新游标:使用返回的 max_cursor
  3164. if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
  3165. // 只有当 max_cursor 有变化时才继续
  3166. if (data.max_cursor !== maxCursor) {
  3167. maxCursor = data.max_cursor;
  3168. hasMore = apiHasMore && awemeList.length > 0;
  3169. } else {
  3170. // max_cursor 没变化,说明到底了
  3171. hasMore = false;
  3172. }
  3173. } else if (awemeList.length > 0) {
  3174. // 如果没有 max_cursor,使用最后一个作品的 create_time 作为游标
  3175. const lastAweme = awemeList[awemeList.length - 1];
  3176. if (lastAweme.create_time) {
  3177. const newCursor = lastAweme.create_time;
  3178. if (newCursor !== maxCursor) {
  3179. maxCursor = newCursor;
  3180. hasMore = apiHasMore;
  3181. } else {
  3182. hasMore = false;
  3183. }
  3184. } else {
  3185. hasMore = false;
  3186. }
  3187. } else {
  3188. // 没有获取到数据,停止循环
  3189. hasMore = false;
  3190. }
  3191. logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);
  3192. // 稍微延迟,避免请求过快
  3193. if (hasMore) {
  3194. await new Promise(resolve => setTimeout(resolve, 500));
  3195. }
  3196. }
  3197. logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages, items count: ${totalCount}`);
  3198. } catch (e) {
  3199. logger.warn('[DirectAPI] Failed to fetch works:', e);
  3200. }
  3201. return { works, total: totalCount };
  3202. }
  3203. /**
  3204. * 通过 Python API 获取评论 - 分作品逐个获取
  3205. */
  3206. private async fetchCommentsViaPythonApi(platform: 'douyin' | 'xiaohongshu', cookies: CookieData[]): Promise<WorkComments[]> {
  3207. const allWorkComments: WorkComments[] = [];
  3208. const cookieString = JSON.stringify(cookies);
  3209. // 1. 先获取作品列表
  3210. logger.info(`[${platform} Comments Python] Fetching works list...`);
  3211. const worksResponse = await fetch(`${PYTHON_SERVICE_URL}/works`, {
  3212. method: 'POST',
  3213. headers: { 'Content-Type': 'application/json' },
  3214. body: JSON.stringify({
  3215. platform,
  3216. cookie: cookieString,
  3217. page: 0,
  3218. page_size: 50,
  3219. }),
  3220. });
  3221. if (!worksResponse.ok) {
  3222. throw new Error(`Python API works returned ${worksResponse.status}`);
  3223. }
  3224. const worksResult = await worksResponse.json();
  3225. if (!worksResult.success) {
  3226. throw new Error(worksResult.error || 'Failed to get works');
  3227. }
  3228. const works = worksResult.works || [];
  3229. logger.info(`[${platform} Comments Python] Got ${works.length} works`);
  3230. // 2. 遍历作品获取评论
  3231. for (const work of works) {
  3232. const workId = work.work_id;
  3233. if (!workId) continue;
  3234. try {
  3235. logger.info(`[${platform} Comments Python] Fetching comments for work ${workId}...`);
  3236. const commentsResponse = await fetch(`${PYTHON_SERVICE_URL}/comments`, {
  3237. method: 'POST',
  3238. headers: { 'Content-Type': 'application/json' },
  3239. body: JSON.stringify({
  3240. platform,
  3241. cookie: cookieString,
  3242. work_id: workId,
  3243. }),
  3244. });
  3245. if (!commentsResponse.ok) {
  3246. logger.warn(`[${platform} Comments Python] Comments API returned ${commentsResponse.status} for work ${workId}`);
  3247. continue;
  3248. }
  3249. const commentsResult = await commentsResponse.json();
  3250. if (!commentsResult.success) {
  3251. logger.warn(`[${platform} Comments Python] Failed to get comments for work ${workId}: ${commentsResult.error}`);
  3252. continue;
  3253. }
  3254. const comments: CommentItem[] = (commentsResult.comments || []).map((c: {
  3255. comment_id: string;
  3256. author_id: string;
  3257. author_name: string;
  3258. author_avatar: string;
  3259. content: string;
  3260. like_count: number;
  3261. create_time: string;
  3262. reply_count?: number;
  3263. }) => ({
  3264. commentId: c.comment_id,
  3265. authorId: c.author_id,
  3266. authorName: c.author_name,
  3267. authorAvatar: c.author_avatar,
  3268. content: c.content,
  3269. likeCount: c.like_count,
  3270. commentTime: c.create_time,
  3271. replyCount: c.reply_count || 0,
  3272. }));
  3273. if (comments.length > 0) {
  3274. allWorkComments.push({
  3275. videoId: workId,
  3276. videoTitle: work.title || '',
  3277. videoCoverUrl: work.cover_url || '',
  3278. comments,
  3279. });
  3280. logger.info(`[${platform} Comments Python] Got ${comments.length} comments for work ${workId}`);
  3281. }
  3282. } catch (commentError) {
  3283. logger.warn(`[${platform} Comments Python] Error fetching comments for work ${workId}:`, commentError);
  3284. }
  3285. }
  3286. logger.info(`[${platform} Comments Python] Total: ${allWorkComments.length} works with comments`);
  3287. return allWorkComments;
  3288. }
  3289. /**
  3290. * 通过 Python API 获取抖音评论 - 一次性获取所有作品的评论(备用)
  3291. */
  3292. private async fetchDouyinCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
  3293. const cookieString = JSON.stringify(cookies);
  3294. logger.info('[Douyin Comments Python] Fetching all comments...');
  3295. const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
  3296. method: 'POST',
  3297. headers: { 'Content-Type': 'application/json' },
  3298. body: JSON.stringify({
  3299. platform: 'douyin',
  3300. cookie: cookieString,
  3301. }),
  3302. });
  3303. if (!response.ok) {
  3304. throw new Error(`Python API all_comments returned ${response.status}`);
  3305. }
  3306. const result = await response.json();
  3307. if (!result.success) {
  3308. throw new Error(result.error || 'Failed to get all comments');
  3309. }
  3310. const workComments = result.work_comments || [];
  3311. logger.info(`[Douyin Comments Python] Got ${workComments.length} works with comments`);
  3312. // 转换数据格式
  3313. const allWorkComments: WorkComments[] = workComments.map((wc: {
  3314. work_id: string;
  3315. title: string;
  3316. cover_url: string;
  3317. comments: Array<{
  3318. comment_id: string;
  3319. author_id: string;
  3320. author_name: string;
  3321. author_avatar: string;
  3322. content: string;
  3323. like_count: number;
  3324. create_time: string;
  3325. is_author?: boolean;
  3326. }>;
  3327. }) => ({
  3328. videoId: wc.work_id,
  3329. videoTitle: wc.title || '',
  3330. videoCoverUrl: wc.cover_url || '',
  3331. comments: (wc.comments || []).map(c => ({
  3332. commentId: c.comment_id,
  3333. authorId: c.author_id,
  3334. authorName: c.author_name,
  3335. authorAvatar: c.author_avatar,
  3336. content: c.content,
  3337. likeCount: c.like_count,
  3338. commentTime: c.create_time,
  3339. })),
  3340. }));
  3341. logger.info(`[Douyin Comments Python] Total: ${allWorkComments.length} works with comments`);
  3342. return allWorkComments;
  3343. }
  3344. /**
  3345. * 获取抖音评论 - 优先使用 Python API
  3346. */
  3347. async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  3348. // 优先使用 Python API(分作品获取)
  3349. const pythonAvailable = await this.checkPythonServiceAvailable();
  3350. if (pythonAvailable) {
  3351. logger.info('[Douyin Comments] Using Python API...');
  3352. try {
  3353. const result = await this.fetchCommentsViaPythonApi('douyin', cookies);
  3354. if (result.length > 0) {
  3355. return result;
  3356. }
  3357. logger.info('[Douyin Comments] Python API returned empty, falling back to Playwright...');
  3358. } catch (pythonError) {
  3359. logger.warn('[Douyin Comments] Python API failed:', pythonError);
  3360. }
  3361. }
  3362. // 回退到 Playwright API 拦截方式
  3363. const result = await this.fetchDouyinCommentsByApiInterception(cookies);
  3364. if (result.length > 0) {
  3365. return result;
  3366. }
  3367. // 如果 API 方式失败,使用旧的 DOM 解析方式作为备用
  3368. logger.info('[Fallback] Using DOM parsing method...');
  3369. const browser = await chromium.launch({
  3370. headless: true, // 改为无头模式
  3371. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  3372. });
  3373. const allWorkComments: WorkComments[] = [];
  3374. try {
  3375. const context = await browser.newContext({
  3376. viewport: { width: 1920, height: 1080 },
  3377. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  3378. });
  3379. // 设置 Cookie
  3380. const playwrightCookies = cookies.map(c => ({
  3381. name: c.name,
  3382. value: c.value,
  3383. domain: c.domain || '.douyin.com',
  3384. path: c.path || '/',
  3385. }));
  3386. await context.addCookies(playwrightCookies);
  3387. logger.info(`Set ${playwrightCookies.length} cookies`);
  3388. const page = await context.newPage();
  3389. // 导航到评论管理页面
  3390. logger.info('Navigating to Douyin comment management page...');
  3391. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  3392. waitUntil: 'domcontentloaded',
  3393. timeout: 60000,
  3394. });
  3395. // 等待页面完全加载
  3396. logger.info('Waiting for page to fully load...');
  3397. await page.waitForTimeout(5000);
  3398. // 检查是否需要登录
  3399. const currentUrl = page.url();
  3400. logger.info(`Current URL: ${currentUrl}`);
  3401. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  3402. logger.warn('Cookie expired, need re-login');
  3403. await browser.close();
  3404. return allWorkComments;
  3405. }
  3406. logger.info('Page loaded successfully');
  3407. // 等待评论列表加载
  3408. logger.info('Waiting for comments to load...');
  3409. try {
  3410. await page.waitForSelector('[class*="comment-content-text-"]', { timeout: 10000 });
  3411. logger.info('Comments loaded');
  3412. } catch {
  3413. logger.warn('No comments found on initial load, will try to select works');
  3414. }
  3415. // 辅助函数:从当前页面提取评论
  3416. const extractCommentsFromCurrentPage = async (): Promise<CommentItem[]> => {
  3417. logger.info('Extracting comments from current page...');
  3418. // 滚动页面加载所有评论
  3419. await page.evaluate(async () => {
  3420. // 滚动多次加载更多评论
  3421. for (let i = 0; i < 10; i++) {
  3422. window.scrollBy(0, 500);
  3423. await new Promise(r => setTimeout(r, 800));
  3424. }
  3425. window.scrollTo(0, 0);
  3426. });
  3427. await page.waitForTimeout(2000);
  3428. // 使用精确选择器提取评论
  3429. const comments = await page.evaluate(() => {
  3430. const result: Array<{
  3431. commentId: string;
  3432. authorId: string;
  3433. authorName: string;
  3434. authorAvatar: string;
  3435. content: string;
  3436. likeCount: number;
  3437. commentTime: string;
  3438. }> = [];
  3439. const seenContents = new Set<string>();
  3440. // 查找所有评论容器:包含 username 和 comment-content-text 的 container
  3441. const allContainers = document.querySelectorAll('[class*="container-"]');
  3442. const commentContainers: Element[] = [];
  3443. allContainers.forEach(container => {
  3444. const hasUsername = container.querySelector('[class*="username-"]');
  3445. const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
  3446. if (hasUsername && hasCommentContent) {
  3447. commentContainers.push(container);
  3448. }
  3449. });
  3450. console.log(`Found ${commentContainers.length} comment containers`);
  3451. commentContainers.forEach((container, index) => {
  3452. try {
  3453. // 用户名
  3454. const usernameEl = container.querySelector('[class*="username-"]');
  3455. const authorName = usernameEl?.textContent?.trim() || '未知用户';
  3456. // 时间
  3457. const timeEl = container.querySelector('[class*="time-"]');
  3458. const commentTime = timeEl?.textContent?.trim() || '';
  3459. // 评论内容
  3460. const contentEl = container.querySelector('[class*="comment-content-text-"]');
  3461. const content = contentEl?.textContent?.trim() || '';
  3462. if (!content) return;
  3463. // 头像
  3464. const avatarContainer = container.querySelector('[class*="avatar-"]');
  3465. const avatarImg = avatarContainer?.querySelector('img');
  3466. const authorAvatar = avatarImg?.src || '';
  3467. // 去重
  3468. const key = `${authorName}||${content}`;
  3469. if (seenContents.has(key)) return;
  3470. seenContents.add(key);
  3471. // 点赞数
  3472. let likeCount = 0;
  3473. const opsEl = container.querySelector('[class*="operations-"]');
  3474. if (opsEl) {
  3475. const itemEl = opsEl.querySelector('[class*="item-"]');
  3476. if (itemEl) {
  3477. const match = itemEl.textContent?.match(/(\d+)/);
  3478. if (match) likeCount = parseInt(match[1], 10);
  3479. }
  3480. }
  3481. // 生成 ID
  3482. const hash = content.slice(0, 30) + authorName + commentTime;
  3483. const commentId = `dy_${btoa(encodeURIComponent(hash)).slice(0, 20)}`;
  3484. result.push({
  3485. commentId,
  3486. authorId: authorName,
  3487. authorName,
  3488. authorAvatar,
  3489. content,
  3490. likeCount,
  3491. commentTime,
  3492. });
  3493. console.log(`[${index}] ${authorName}: ${content.slice(0, 30)}`);
  3494. } catch (e) {
  3495. console.error(`Error at ${index}:`, e);
  3496. }
  3497. });
  3498. return result;
  3499. });
  3500. logger.info(`Extracted ${comments.length} comments`);
  3501. return comments;
  3502. };
  3503. // 辅助函数:获取当前显示的作品标题
  3504. const getCurrentWorkTitle = async (): Promise<string> => {
  3505. return page.evaluate(() => {
  3506. // 查找作品标题 - 通常在页面顶部区域
  3507. // 排除筛选器和按钮中的文本
  3508. const excludeTexts = ['全部评论', '最新发布', '全部人群', '搜索', '选择作品', '评论管理'];
  3509. // 方法1: 查找视频信息区域
  3510. const videoInfoSelectors = [
  3511. '[class*="video-info"] [class*="title"]',
  3512. '[class*="work-info"] [class*="title"]',
  3513. '[class*="content-info"] [class*="title"]',
  3514. ];
  3515. for (const selector of videoInfoSelectors) {
  3516. const el = document.querySelector(selector);
  3517. if (el?.textContent) {
  3518. const text = el.textContent.trim();
  3519. if (text.length > 5 && !excludeTexts.some(e => text.includes(e))) {
  3520. return text;
  3521. }
  3522. }
  3523. }
  3524. // 方法2: 查找页面上较长的标题文本
  3525. const allTexts = document.querySelectorAll('div, span, p');
  3526. for (const el of Array.from(allTexts)) {
  3527. const text = el.textContent?.trim() || '';
  3528. if (text.length > 20 &&
  3529. text.length < 200 &&
  3530. !excludeTexts.some(e => text.includes(e)) &&
  3531. !el.closest('button') &&
  3532. !el.closest('[class*="select"]') &&
  3533. !el.closest('[class*="filter"]')) {
  3534. // 检查是否可能是作品标题(通常包含特定字符或格式)
  3535. if (text.includes('#') || text.match(/[,。!?、]/)) {
  3536. return text;
  3537. }
  3538. }
  3539. }
  3540. return '';
  3541. });
  3542. };
  3543. // 步骤1: 先获取当前页面显示的评论(默认显示的第一个作品)
  3544. logger.info('Step 1: Getting comments from default view...');
  3545. const defaultTitle = await getCurrentWorkTitle();
  3546. const defaultComments = await extractCommentsFromCurrentPage();
  3547. if (defaultComments.length > 0) {
  3548. allWorkComments.push({
  3549. videoId: `video_${Date.now()}`,
  3550. videoTitle: defaultTitle || '默认作品',
  3551. videoCoverUrl: '',
  3552. comments: defaultComments,
  3553. });
  3554. logger.info(`Got ${defaultComments.length} comments from default view, title: "${defaultTitle.slice(0, 50)}"`);
  3555. }
  3556. // 步骤2: 尝试点击"选择作品"按钮获取更多作品的评论
  3557. logger.info('Step 2: Looking for "选择作品" button...');
  3558. // 使用 locator 查找按钮
  3559. const selectBtn = page.locator('text=选择作品').first();
  3560. const btnCount = await selectBtn.count();
  3561. logger.info(`Found ${btnCount} "选择作品" button(s)`);
  3562. if (btnCount > 0) {
  3563. logger.info('Clicking "选择作品" button...');
  3564. await selectBtn.click();
  3565. // 等待更长时间,确保弹窗完全加载
  3566. logger.info('Waiting for work list modal to appear...');
  3567. await page.waitForTimeout(5000);
  3568. // 打印当前页面状态,帮助调试
  3569. const modalInfo = await page.evaluate(() => {
  3570. // 查找所有可能的弹窗元素
  3571. const modals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="drawer"], [class*="dialog"], [role="dialog"]');
  3572. const modalClasses = Array.from(modals).map(m => m.className).slice(0, 5);
  3573. // 查找所有图片(作品封面)
  3574. const images = document.querySelectorAll('img[src*="douyinpic"]');
  3575. // 查找所有可能的卡片元素
  3576. const cards = document.querySelectorAll('[class*="card"], [class*="item"]');
  3577. const cardClasses = Array.from(cards).map(c => c.className).slice(0, 10);
  3578. return {
  3579. modalCount: modals.length,
  3580. modalClasses,
  3581. imageCount: images.length,
  3582. cardCount: cards.length,
  3583. cardClasses,
  3584. };
  3585. });
  3586. logger.info(`Modal debug: ${JSON.stringify(modalInfo)}`);
  3587. // 尝试多种选择器查找作品列表
  3588. const workSelectors = [
  3589. '[class*="video-card"]',
  3590. '[class*="work-item"]',
  3591. '[class*="content-item"]',
  3592. '[class*="modal"] [class*="card"]',
  3593. '[class*="modal"] img',
  3594. '[class*="drawer"] [class*="card"]',
  3595. '[class*="drawer"] img',
  3596. '[role="dialog"] [class*="card"]',
  3597. '[role="dialog"] img',
  3598. '[class*="popup"] img',
  3599. 'img[src*="douyinpic"]', // 直接找抖音图片
  3600. ];
  3601. let workElements: Awaited<ReturnType<typeof page.$$>> = [];
  3602. let usedSelector = '';
  3603. for (const selector of workSelectors) {
  3604. const elements = await page.$$(selector);
  3605. logger.info(`Selector "${selector}" found ${elements.length} elements`);
  3606. if (elements.length > 0 && elements.length < 50) { // 避免选中太多无关元素
  3607. workElements = elements;
  3608. usedSelector = selector;
  3609. break;
  3610. }
  3611. }
  3612. logger.info(`Using selector "${usedSelector}", found ${workElements.length} work items`);
  3613. if (workElements.length > 0) {
  3614. // 首先获取所有作品的评论数信息
  3615. // 根据 HTML 结构:
  3616. // - 作品项容器: div.container-Lkxos9 (类名可能变化,使用 [class*="container-"])
  3617. // - 标题: div.title-LUOP3b (类名可能变化,使用 [class*="title-"])
  3618. // - 评论数: div.right-os7ZB9 > div (类名可能变化,使用 [class*="right-"] > div)
  3619. const workInfoList = await page.evaluate(() => {
  3620. const works: Array<{ index: number; title: string; commentCount: number }> = [];
  3621. // 查找作品列表容器中的所有作品项
  3622. // 根据用户提供的 HTML,作品项的类名是 container-Lkxos9
  3623. const workContainers = document.querySelectorAll('[role="dialog"] [class*="container-"]');
  3624. console.log(`Found ${workContainers.length} work containers`);
  3625. workContainers.forEach((container, index) => {
  3626. // 检查是否包含图片(确认是作品项而不是其他容器)
  3627. const img = container.querySelector('img[src*="douyinpic"]');
  3628. if (!img) {
  3629. console.log(`Container ${index} has no douyinpic image, skipping`);
  3630. return;
  3631. }
  3632. // 提取标题
  3633. const titleEl = container.querySelector('[class*="title-"]');
  3634. const title = titleEl?.textContent?.trim() || `作品 ${works.length + 1}`;
  3635. // 提取评论数 - 在 right- 容器的最后一个 div 中
  3636. let commentCount = 0;
  3637. const rightContainer = container.querySelector('[class*="right-"]');
  3638. if (rightContainer) {
  3639. // 获取 right 容器下的所有直接 div 子元素
  3640. const divs = rightContainer.querySelectorAll(':scope > div');
  3641. if (divs.length > 0) {
  3642. // 最后一个 div 包含评论数
  3643. const lastDiv = divs[divs.length - 1];
  3644. const text = lastDiv.textContent?.trim() || '0';
  3645. const num = parseInt(text, 10);
  3646. if (!isNaN(num)) {
  3647. commentCount = num;
  3648. }
  3649. }
  3650. }
  3651. console.log(`Work ${works.length}: title="${title.slice(0, 30)}...", commentCount=${commentCount}`);
  3652. works.push({
  3653. index: works.length,
  3654. title: title.slice(0, 100),
  3655. commentCount
  3656. });
  3657. });
  3658. // 如果上面的选择器没找到,尝试备用方法
  3659. if (works.length === 0) {
  3660. console.log('Primary selector failed, trying fallback...');
  3661. // 直接查找包含 douyinpic 图片的元素的父容器
  3662. const images = document.querySelectorAll('[role="dialog"] img[src*="douyinpic"]');
  3663. images.forEach((img, index) => {
  3664. // 向上查找到作品项容器
  3665. let container = img.parentElement;
  3666. while (container && !container.classList.toString().includes('container-')) {
  3667. container = container.parentElement;
  3668. }
  3669. if (container) {
  3670. const titleEl = container.querySelector('[class*="title-"]');
  3671. const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
  3672. // 查找评论数
  3673. let commentCount = 0;
  3674. const rightEl = container.querySelector('[class*="right-"]');
  3675. if (rightEl) {
  3676. const text = rightEl.textContent?.trim() || '';
  3677. // 提取最后出现的数字
  3678. const matches = text.match(/\d+/g);
  3679. if (matches && matches.length > 0) {
  3680. commentCount = parseInt(matches[matches.length - 1], 10);
  3681. }
  3682. }
  3683. works.push({ index, title: title.slice(0, 100), commentCount });
  3684. }
  3685. });
  3686. }
  3687. return works;
  3688. });
  3689. logger.info(`Work info list (${workInfoList.length} items): ${JSON.stringify(workInfoList)}`);
  3690. // 过滤出评论数 > 0 的作品,或者评论数未知(-1)的作品
  3691. const worksWithComments = workInfoList.filter(w => w.commentCount > 0 || w.commentCount === -1);
  3692. logger.info(`Found ${worksWithComments.length} works with comments > 0 or unknown (out of ${workInfoList.length})`);
  3693. // 如果所有作品评论数都是0,则不处理任何作品
  3694. const allZero = workInfoList.every(w => w.commentCount === 0);
  3695. if (allZero) {
  3696. logger.info('All works have 0 comments, skipping all');
  3697. }
  3698. // 如果没有找到评论数信息或有未知的,处理这些作品
  3699. const indicesToProcess = allZero
  3700. ? []
  3701. : (worksWithComments.length > 0
  3702. ? worksWithComments.map(w => w.index)
  3703. : Array.from({ length: Math.min(workElements.length, 10) }, (_, i) => i));
  3704. logger.info(`Will process work indices: ${indicesToProcess.join(', ')}`);
  3705. // 遍历每个有评论的作品
  3706. for (let idx = 0; idx < indicesToProcess.length; idx++) {
  3707. const i = indicesToProcess[idx];
  3708. try {
  3709. const workInfo = workInfoList.find(w => w.index === i);
  3710. logger.info(`Processing work ${idx + 1}/${indicesToProcess.length} (index=${i}, title="${workInfo?.title}", expectedComments=${workInfo?.commentCount})...`);
  3711. // 重新打开选择作品弹窗
  3712. if (idx > 0) {
  3713. await selectBtn.click();
  3714. await page.waitForTimeout(3000);
  3715. }
  3716. // 重新获取元素列表(因为 DOM 可能已变化)
  3717. const currentItems = await page.$$(usedSelector);
  3718. if (i < currentItems.length) {
  3719. // 滚动到元素可见
  3720. await currentItems[i].scrollIntoViewIfNeeded();
  3721. await page.waitForTimeout(500);
  3722. // 点击元素
  3723. await currentItems[i].click();
  3724. await page.waitForTimeout(4000);
  3725. // 获取评论
  3726. const title = await getCurrentWorkTitle();
  3727. const comments = await extractCommentsFromCurrentPage();
  3728. logger.info(`Work index=${i}: title="${title.slice(0, 50)}", comments=${comments.length}`);
  3729. // 检查是否已经获取过这个作品的评论
  3730. const exists = allWorkComments.some(w =>
  3731. w.videoTitle === title ||
  3732. (w.comments.length > 0 && comments.length > 0 &&
  3733. w.comments[0].content === comments[0].content)
  3734. );
  3735. if (!exists && (comments.length > 0 || title)) {
  3736. allWorkComments.push({
  3737. videoId: `video_${Date.now()}_${i}`,
  3738. videoTitle: title || workInfo?.title || `作品 ${i + 1}`,
  3739. videoCoverUrl: '',
  3740. comments,
  3741. });
  3742. logger.info(`Work index=${i}: Saved ${comments.length} comments`);
  3743. } else {
  3744. logger.info(`Work index=${i}: Skipped (duplicate or empty)`);
  3745. }
  3746. }
  3747. } catch (err) {
  3748. logger.warn(`Error processing work index=${i}:`, err);
  3749. }
  3750. }
  3751. } else {
  3752. logger.warn('No work items found in modal');
  3753. }
  3754. // 按 Escape 关闭弹窗
  3755. try {
  3756. await page.keyboard.press('Escape');
  3757. await page.waitForTimeout(500);
  3758. } catch { }
  3759. } else {
  3760. logger.warn('"选择作品" button not found, only default comments will be returned');
  3761. }
  3762. await page.close();
  3763. await context.close();
  3764. await browser.close();
  3765. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  3766. logger.info(`Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  3767. return allWorkComments;
  3768. } catch (error) {
  3769. logger.error('Error fetching Douyin comments:', error);
  3770. try {
  3771. await browser.close();
  3772. } catch { }
  3773. return allWorkComments;
  3774. }
  3775. }
  3776. /**
  3777. * 通过 Python API 获取小红书评论 - 一次性获取所有作品的评论
  3778. */
  3779. private async fetchXiaohongshuCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
  3780. const cookieString = JSON.stringify(cookies);
  3781. logger.info('[Xiaohongshu Comments Python] Fetching all comments...');
  3782. const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
  3783. method: 'POST',
  3784. headers: { 'Content-Type': 'application/json' },
  3785. body: JSON.stringify({
  3786. platform: 'xiaohongshu',
  3787. cookie: cookieString,
  3788. }),
  3789. });
  3790. if (!response.ok) {
  3791. throw new Error(`Python API all_comments returned ${response.status}`);
  3792. }
  3793. const result = await response.json();
  3794. if (!result.success) {
  3795. throw new Error(result.error || 'Failed to get all comments');
  3796. }
  3797. const workComments = result.work_comments || [];
  3798. logger.info(`[Xiaohongshu Comments Python] Got ${workComments.length} works with comments`);
  3799. // 转换数据格式
  3800. const allWorkComments: WorkComments[] = workComments.map((wc: {
  3801. work_id: string;
  3802. title: string;
  3803. cover_url: string;
  3804. comments: Array<{
  3805. comment_id: string;
  3806. author_id: string;
  3807. author_name: string;
  3808. author_avatar: string;
  3809. content: string;
  3810. like_count: number;
  3811. create_time: string;
  3812. }>;
  3813. }) => ({
  3814. videoId: wc.work_id,
  3815. videoTitle: wc.title || '',
  3816. videoCoverUrl: wc.cover_url || '',
  3817. comments: (wc.comments || []).map(c => ({
  3818. commentId: c.comment_id,
  3819. authorId: c.author_id,
  3820. authorName: c.author_name,
  3821. authorAvatar: c.author_avatar,
  3822. content: c.content,
  3823. likeCount: c.like_count,
  3824. commentTime: c.create_time,
  3825. })),
  3826. }));
  3827. logger.info(`[Xiaohongshu Comments Python] Total: ${allWorkComments.length} works with comments`);
  3828. return allWorkComments;
  3829. }
  3830. /**
  3831. * 获取小红书评论 - 优先使用 Python API
  3832. */
  3833. async fetchXiaohongshuCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  3834. // 优先使用 Python API(分作品获取)
  3835. const pythonAvailable = await this.checkPythonServiceAvailable();
  3836. if (pythonAvailable) {
  3837. logger.info('[Xiaohongshu Comments] Using Python API...');
  3838. try {
  3839. const result = await this.fetchCommentsViaPythonApi('xiaohongshu', cookies);
  3840. if (result.length > 0) {
  3841. return result;
  3842. }
  3843. logger.info('[Xiaohongshu Comments] Python API returned empty, falling back to Playwright...');
  3844. } catch (pythonError) {
  3845. logger.warn('[Xiaohongshu Comments] Python API failed:', pythonError);
  3846. }
  3847. }
  3848. // 回退到 Playwright 方式
  3849. const browser = await chromium.launch({
  3850. headless: true,
  3851. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  3852. });
  3853. const allWorkComments: WorkComments[] = [];
  3854. try {
  3855. const context = await browser.newContext({
  3856. viewport: { width: 1920, height: 1080 },
  3857. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  3858. });
  3859. // 设置 Cookie
  3860. const playwrightCookies = cookies.map(c => ({
  3861. name: c.name,
  3862. value: c.value,
  3863. domain: c.domain || '.xiaohongshu.com',
  3864. path: c.path || '/',
  3865. }));
  3866. await context.addCookies(playwrightCookies);
  3867. logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);
  3868. const page = await context.newPage();
  3869. // 用于捕获评论数据
  3870. const capturedComments: Map<string, CommentItem[]> = new Map();
  3871. const capturedNotes: Array<{
  3872. noteId: string;
  3873. title: string;
  3874. coverUrl: string;
  3875. }> = [];
  3876. // 设置 API 响应监听器
  3877. page.on('response', async (response) => {
  3878. const url = response.url();
  3879. try {
  3880. // 监听笔记列表 API
  3881. if (url.includes('/api/galaxy/creator/content/note_list') ||
  3882. url.includes('/api/galaxy/creator/notes')) {
  3883. const data = await response.json();
  3884. logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
  3885. const notes = data?.data?.notes || data?.data?.list || [];
  3886. for (const note of notes) {
  3887. capturedNotes.push({
  3888. noteId: note.note_id || note.id || '',
  3889. title: note.title || note.desc || '',
  3890. coverUrl: note.cover?.url || note.cover || '',
  3891. });
  3892. }
  3893. }
  3894. // 监听评论列表 API
  3895. if (url.includes('/api/sns/web/v2/comment/page') ||
  3896. url.includes('/api/galaxy/creator/comment') ||
  3897. url.includes('/api/sns/v1/note/comment')) {
  3898. const data = await response.json();
  3899. logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
  3900. const comments: CommentItem[] = [];
  3901. const commentList = data?.data?.comments || data?.comments || [];
  3902. for (const comment of commentList) {
  3903. comments.push({
  3904. commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
  3905. authorId: comment.user_info?.user_id || comment.user_id || '',
  3906. authorName: comment.user_info?.nickname || comment.nickname || '',
  3907. authorAvatar: comment.user_info?.image || comment.avatar || '',
  3908. content: comment.content || '',
  3909. likeCount: comment.like_count || 0,
  3910. commentTime: comment.create_time || comment.time || '',
  3911. parentCommentId: comment.target_comment_id || undefined,
  3912. });
  3913. // 处理子评论
  3914. const subComments = comment.sub_comments || comment.replies || [];
  3915. for (const sub of subComments) {
  3916. comments.push({
  3917. commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
  3918. authorId: sub.user_info?.user_id || sub.user_id || '',
  3919. authorName: sub.user_info?.nickname || sub.nickname || '',
  3920. authorAvatar: sub.user_info?.image || sub.avatar || '',
  3921. content: sub.content || '',
  3922. likeCount: sub.like_count || 0,
  3923. commentTime: sub.create_time || sub.time || '',
  3924. parentCommentId: comment.id || comment.comment_id || undefined,
  3925. });
  3926. }
  3927. }
  3928. // 尝试从 URL 获取笔记 ID
  3929. const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
  3930. const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;
  3931. if (comments.length > 0) {
  3932. const existing = capturedComments.get(noteId) || [];
  3933. capturedComments.set(noteId, [...existing, ...comments]);
  3934. }
  3935. }
  3936. } catch { }
  3937. });
  3938. // 导航到评论管理页面
  3939. logger.info('[Xiaohongshu Comments] Navigating to comment management...');
  3940. await page.goto('https://creator.xiaohongshu.com/creator/comment', {
  3941. waitUntil: 'domcontentloaded',
  3942. timeout: 60000,
  3943. });
  3944. await page.waitForTimeout(5000);
  3945. // 检查是否需要登录
  3946. const currentUrl = page.url();
  3947. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  3948. logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
  3949. await browser.close();
  3950. return allWorkComments;
  3951. }
  3952. // 尝试加载更多评论
  3953. for (let i = 0; i < 5; i++) {
  3954. await page.evaluate(() => {
  3955. window.scrollBy(0, 500);
  3956. });
  3957. await page.waitForTimeout(1000);
  3958. }
  3959. // 等待 API 响应
  3960. await page.waitForTimeout(3000);
  3961. // 将捕获的评论转换为 WorkComments 格式
  3962. for (const [noteId, comments] of capturedComments) {
  3963. const noteInfo = capturedNotes.find(n => n.noteId === noteId);
  3964. allWorkComments.push({
  3965. videoId: noteId,
  3966. videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
  3967. videoCoverUrl: noteInfo?.coverUrl || '',
  3968. comments,
  3969. });
  3970. }
  3971. // 如果没有从 API 获取到评论,尝试从页面提取
  3972. if (allWorkComments.length === 0) {
  3973. logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');
  3974. const pageComments = await page.evaluate(() => {
  3975. const result: Array<{
  3976. commentId: string;
  3977. authorName: string;
  3978. authorAvatar: string;
  3979. content: string;
  3980. likeCount: number;
  3981. commentTime: string;
  3982. }> = [];
  3983. const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
  3984. commentItems.forEach((item, index) => {
  3985. try {
  3986. const authorEl = item.querySelector('[class*="author"], [class*="name"]');
  3987. const avatarEl = item.querySelector('img');
  3988. const contentEl = item.querySelector('[class*="content"]');
  3989. const timeEl = item.querySelector('[class*="time"]');
  3990. const likeEl = item.querySelector('[class*="like"] span');
  3991. result.push({
  3992. commentId: `xhs_page_${index}`,
  3993. authorName: authorEl?.textContent?.trim() || '',
  3994. authorAvatar: avatarEl?.src || '',
  3995. content: contentEl?.textContent?.trim() || '',
  3996. likeCount: parseInt(likeEl?.textContent || '0') || 0,
  3997. commentTime: timeEl?.textContent?.trim() || '',
  3998. });
  3999. } catch { }
  4000. });
  4001. return result;
  4002. });
  4003. if (pageComments.length > 0) {
  4004. allWorkComments.push({
  4005. videoId: 'page_comments',
  4006. videoTitle: '页面评论',
  4007. videoCoverUrl: '',
  4008. comments: pageComments.map(c => ({
  4009. ...c,
  4010. authorId: '',
  4011. })),
  4012. });
  4013. }
  4014. }
  4015. await page.close();
  4016. await context.close();
  4017. await browser.close();
  4018. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  4019. logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  4020. return allWorkComments;
  4021. } catch (error) {
  4022. logger.error('[Xiaohongshu Comments] Error:', error);
  4023. try {
  4024. await browser.close();
  4025. } catch { }
  4026. return allWorkComments;
  4027. }
  4028. }
  4029. }
  4030. export const headlessBrowserService = new HeadlessBrowserService();