HeadlessBrowserService.ts 174 KB

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