| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460 |
- /// <reference lib="dom" />
- import { chromium, type BrowserContext, type Page } from 'playwright';
- import { logger } from '../utils/logger.js';
- import type { PlatformType } from '@media-manager/shared';
- // Python 服务配置
- const PYTHON_SERVICE_URL = process.env.PYTHON_PUBLISH_SERVICE_URL || process.env.XHS_SERVICE_URL || 'http://localhost:5005';
- // 抖音 API 接口配置
- const DOUYIN_API = {
- // 检查用户登录状态 - 返回 result: true 表示已登录(需要在浏览器上下文中调用)
- CHECK_USER: '/aweme/v1/creator/check/user/',
- // 获取作品列表(新接口,支持分页)
- WORK_LIST: 'https://creator.douyin.com/janus/douyin/creator/pc/work_list',
- // 获取评论列表
- COMMENT_LIST: 'https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/',
- // 创作者首页(用于触发登录检查)
- CREATOR_HOME: 'https://creator.douyin.com/creator-micro/home',
- };
- // 平台 API 配置(用于直接 HTTP 请求检查)
- const PLATFORM_API_CONFIG: Record<string, {
- checkUrl: string;
- isValidResponse: (data: unknown) => boolean;
- }> = {
- douyin: {
- // 使用账号基础信息接口检查 Cookie 有效性
- checkUrl: 'https://creator.douyin.com/web/api/creator/mcn/account_base_info?show_mcn_status=1',
- isValidResponse: (data: unknown) => {
- const resp = data as { status_code?: number; BaseResp?: { StatusCode?: number } };
- // status_code 为 0 表示 Cookie 有效
- return resp?.status_code === 0 || resp?.BaseResp?.StatusCode === 0;
- },
- },
- baijiahao: {
- // 使用 appinfo 接口检查 Cookie 有效性
- checkUrl: 'https://baijiahao.baidu.com/builder/app/appinfo',
- isValidResponse: (data: unknown) => {
- const resp = data as {
- errno?: number;
- errmsg?: string;
- data?: {
- user?: {
- name?: string;
- app_id?: string | number;
- userid?: number;
- status?: string;
- }
- }
- };
-
- 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}`);
-
- // errno 为 0 表示请求成功
- const isErrnoOk = resp?.errno === 0;
-
- // 必须有用户信息(name 或 app_id)
- const hasUserInfo = !!(resp?.data?.user?.name || resp?.data?.user?.app_id);
-
- // 用户状态不能是 'banned' 或其他异常状态
- const userStatus = resp?.data?.user?.status;
- const isStatusOk = !userStatus || userStatus === 'audit' || userStatus === 'pass' || userStatus === 'active';
-
- const isValid = isErrnoOk && hasUserInfo && isStatusOk;
-
- if (!isValid) {
- logger.warn(`[Baijiahao] Cookie invalid: errno=${resp?.errno}, hasUserInfo=${hasUserInfo}, status=${userStatus}`);
- }
-
- return isValid;
- },
- },
- };
- export interface AccountInfo {
- accountId: string;
- accountName: string;
- avatarUrl: string;
- fansCount: number;
- worksCount: number;
- worksList?: WorkItem[];
- }
- export interface WorkItem {
- videoId?: string;
- title: string;
- coverUrl: string;
- duration: string;
- publishTime: string;
- status: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- }
- export interface CommentItem {
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- parentCommentId?: string;
- videoId?: string;
- videoTitle?: string;
- videoCoverUrl?: string;
- }
- export interface WorkComments {
- videoId: string;
- videoTitle: string;
- videoCoverUrl: string;
- comments: CommentItem[];
- }
- export interface CookieData {
- name: string;
- value: string;
- domain: string;
- path: string;
- }
- /**
- * 无头浏览器服务 - 用于后台静默获取账号信息
- */
- class HeadlessBrowserService {
- /**
- * 检查 Cookie 是否有效
- * 优先使用 Python 服务(通过浏览器访问后台检测),回退到 API 检查
- */
- async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- logger.info(`[checkCookieValid] Checking cookie for ${platform}, cookie count: ${cookies.length}`);
-
- // 优先使用 Python 服务检查(通过浏览器访问后台页面,检测是否被重定向到登录页)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- try {
- const result = await this.checkLoginViaPython(platform, cookies);
- logger.info(`[checkCookieValid] Python service result for ${platform}: ${result}`);
- return result;
- } catch (error) {
- logger.warn(`[Python API] Check login failed, falling back to API check:`, error);
- }
- } else {
- logger.info(`[checkCookieValid] Python service not available, using API check`);
- }
- // 回退到 API 检查
- const apiConfig = PLATFORM_API_CONFIG[platform];
- if (apiConfig) {
- const result = await this.checkCookieValidByApi(platform, cookies, apiConfig);
- logger.info(`[checkCookieValid] API check result for ${platform}: ${result}`);
- return result;
- }
- // 其他平台使用浏览器检查
- const result = await this.checkCookieValidByBrowser(platform, cookies);
- logger.info(`[checkCookieValid] Browser check result for ${platform}: ${result}`);
- return result;
- }
- /**
- * 通过 Python 服务检查登录状态(浏览器访问后台页面,检测是否需要登录)
- */
- private async checkLoginViaPython(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- const pythonUrl = PYTHON_SERVICE_URL;
- // 构建 Cookie 字符串
- const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
- logger.info(`[Python API] Checking login status for ${platform}`);
- const response = await fetch(`${pythonUrl}/check_login`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API returned ${response.status}`);
- }
- const result = await response.json() as {
- success: boolean;
- valid: boolean;
- need_login: boolean;
- message?: string;
- error?: string;
- };
- logger.info(`[Python API] Check login result for ${platform}: valid=${result.valid}, need_login=${result.need_login}`);
- if (!result.success) {
- throw new Error(result.error || 'Check login failed');
- }
- return result.valid && !result.need_login;
- }
- /**
- * 通过 API 检查 Cookie 是否有效
- * 注意:API 返回不确定状态时会回退到浏览器检查,避免误判
- */
- private async checkCookieValidByApi(
- platform: PlatformType,
- cookies: CookieData[],
- apiConfig: typeof PLATFORM_API_CONFIG[string]
- ): Promise<boolean> {
- try {
- // 构建 Cookie 字符串(所有 Cookie 拼接)
- const cookieString = cookies
- .map(c => `${c.name}=${c.value}`)
- .join('; ');
- logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);
- // 发起 API 请求,模拟浏览器请求
- const response = await fetch(apiConfig.checkUrl, {
- method: 'GET',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Cache-Control': 'no-cache',
- 'Cookie': cookieString,
- 'Pragma': 'no-cache',
- 'Referer': this.getPlatformReferer(platform),
- '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',
- 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
- 'sec-ch-ua-mobile': '?0',
- 'sec-ch-ua-platform': '"Windows"',
- 'sec-fetch-dest': 'empty',
- 'sec-fetch-mode': 'cors',
- 'sec-fetch-site': 'same-origin',
- },
- });
- const data = await response.json();
- logger.info(`[API] Raw response for ${platform}:`, JSON.stringify(data).substring(0, 500));
-
- const isValid = apiConfig.isValidResponse(data);
- const statusCode = (data as { status_code?: number; errno?: number; ret?: { errno?: number } })?.status_code
- ?? (data as { errno?: number })?.errno
- ?? (data as { ret?: { errno?: number } })?.ret?.errno;
- logger.info(`API check cookie for ${platform}: valid=${isValid}, statusCode=${statusCode}`);
- // 如果 API 明确返回有效,直接返回 true
- if (isValid) {
- return true;
- }
- // API 返回无效时,检查是否是明确的"未登录"状态
- // 抖音: status_code 为 2 或 8 通常表示未登录/登录过期
- // 百家号: errno 为非 0 可能表示未登录,但需要根据具体错误码判断
- const clearlyNotLoggedIn = statusCode === 2 || statusCode === 8;
- if (clearlyNotLoggedIn) {
- logger.info(`[API] Platform ${platform} clearly not logged in (statusCode=${statusCode})`);
- return false;
- }
- // 百家号特殊处理:根据 errno 判断
- if (platform === 'baijiahao') {
- const errno = (data as { errno?: number })?.errno;
-
- // errno 为 0 表示请求成功,但可能没有用户信息(已在 isValidResponse 中检查)
- if (errno === 0) {
- // 如果 isValid 为 false,说明虽然请求成功但没有用户信息,可能是 Cookie 无效
- if (!isValid) {
- logger.warn(`[API] Baijiahao errno=0 but no user info, cookie may be invalid`);
- return false;
- }
- return true;
- }
-
- // errno 非 0 表示请求失败,可能是 Cookie 无效
- // 常见错误码:
- // - 110: 未登录
- // - 其他非 0 值:可能是权限问题或其他错误
- logger.warn(`[API] Baijiahao errno=${errno}, cookie is invalid`);
- return false;
- }
- // 不确定的状态(如 status_code=7),回退到浏览器检查
- logger.info(`[API] Uncertain status for ${platform} (statusCode=${statusCode}), falling back to browser check`);
- return this.checkCookieValidByBrowser(platform, cookies);
- } catch (error) {
- logger.error(`API check cookie error for ${platform}:`, error);
- // API 检查失败时,回退到浏览器检查
- return this.checkCookieValidByBrowser(platform, cookies);
- }
- }
- /**
- * 获取平台 Referer
- */
- private getPlatformReferer(platform: PlatformType): string {
- const referers: Record<string, string> = {
- douyin: 'https://creator.douyin.com/',
- bilibili: 'https://member.bilibili.com/',
- kuaishou: 'https://cp.kuaishou.com/',
- baijiahao: 'https://baijiahao.baidu.com/',
- };
- return referers[platform] || '';
- }
- /**
- * 通过浏览器检查 Cookie 是否有效(检查是否被重定向到登录页)
- * 注意:网络错误或服务不可用时返回 true(保持原状态),避免误判为过期
- */
- private async checkCookieValidByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- // 对于抖音平台,使用 check/user 接口检查
- if (platform === 'douyin') {
- return this.checkDouyinLoginByApi(cookies);
- }
- const browser = await chromium.launch({ headless: true });
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- const config = this.getPlatformConfig(platform);
- // 访问平台主页
- await page.goto(config.homeUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- const url = page.url();
- logger.info(`Browser check cookie for ${platform}: URL=${url}`);
- // 检查是否被重定向到登录页
- const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));
- await page.close();
- await context.close();
- await browser.close();
- return !isLoginPage;
- } catch (error) {
- logger.error(`Browser check cookie error for ${platform}:`, error);
- await browser.close();
- // 网络错误或服务不可用时返回 true,避免误判为过期
- logger.warn(`[Browser] Check failed due to error, assuming valid to avoid false expiration`);
- return true;
- }
- }
- /**
- * 抖音登录状态检查 - 通过监听 check/user 接口
- * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
- */
- async checkDouyinLoginByApi(cookies: CookieData[]): Promise<boolean> {
- const browser = await chromium.launch({ headless: true });
- let isLoggedIn = false;
- let checkCompleted = false;
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- // 监听 check/user 接口响应
- page.on('response', async (response) => {
- const url = response.url();
- if (url.includes(DOUYIN_API.CHECK_USER)) {
- try {
- const data = await response.json();
- // result: true 表示已登录
- isLoggedIn = data?.result === true && data?.status_code === 0;
- checkCompleted = true;
- logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
- } catch {
- // 忽略解析错误
- }
- }
- });
- // 访问创作者首页,触发 check/user 接口
- await page.goto(DOUYIN_API.CREATOR_HOME, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待接口响应或超时
- const startTime = Date.now();
- while (!checkCompleted && Date.now() - startTime < 10000) {
- await page.waitForTimeout(500);
- }
- // 如果没有收到 check/user 响应,检查 URL 是否被重定向到登录页
- if (!checkCompleted) {
- const currentUrl = page.url();
- isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
- logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
- }
- await page.close();
- await context.close();
- await browser.close();
- return isLoggedIn;
- } catch (error) {
- logger.error('[Douyin] checkDouyinLoginByApi error:', error);
- try {
- await browser.close();
- } catch { }
- // 网络错误或服务不可用时返回 true,避免误判为过期
- logger.warn(`[Douyin] Check failed due to error, assuming valid to avoid false expiration`);
- return true;
- }
- }
- /**
- * 访问平台后台页面并截图(用于 AI 分析)
- * @param platform 平台类型
- * @param cookies Cookie 数据
- * @returns Base64 编码的截图,失败返回 null
- */
- async capturePageScreenshot(platform: PlatformType, cookies: CookieData[]): Promise<string | null> {
- const browser = await chromium.launch({ headless: true });
-
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
-
- await context.addCookies(cookies);
- const page = await context.newPage();
-
- const config = this.getPlatformConfig(platform);
-
- logger.info(`[Screenshot] Navigating to ${platform} home page: ${config.homeUrl}`);
-
- // 访问平台主页
- await page.goto(config.homeUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
-
- // 等待页面加载
- await page.waitForTimeout(3000);
-
- const url = page.url();
- logger.info(`[Screenshot] Current URL: ${url}`);
-
- // 截图
- const screenshotBuffer = await page.screenshot({
- type: 'jpeg',
- quality: 80,
- fullPage: false,
- });
-
- const base64Screenshot = screenshotBuffer.toString('base64');
-
- await page.close();
- await context.close();
- await browser.close();
-
- logger.info(`[Screenshot] Captured screenshot for ${platform}, size: ${Math.round(base64Screenshot.length / 1024)}KB`);
-
- return base64Screenshot;
- } catch (error) {
- logger.error(`[Screenshot] Failed to capture screenshot for ${platform}:`, error);
- try {
- await browser.close();
- } catch { /* ignore */ }
- return null;
- }
- }
- /**
- * 检查 Python 服务是否可用
- */
- private async checkPythonServiceAvailable(): Promise<boolean> {
- try {
- const response = await fetch(`${PYTHON_SERVICE_URL}/health`, {
- method: 'GET',
- signal: AbortSignal.timeout(3000),
- });
- return response.ok;
- } catch {
- return false;
- }
- }
- /**
- * 通过 Python API 获取作品列表
- */
- private async fetchWorksViaPython(platform: PlatformType, cookies: CookieData[]): Promise<WorkItem[]> {
- logger.info(`[Python API] Fetching works for ${platform}...`);
- // 将 cookies 转换为字符串格式
- const cookieString = JSON.stringify(cookies);
- // Python 服务中视频号的 platform 名称是 weixin
- const pythonPlatform = platform === 'weixin_video' ? 'weixin' : platform;
- const response = await fetch(`${PYTHON_SERVICE_URL}/works`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- platform: pythonPlatform,
- cookie: cookieString,
- page: 0,
- page_size: 50,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API returned ${response.status}`);
- }
- const result = await response.json();
- if (!result.success) {
- throw new Error(result.error || 'Failed to get works');
- }
- logger.info(`[Python API] Got ${result.works?.length || 0} works for ${platform}`);
- // 转换数据格式
- return (result.works || []).map((work: {
- work_id: string;
- title: string;
- cover_url: string;
- duration: number;
- publish_time: string;
- status: string;
- play_count: number;
- like_count: number;
- comment_count: number;
- share_count: number;
- collect_count?: number;
- }) => ({
- videoId: work.work_id,
- title: work.title,
- coverUrl: work.cover_url,
- duration: String(work.duration || 0),
- publishTime: work.publish_time,
- status: work.status || 'published',
- playCount: work.play_count || 0,
- likeCount: work.like_count || 0,
- commentCount: work.comment_count || 0,
- shareCount: work.share_count || 0,
- }));
- }
- /**
- * 获取账号信息(优先使用 Python API,回退到无头浏览器)
- */
- async fetchAccountInfo(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
- logger.info(`[fetchAccountInfo] Starting for platform: ${platform}`);
-
- // 百家号使用直接 API 获取账号信息和作品列表
- if (platform === 'baijiahao') {
- logger.info(`[fetchAccountInfo] Using direct API for baijiahao`);
- return this.fetchBaijiahaoAccountInfoDirectApi(cookies);
- }
- // 对于支持的平台,尝试使用 Python API 获取作品列表和账号信息
- const supportedPlatforms: PlatformType[] = ['douyin', 'xiaohongshu', 'kuaishou', 'weixin_video'];
- if (supportedPlatforms.includes(platform)) {
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info(`[Python API] Service available, trying to fetch works for ${platform}`);
- try {
- const worksList = await this.fetchWorksViaPython(platform, cookies);
- // 如果成功获取到作品,使用 Playwright 获取账号基本信息
- if (worksList.length > 0) {
- logger.info(`[Python API] Successfully fetched ${worksList.length} works for ${platform}`);
- try {
- const accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- accountInfo.worksList = worksList;
- // 直接使用 Python API 获取的作品数量(最准确,排除了已删除/私密视频)
- accountInfo.worksCount = worksList.length;
- logger.info(`[fetchAccountInfo] Using Python API works count for ${platform}: ${accountInfo.worksCount}`);
- return accountInfo;
- } catch (playwrightError) {
- logger.warn(`[Playwright] Failed to get account info for ${platform}:`, playwrightError);
- const accountInfo = this.getDefaultAccountInfo(platform);
- accountInfo.worksList = worksList;
- accountInfo.worksCount = worksList.length;
- return accountInfo;
- }
- }
- // 作品列表为空,尝试用 Playwright 获取账号信息
- logger.info(`[Python API] Got empty works list for ${platform}, trying Playwright`);
- } catch (pythonError) {
- logger.warn(`[Python API] Failed to fetch works for ${platform}:`, pythonError);
- }
- } else {
- logger.info(`[Python API] Service not available for ${platform}`);
- }
- }
- // 使用 Playwright 获取账号信息
- logger.info(`[Playwright] Fetching account info for ${platform}`);
- return this.fetchAccountInfoWithPlaywright(platform, cookies);
- }
- /**
- * 使用 Playwright 获取账号信息(原方法)
- */
- private async fetchAccountInfoWithPlaywright(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
- const browser = await chromium.launch({ headless: true });
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- let accountInfo: AccountInfo;
- switch (platform) {
- case 'douyin':
- accountInfo = await this.fetchDouyinAccountInfo(page, context, cookies);
- break;
- case 'bilibili':
- accountInfo = await this.fetchBilibiliAccountInfo(page, context, cookies);
- break;
- case 'kuaishou':
- accountInfo = await this.fetchKuaishouAccountInfo(page, context, cookies);
- break;
- case 'xiaohongshu':
- accountInfo = await this.fetchXiaohongshuAccountInfo(page, context, cookies);
- break;
- case 'weixin_video':
- accountInfo = await this.fetchWeixinVideoAccountInfo(page, context, cookies);
- break;
- default:
- accountInfo = this.getDefaultAccountInfo(platform);
- }
- await page.close();
- await context.close();
- await browser.close();
- return accountInfo;
- } catch (error) {
- logger.error('HeadlessBrowser fetchAccountInfo error:', error);
- await browser.close();
- return this.getDefaultAccountInfo(platform);
- }
- }
- /**
- * 获取抖音账号信息 - 通过 API 方式获取
- * 1. 监听 check/user 接口验证登录状态
- * 2. 通过 work_list API 获取作品数和作品列表
- */
- private async fetchDouyinAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `douyin_${Date.now()}`;
- let accountName = '抖音账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- let worksList: WorkItem[] = [];
- let isLoggedIn = false;
- // 用于存储从 API 捕获的数据
- const capturedData: {
- userInfo?: {
- nickname?: string;
- avatar?: string;
- uid?: string;
- sec_uid?: string;
- unique_id?: string; // 抖音号(如 Ethanfly9392)
- short_id?: string; // 短ID
- follower_count?: number;
- };
- worksList?: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- duration: number;
- createTime: number;
- statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number };
- }>;
- total?: number;
- } = {};
- try {
- // 从 Cookie 获取用户 ID
- const uidCookie = cookies.find(c =>
- ['passport_uid', 'uid', 'ssid'].includes(c.name)
- );
- if (uidCookie?.value) {
- accountId = `douyin_${uidCookie.value}`;
- }
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听 check/user 接口 - 验证登录状态
- if (url.includes(DOUYIN_API.CHECK_USER)) {
- const data = await response.json();
- isLoggedIn = data?.result === true && data?.status_code === 0;
- logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
- }
- // 监听 work_list 接口 - 获取作品列表
- if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
- const data = await response.json();
- if (data?.aweme_list && data.aweme_list.length > 0) {
- // 优先从 author.aweme_count 获取真实的作品数(最准确)
- const firstAweme = data.aweme_list[0];
- const authorAwemeCount = firstAweme?.author?.aweme_count;
- if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
- capturedData.total = authorAwemeCount;
- logger.info(`[Douyin API] Using author.aweme_count as works count: ${authorAwemeCount}`);
- } else {
- // 备用方案:使用 items 数组长度
- const itemsCount = data?.items?.length || 0;
- if (itemsCount > 0) {
- capturedData.total = (capturedData.total || 0) + itemsCount;
- } else {
- // 如果没有 items,使用 aweme_list 长度
- capturedData.total = (capturedData.total || 0) + data.aweme_list.length;
- }
- }
- // 解析作品列表
- capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
- const statistics = aweme.statistics as Record<string, unknown> || {};
- const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
- const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';
- return {
- awemeId: String(aweme.aweme_id || ''),
- title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
- coverUrl,
- duration: Number(aweme.duration || 0),
- createTime: Number(aweme.create_time || 0),
- statistics: {
- play_count: Number(statistics.play_count || 0),
- digg_count: Number(statistics.digg_count || 0),
- comment_count: Number(statistics.comment_count || 0),
- share_count: Number(statistics.share_count || 0),
- },
- };
- });
- logger.info(`[Douyin API] work_list: itemsCount=${capturedData.total}, aweme_list_length=${capturedData.worksList?.length}`);
- }
- }
- // 监听账号信息接口 - 增加更多可能的接口
- if (url.includes('/account_base_info') ||
- url.includes('/user/info') ||
- url.includes('/creator/user') ||
- url.includes('/data/overview') ||
- url.includes('/creator-micro/data') ||
- url.includes('/home_data')) {
- const data = await response.json();
- logger.info(`[Douyin API] Captured response from: ${url.split('?')[0]}`);
- // 尝试多种数据结构
- const user = data?.user || data?.data?.user || data?.data || data;
- if (user) {
- const nickname = user.nickname || user.name || user.nick_name || user.user_name;
- const avatar = user.avatar_url || user.avatar_thumb?.url_list?.[0] || user.avatar || user.avatar_larger?.url_list?.[0];
- const uid = user.uid || user.user_id || user.id;
- const fans = user.follower_count || user.fans_count || user.mplatform_followers_count;
- // 获取抖音号(unique_id 或 short_id)
- const uniqueId = user.unique_id || user.short_id || user.douyin_id;
- if (nickname || uid || uniqueId) {
- capturedData.userInfo = {
- nickname: nickname,
- avatar: avatar,
- uid: uid,
- sec_uid: user.sec_uid,
- unique_id: uniqueId,
- short_id: user.short_id,
- follower_count: fans,
- };
- logger.info(`[Douyin API] user info captured: nickname=${capturedData.userInfo.nickname}, uid=${capturedData.userInfo.uid}, unique_id=${capturedData.userInfo.unique_id}`);
- }
- }
- }
- } catch (e) {
- // 忽略非 JSON 响应
- }
- });
- // 访问主页获取基本信息并触发 check/user 接口
- logger.info('[Douyin] Navigating to creator home...');
- await page.goto(DOUYIN_API.CREATOR_HOME, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待页面加载完成
- await page.waitForTimeout(3000);
- // 尝试等待网络空闲
- try {
- await page.waitForLoadState('networkidle', { timeout: 10000 });
- } catch {
- // 超时继续
- }
- // 额外等待确保 API 响应被捕获
- await page.waitForTimeout(2000);
- // 检查登录状态 - 如果没有从 API 获取到,通过 URL 判断
- if (!isLoggedIn) {
- const currentUrl = page.url();
- isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
- }
- if (!isLoggedIn) {
- logger.warn('[Douyin] Not logged in, returning default account info');
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- }
- // 从页面提取基本账号信息(作为 API 数据的补充)
- const accountData = await page.evaluate(() => {
- const result: { name?: string; avatar?: string; fans?: number; douyinId?: string } = {};
- // 提取抖音号 - 多种方式
- // 方式1:通过选择器查找包含抖音号的元素
- const uniqueIdSelectors = [
- 'div[class*="unique"]',
- 'span[class*="unique"]',
- 'div[class*="douyin-id"]',
- 'span[class*="douyin-id"]',
- '[class*="account-id"]',
- '[class*="shortId"]',
- '[class*="short-id"]',
- ];
- for (const selector of uniqueIdSelectors) {
- const el = document.querySelector(selector);
- if (el) {
- const text = el.textContent?.trim() || '';
- const match = text.match(/抖音号[::]\s*(\S+)/) || text.match(/ID[::]\s*(\S+)/);
- if (match) {
- result.douyinId = match[1];
- break;
- }
- // 如果元素文本本身就是抖音号(无前缀)
- if (text && !text.includes('抖音号') && /^[a-zA-Z0-9_]+$/.test(text)) {
- result.douyinId = text;
- break;
- }
- }
- }
- // 方式2:全局搜索包含"抖音号"的文本
- if (!result.douyinId) {
- const allElements = Array.from(document.querySelectorAll('span, div, p'));
- for (const el of allElements) {
- const text = el.textContent?.trim() || '';
- // 匹配 "抖音号:xxx" 或 "抖音号: xxx"
- const match = text.match(/抖音号[::]\s*([a-zA-Z0-9_]+)/);
- if (match && match[1]) {
- result.douyinId = match[1];
- break;
- }
- }
- }
- // 查找头像 - 优先使用头像容器
- const avatarSelectors = [
- '[class*="avatar"] img',
- '[class*="user-avatar"] img',
- '[class*="profile"] img',
- 'img[class*="avatar"]',
- ];
- for (const selector of avatarSelectors) {
- const img = document.querySelector(selector) as HTMLImageElement;
- if (img?.src && (img.src.includes('aweme') || img.src.includes('douyinpic') || img.src.includes('bytedance'))) {
- result.avatar = img.src;
- break;
- }
- }
- // 备用方案:查找所有图片
- if (!result.avatar) {
- const avatarImgs = Array.from(document.querySelectorAll('img'));
- for (const img of avatarImgs) {
- const src = img.src || img.getAttribute('src') || '';
- if (src && (src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance'))) {
- const rect = img.getBoundingClientRect();
- if (rect.width > 30 && rect.width < 150 && rect.top < 300) {
- result.avatar = src;
- break;
- }
- }
- }
- }
- // 获取粉丝数 - 多种选择器
- const fansSelectors = [
- '#guide_home_fans',
- '[class*="fans"]',
- '[class*="follower"]',
- '[class*="data-item"]',
- ];
- for (const selector of fansSelectors) {
- const el = document.querySelector(selector);
- if (el) {
- const text = el.textContent?.trim() || '';
- // 匹配 "123" 或 "1.2万" 或 "粉丝 123"
- const match = text.match(/(\d+(?:\.\d+)?)\s*([万wW])?/);
- if (match) {
- let num = parseFloat(match[1]);
- if (match[2]) num *= 10000;
- result.fans = Math.floor(num);
- break;
- }
- }
- }
- // 查找用户名 - 更精确的选择器
- const nameSelectors = [
- '[class*="user-name"]',
- '[class*="nickname"]',
- '[class*="author-name"]',
- '[class*="profile-name"]',
- 'h1[class*="name"]',
- 'h2[class*="name"]',
- ];
- for (const selector of nameSelectors) {
- const el = document.querySelector(selector);
- if (el) {
- const text = el.textContent?.trim() || '';
- if (text && text.length >= 2 && text.length <= 30) {
- result.name = text;
- break;
- }
- }
- }
- // 备用方案:查找包含名字的容器
- if (!result.name) {
- const nameContainers = Array.from(document.querySelectorAll('[class*="name"], [class*="nick"], [class*="user"]'));
- for (const container of nameContainers) {
- const text = container.textContent?.trim() || '';
- if (text &&
- text.length >= 2 &&
- text.length <= 20 &&
- !text.includes('关注') &&
- !text.includes('粉丝') &&
- !text.includes('获赞') &&
- !text.includes('加载') &&
- !text.includes('创作') &&
- !text.includes('发布') &&
- !text.includes('抖音号') &&
- !text.match(/^\d+$/)) {
- const rect = container.getBoundingClientRect();
- if (rect.top < 400 && rect.left < 500) {
- result.name = text;
- break;
- }
- }
- }
- }
- return result;
- });
- // 优先使用抖音号作为 ID(unique_id),其次是页面提取的抖音号,最后是 uid
- if (capturedData.userInfo?.unique_id) {
- // 优先使用抖音号(如 Ethanfly9392)
- accountId = `douyin_${capturedData.userInfo.unique_id}`;
- logger.info(`[Douyin] Using unique_id as accountId: ${accountId}`);
- } else if (capturedData.userInfo?.short_id) {
- // 其次使用短ID
- accountId = `douyin_${capturedData.userInfo.short_id}`;
- logger.info(`[Douyin] Using short_id as accountId: ${accountId}`);
- } else if (accountData.douyinId) {
- // 使用页面提取的抖音号
- accountId = `douyin_${accountData.douyinId}`;
- logger.info(`[Douyin] Using page douyinId as accountId: ${accountId}`);
- } else if (capturedData.userInfo?.uid) {
- // 最后使用内部uid
- accountId = `douyin_${capturedData.userInfo.uid}`;
- logger.info(`[Douyin] Using uid as accountId: ${accountId}`);
- }
- accountName = capturedData.userInfo?.nickname || accountData.name || accountName;
- avatarUrl = capturedData.userInfo?.avatar || accountData.avatar || avatarUrl;
- fansCount = capturedData.userInfo?.follower_count || accountData.fans || fansCount;
- // 通过 API 获取作品列表
- logger.info('[Douyin] Fetching works via API...');
- const apiResult = await this.fetchWorksDirectApi(page);
- if (apiResult.works.length > 0) {
- // 使用 items 累计数量作为作品数(apiResult.total 现在是累计的 items.length)
- // 如果 total 为 0,则使用 works 列表长度
- worksCount = apiResult.total > 0 ? apiResult.total : apiResult.works.length;
- worksList = apiResult.works.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- duration: '00:00',
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: 0,
- likeCount: 0,
- commentCount: w.commentCount,
- shareCount: 0,
- }));
- logger.info(`[Douyin] Got ${apiResult.works.length} works from API, total count: ${worksCount}`);
- } else if (capturedData.worksList && capturedData.worksList.length > 0) {
- // 如果直接 API 调用失败,使用监听到的数据
- worksCount = capturedData.total || capturedData.worksList.length;
- worksList = capturedData.worksList.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- duration: this.formatDuration(w.duration),
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: w.statistics.play_count,
- likeCount: w.statistics.digg_count,
- commentCount: w.statistics.comment_count,
- shareCount: w.statistics.share_count,
- }));
- logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
- }
- } catch (error) {
- logger.warn('Failed to fetch Douyin account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- }
- /**
- * 格式化视频时长
- */
- private formatDuration(ms: number): string {
- if (!ms) return '00:00';
- const seconds = Math.floor(ms / 1000);
- const minutes = Math.floor(seconds / 60);
- const remainingSeconds = seconds % 60;
- return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
- }
- /**
- * 获取B站账号信息
- */
- private async fetchBilibiliAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `bilibili_${Date.now()}`;
- let accountName = 'B站账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- try {
- const uidCookie = cookies.find(c => c.name === 'DedeUserID');
- if (uidCookie?.value) {
- accountId = `bilibili_${uidCookie.value}`;
- }
- await page.goto('https://member.bilibili.com/platform/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 获取用户名
- const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
- if (nameEl) {
- const text = await nameEl.textContent();
- if (text?.trim()) {
- accountName = text.trim();
- }
- }
- // 获取头像
- const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
- if (avatarEl) {
- const src = await avatarEl.getAttribute('src');
- if (src) {
- avatarUrl = src;
- }
- }
- } catch (error) {
- logger.warn('Failed to fetch Bilibili account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取快手账号信息
- */
- private async fetchKuaishouAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `kuaishou_${Date.now()}`;
- let accountName = '快手账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- try {
- const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
- if (uidCookie?.value) {
- accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
- }
- await page.goto('https://cp.kuaishou.com/profile', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 获取用户名
- const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
- if (nameEl) {
- const text = await nameEl.textContent();
- if (text?.trim()) {
- accountName = text.trim();
- }
- }
- // 获取头像
- const avatarEl = await page.$('[class*="avatar"] img');
- if (avatarEl) {
- const src = await avatarEl.getAttribute('src');
- if (src) {
- avatarUrl = src;
- }
- }
- } catch (error) {
- logger.warn('Failed to fetch Kuaishou account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取微信视频号账号信息
- */
- private async fetchWeixinVideoAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `weixin_video_${Date.now()}`;
- let accountName = '视频号账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- let finderId = '';
- try {
- // 从 Cookie 中提取用户标识
- // 优先使用 finder_username(视频号唯一标识)
- const finderUsernameCookie = cookies.find(c => c.name === 'finder_username');
- if (finderUsernameCookie?.value) {
- finderId = finderUsernameCookie.value;
- accountId = `weixin_video_${finderId}`;
- logger.info(`[WeixinVideo] Found finder_username from cookie: ${finderId}`);
- }
- // 备选:使用 wxuin 或 uin
- if (!finderId) {
- const uinCookie = cookies.find(c => c.name === 'wxuin' || c.name === 'uin');
- if (uinCookie?.value) {
- // 仍然保持时间戳格式,后续会尝试从页面获取真实 ID
- accountId = `weixin_video_${uinCookie.value}`;
- logger.info(`[WeixinVideo] Using uin from cookie: ${uinCookie.value}`);
- }
- }
- // 访问视频号创作者平台首页
- await page.goto('https://channels.weixin.qq.com/platform/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[WeixinVideo] Cookie expired, needs login');
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- // 从页面提取账号信息
- const accountData = await page.evaluate(() => {
- const result: { name?: string; avatar?: string; fans?: number; works?: number; finderId?: string } = {};
- try {
- // ===== 1. 优先使用精确选择器获取视频号 ID =====
- // 方法1: 通过 #finder-uid-copy 的 data-clipboard-text 属性获取
- const finderIdCopyEl = document.querySelector('#finder-uid-copy');
- if (finderIdCopyEl) {
- const clipboardText = finderIdCopyEl.getAttribute('data-clipboard-text');
- if (clipboardText && clipboardText.length >= 10) {
- result.finderId = clipboardText;
- console.log('[WeixinVideo] Found finder ID from data-clipboard-text:', result.finderId);
- } else {
- // 备选:获取元素文本内容
- const text = finderIdCopyEl.textContent?.trim();
- if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
- result.finderId = text;
- console.log('[WeixinVideo] Found finder ID from #finder-uid-copy text:', result.finderId);
- }
- }
- }
-
- // 方法2: 通过 .finder-uniq-id 选择器获取
- if (!result.finderId) {
- const finderUniqIdEl = document.querySelector('.finder-uniq-id');
- if (finderUniqIdEl) {
- const clipboardText = finderUniqIdEl.getAttribute('data-clipboard-text');
- if (clipboardText && clipboardText.length >= 10) {
- result.finderId = clipboardText;
- console.log('[WeixinVideo] Found finder ID from .finder-uniq-id data-clipboard-text:', result.finderId);
- } else {
- const text = finderUniqIdEl.textContent?.trim();
- if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
- result.finderId = text;
- console.log('[WeixinVideo] Found finder ID from .finder-uniq-id text:', result.finderId);
- }
- }
- }
- }
-
- // 方法3: 从页面文本中正则匹配
- if (!result.finderId) {
- const bodyText = document.body.innerText || '';
- const finderIdPatterns = [
- /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
- /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
- ];
- for (const pattern of finderIdPatterns) {
- const match = bodyText.match(pattern);
- if (match && match[1] && match[1].length >= 10) {
- result.finderId = match[1];
- console.log('[WeixinVideo] Found finder ID from regex:', result.finderId);
- break;
- }
- }
- }
-
- // ===== 2. 获取账号名称 =====
- // 优先使用 h2.finder-nickname
- const nicknameEl = document.querySelector('h2.finder-nickname') ||
- document.querySelector('.finder-nickname');
- if (nicknameEl) {
- const text = nicknameEl.textContent?.trim();
- if (text && text.length >= 2 && text.length <= 30) {
- result.name = text;
- console.log('[WeixinVideo] Found name from .finder-nickname:', result.name);
- }
- }
-
- // 备选选择器
- if (!result.name) {
- const nameSelectors = [
- '.account-name',
- '[class*="nickname"]',
- '[class*="userName"]',
- ];
- for (const selector of nameSelectors) {
- const el = document.querySelector(selector);
- const text = el?.textContent?.trim();
- if (text && text.length >= 2 && text.length <= 30) {
- result.name = text;
- console.log('[WeixinVideo] Found name from selector:', selector, result.name);
- break;
- }
- }
- }
- // ===== 3. 获取头像 =====
- // 优先使用 img.avatar
- const avatarEl = document.querySelector('img.avatar') as HTMLImageElement;
- if (avatarEl?.src && avatarEl.src.startsWith('http')) {
- result.avatar = avatarEl.src;
- console.log('[WeixinVideo] Found avatar from img.avatar:', result.avatar);
- }
-
- // 备选选择器
- if (!result.avatar) {
- const avatarSelectors = [
- '.finder-info-container img.avatar',
- 'img[alt="视频号头像"]',
- 'img[src*="wx.qlogo.cn/finderhead"]',
- 'img[src*="wx.qlogo"]',
- ];
- for (const selector of avatarSelectors) {
- const el = document.querySelector(selector) as HTMLImageElement;
- if (el?.src && el.src.startsWith('http')) {
- result.avatar = el.src;
- console.log('[WeixinVideo] Found avatar from selector:', selector);
- break;
- }
- }
- }
- // ===== 4. 获取视频数和关注者数 =====
- // 使用 .finder-content-info 中的 .finder-info-num
- const contentInfo = document.querySelector('.finder-content-info');
- if (contentInfo) {
- const infoDivs = contentInfo.querySelectorAll('div');
- infoDivs.forEach(div => {
- const text = div.textContent || '';
- const numEl = div.querySelector('.finder-info-num');
- if (numEl) {
- const num = parseInt(numEl.textContent?.trim() || '0', 10);
- if (text.includes('视频') || text.includes('作品')) {
- result.works = num;
- console.log('[WeixinVideo] Found works from .finder-info-num:', result.works);
- } else if (text.includes('关注者') || text.includes('粉丝')) {
- result.fans = num;
- console.log('[WeixinVideo] Found fans from .finder-info-num:', result.fans);
- }
- }
- });
- }
-
- // 备选:从页面整体文本中匹配
- if (result.fans === undefined || result.works === undefined) {
- const bodyText = document.body.innerText || '';
-
- if (result.fans === undefined) {
- const fansMatch = bodyText.match(/关注者\s*(\d+(?:\.\d+)?[万wW]?)/) ||
- bodyText.match(/粉丝\s*(\d+(?:\.\d+)?[万wW]?)/);
- if (fansMatch) {
- let count = parseFloat(fansMatch[1]);
- if (fansMatch[1].includes('万') || fansMatch[1].toLowerCase().includes('w')) {
- count = count * 10000;
- }
- result.fans = Math.floor(count);
- console.log('[WeixinVideo] Found fans from text:', result.fans);
- }
- }
-
- if (result.works === undefined) {
- const worksMatch = bodyText.match(/视频\s*(\d+)/) ||
- bodyText.match(/作品\s*(\d+)/);
- if (worksMatch) {
- result.works = parseInt(worksMatch[1], 10);
- console.log('[WeixinVideo] Found works from text:', result.works);
- }
- }
- }
- } catch (e) {
- console.error('[WeixinVideo] Extract error:', e);
- }
- return result;
- });
- logger.info(`[WeixinVideo] Extracted account data from home page:`, accountData);
- // 更新账号信息
- if (accountData.name) {
- accountName = accountData.name;
- }
- if (accountData.avatar) {
- avatarUrl = accountData.avatar;
- }
- if (accountData.fans !== undefined) {
- fansCount = accountData.fans;
- }
- if (accountData.works !== undefined) {
- worksCount = accountData.works;
- }
- if (accountData.finderId) {
- finderId = accountData.finderId;
- accountId = `weixin_video_${accountData.finderId}`;
- }
- // 如果首页没有获取到视频号 ID,尝试访问账号设置页面
- if (!finderId || finderId.length < 10) {
- logger.info('[WeixinVideo] Finder ID not found on home page, trying account settings page...');
-
- try {
- // 访问账号设置页面
- await page.goto('https://channels.weixin.qq.com/platform/account', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
-
- // 从账号设置页面提取视频号 ID
- const settingsData = await page.evaluate(() => {
- const result: { finderId?: string; name?: string } = {};
- const bodyText = document.body.innerText || '';
-
- // 尝试多种匹配模式
- const patterns = [
- /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
- /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
- /视频号[::\s]+([a-zA-Z0-9_]{10,})/,
- /Finder\s*ID[::\s]*([a-zA-Z0-9_]+)/i,
- /finder_username[::\s]*([a-zA-Z0-9_]+)/i,
- /唯一标识[::\s]*([a-zA-Z0-9_]+)/,
- ];
-
- for (const pattern of patterns) {
- const match = bodyText.match(pattern);
- if (match && match[1]) {
- result.finderId = match[1];
- console.log('[WeixinVideo] Found finder ID from settings page:', result.finderId);
- break;
- }
- }
-
- // 从元素中查找
- if (!result.finderId) {
- const idSelectors = [
- '[class*="finder-id"]',
- '[class*="account-id"]',
- '[class*="unique-id"]',
- '.finder-uniq-id',
- 'span.finder-uniq-id',
- '[class*="copy-id"]',
- ];
- for (const selector of idSelectors) {
- const el = document.querySelector(selector);
- const text = el?.textContent?.trim();
- if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10 && text.length <= 30) {
- result.finderId = text;
- console.log('[WeixinVideo] Found ID from settings selector:', result.finderId);
- break;
- }
- }
- }
-
- return result;
- });
-
- logger.info(`[WeixinVideo] Extracted data from settings page:`, settingsData);
-
- if (settingsData.finderId) {
- finderId = settingsData.finderId;
- accountId = `weixin_video_${settingsData.finderId}`;
- }
- } catch (settingsError) {
- logger.warn('[WeixinVideo] Failed to fetch from settings page:', settingsError);
- }
- }
- logger.info(`[WeixinVideo] Final account info: id=${accountId}, name=${accountName}, avatar=${avatarUrl ? 'yes' : 'no'}, fans=${fansCount}`);
- } catch (error) {
- logger.warn('Failed to fetch WeixinVideo account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取小红书账号信息 - 通过 API 方式获取
- */
- private async fetchXiaohongshuAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `xiaohongshu_${Date.now()}`;
- let accountName = '小红书账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- // 用于存储捕获的数据
- const capturedData: {
- userInfo?: {
- nickname?: string;
- avatar?: string;
- userId?: string;
- redId?: string;
- fans?: number;
- notes?: number;
- };
- } = {};
- try {
- // 从 Cookie 获取用户 ID
- const userIdCookie = cookies.find(c =>
- c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
- );
- if (userIdCookie?.value) {
- accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
- }
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听用户信息 API
- if (url.includes('/api/galaxy/creator/home/personal_info') ||
- url.includes('/api/sns/web/v1/user/selfinfo') ||
- url.includes('/user/selfinfo')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));
- // 解析用户信息
- const userInfo = data?.data?.user_info || data?.data || data;
- if (userInfo) {
- capturedData.userInfo = {
- nickname: userInfo.nickname || userInfo.name || userInfo.userName,
- avatar: userInfo.image || userInfo.avatar || userInfo.images,
- userId: userInfo.user_id || userInfo.userId,
- redId: userInfo.red_id || userInfo.redId,
- fans: userInfo.fans || userInfo.fansCount,
- notes: userInfo.notes || userInfo.noteCount,
- };
- logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
- }
- }
- // 监听创作者主页数据
- if (url.includes('/api/galaxy/creator/home/home_page') ||
- url.includes('/api/galaxy/creator/data')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));
- if (data?.data) {
- const homeData = data.data;
- // 获取粉丝数和笔记数
- if (homeData.fans_count !== undefined) {
- capturedData.userInfo = capturedData.userInfo || {};
- capturedData.userInfo.fans = homeData.fans_count;
- }
- if (homeData.note_count !== undefined) {
- capturedData.userInfo = capturedData.userInfo || {};
- capturedData.userInfo.notes = homeData.note_count;
- }
- }
- }
- } catch {
- // 忽略非 JSON 响应
- }
- });
- // 导航到小红书创作者中心
- logger.info('[Xiaohongshu] Navigating to creator center...');
- await page.goto('https://creator.xiaohongshu.com/creator/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Xiaohongshu] Cookie expired, needs login');
- return this.getDefaultAccountInfo('xiaohongshu');
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 如果 API 没有捕获到数据,尝试从页面提取
- if (!capturedData.userInfo?.nickname) {
- logger.info('[Xiaohongshu] API did not return data, extracting from page...');
- // 尝试获取用户名
- const nameSelectors = [
- '[class*="nickname"]',
- '[class*="user-name"]',
- '[class*="userName"]',
- '.user-info .name',
- '[class*="creator"] [class*="name"]',
- ];
- for (const selector of nameSelectors) {
- const el = await page.$(selector);
- if (el) {
- const text = await el.textContent();
- if (text?.trim() && text.trim().length < 50) {
- accountName = text.trim();
- logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
- break;
- }
- }
- }
- // 尝试获取头像
- const avatarSelectors = [
- '[class*="avatar"] img',
- '[class*="user-avatar"] img',
- '.user-info img',
- '[class*="creator"] img[src*="sns"]',
- ];
- for (const selector of avatarSelectors) {
- const el = await page.$(selector);
- if (el) {
- const src = await el.getAttribute('src');
- if (src && src.startsWith('http')) {
- avatarUrl = src;
- logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
- break;
- }
- }
- }
- // 尝试获取粉丝数
- const statsText = await page.textContent('body');
- const fansMatch = statsText?.match(/粉丝[::\s]*(\d+(?:\.\d+)?[万亿]?)/);
- if (fansMatch) {
- fansCount = this.parseChineseNumber(fansMatch[1]);
- logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
- }
- const notesMatch = statsText?.match(/笔记[::\s]*(\d+)/);
- if (notesMatch) {
- worksCount = parseInt(notesMatch[1], 10);
- logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
- }
- }
- // 使用捕获的数据
- if (capturedData.userInfo) {
- if (capturedData.userInfo.nickname) {
- accountName = capturedData.userInfo.nickname;
- }
- if (capturedData.userInfo.avatar) {
- avatarUrl = capturedData.userInfo.avatar;
- }
- // 优先使用小红书号(redId)作为 accountId
- if (capturedData.userInfo.redId) {
- accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
- logger.info(`[Xiaohongshu] Using redId as accountId: ${accountId}`);
- } else if (capturedData.userInfo.userId) {
- accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
- }
- if (capturedData.userInfo.fans) {
- fansCount = capturedData.userInfo.fans;
- }
- if (capturedData.userInfo.notes) {
- worksCount = capturedData.userInfo.notes;
- }
- }
- // 如果还没获取到小红书号,尝试从页面文本中提取
- if (!accountId.match(/xiaohongshu_[a-zA-Z0-9_]+/) || accountId.includes('_' + Date.now().toString().slice(0, 8))) {
- const bodyText = await page.textContent('body');
- // 匹配小红书号格式:小红书号:xxxxxxx
- const xhsIdMatch = bodyText?.match(/小红书号[::]\s*([a-zA-Z0-9_]+)/) ||
- bodyText?.match(/红书号[::]\s*([a-zA-Z0-9_]+)/);
- if (xhsIdMatch) {
- accountId = `xiaohongshu_${xhsIdMatch[1]}`;
- logger.info(`[Xiaohongshu] Found 小红书号 from page text: ${accountId}`);
- }
- }
- logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
- // 获取作品列表 - 通过监听 API 接口
- const worksList: WorkItem[] = [];
- try {
- logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');
- // 存储所有捕获的笔记数据
- const allNotesData: Array<{
- noteId: string;
- title: string;
- coverUrl: string;
- status: number;
- publishTime: string;
- type: string;
- duration: number;
- likeCount: number;
- commentCount: number;
- collectCount: number;
- viewCount: number;
- shareCount: number;
- }> = [];
- let currentPage = 0;
- let hasMorePages = true;
- const maxPages = 20; // 最多获取20页,防止无限循环
- // 设置 API 响应监听器 - 在导航之前绑定
- let apiResponseReceived = false;
- let totalNotesCount = 0; // 从 tags 中获取的总作品数
- const notesApiHandler = async (response: import('playwright').Response) => {
- const url = response.url();
- try {
- // 监听小红书笔记列表 API
- // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
- if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
- url.includes('/api/sns/v5/creator/note/user/posted') ||
- url.includes('creator/note/user/posted')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);
- if ((data?.success || data?.code === 0) && data?.data) {
- apiResponseReceived = true;
- // 从 tags 中获取总作品数
- // tags 数组中 id="special.note_time_desc" 的项("所有笔记")包含总数
- if (data.data.tags && Array.isArray(data.data.tags)) {
- const allNotesTag = data.data.tags.find((tag: { id?: string; notes_count?: number }) =>
- tag.id === 'special.note_time_desc'
- );
- if (allNotesTag?.notes_count !== undefined) {
- totalNotesCount = allNotesTag.notes_count;
- logger.info(`[Xiaohongshu API] Total notes count from tags: ${totalNotesCount}`);
- }
- }
- const notes = data.data.notes || [];
- for (const note of notes) {
- // 根据 API 返回格式解析数据
- // images_list 是数组,第一个元素包含 url
- // 将 http:// 转换为 https:// 以确保图片能正常加载
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- logger.info(`[Xiaohongshu API] Note: id=${note.id}, title="${note.display_title}", cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
- allNotesData.push({
- noteId: note.id || '',
- title: note.display_title || '',
- coverUrl: coverUrl,
- status: note.tab_status || 1, // 1=已发布
- publishTime: note.time || '',
- type: note.type || 'normal', // video/normal
- duration: duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- // 检查是否还有更多页面
- // page=-1 表示没有更多数据
- if (data.data.page === -1 || notes.length === 0) {
- hasMorePages = false;
- logger.info(`[Xiaohongshu API] No more pages (page indicator: ${data.data.page})`);
- }
- } else {
- hasMorePages = false;
- }
- }
- } catch (e) {
- // 只在有相关 URL 时打印警告
- if (url.includes('creator/note')) {
- logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
- }
- }
- };
- // 先绑定监听器
- page.on('response', notesApiHandler);
- logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');
- // 导航到笔记管理页面 - 使用 domcontentloaded 加快加载,避免 networkidle 超时
- try {
- await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- } catch (navError) {
- // 导航超时不影响已捕获的 API 数据
- logger.warn('[Xiaohongshu] Navigation timeout, but API data may have been captured');
- }
- // 等待 API 响应
- await page.waitForTimeout(5000);
- logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);
- // 如果监听器没有捕获到数据,尝试直接调用 API
- if (allNotesData.length === 0) {
- logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');
- try {
- // 直接在页面上下文中调用 API
- const apiResponse = await page.evaluate(async () => {
- const response = await fetch('https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=0', {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return await response.json();
- });
- logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
- if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
- // 从 tags 中获取总作品数
- if (apiResponse.data.tags && Array.isArray(apiResponse.data.tags)) {
- const allNotesTag = apiResponse.data.tags.find((tag: { id?: string; notes_count?: number }) =>
- tag.id === 'special.note_time_desc'
- );
- if (allNotesTag?.notes_count !== undefined) {
- totalNotesCount = allNotesTag.notes_count;
- logger.info(`[Xiaohongshu API Direct] Total notes count from tags: ${totalNotesCount}`);
- }
- }
- const notes = apiResponse.data.notes || [];
- for (const note of notes) {
- // 将 http:// 转换为 https://
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- logger.info(`[Xiaohongshu API Direct] Note: id=${note.id}, cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
- allNotesData.push({
- noteId: note.id || '',
- title: note.display_title || '',
- coverUrl: coverUrl,
- status: note.tab_status || 1,
- publishTime: note.time || '',
- type: note.type || 'normal',
- duration: duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- // 获取更多页面
- let pageNum = 1;
- let lastPage = apiResponse.data.page;
- while (lastPage !== -1 && pageNum < maxPages) {
- const nextResponse = await page.evaluate(async (p) => {
- const response = await fetch(`https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}`, {
- method: 'GET',
- credentials: 'include',
- });
- return await response.json();
- }, pageNum);
- if (nextResponse?.data?.notes?.length > 0) {
- for (const note of nextResponse.data.notes) {
- // 将 http:// 转换为 https://
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- allNotesData.push({
- noteId: note.id || '',
- title: note.display_title || '',
- coverUrl: coverUrl,
- status: note.tab_status || 1,
- publishTime: note.time || '',
- type: note.type || 'normal',
- duration: duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- pageNum++;
- lastPage = nextResponse.data.page;
- if (lastPage === -1) break;
- } else {
- break;
- }
- }
- }
- } catch (apiError) {
- logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
- }
- }
- // 如果还是没有数据,尝试滚动加载
- if (allNotesData.length === 0) {
- logger.info('[Xiaohongshu] Still no notes, trying scroll to trigger API...');
- await page.waitForTimeout(2000);
- }
- // 滚动加载更多页面(如果通过监听器获取的数据)
- while (hasMorePages && currentPage < maxPages && allNotesData.length > 0 && apiResponseReceived) {
- currentPage++;
- const previousCount = allNotesData.length;
- // 滚动到页面底部触发加载更多
- await page.evaluate(() => {
- window.scrollTo(0, document.body.scrollHeight);
- });
- // 等待新数据加载
- await page.waitForTimeout(2000);
- // 如果没有新数据,退出循环
- if (allNotesData.length === previousCount) {
- logger.info(`[Xiaohongshu] No new notes loaded after scroll, stopping at page ${currentPage}`);
- break;
- }
- logger.info(`[Xiaohongshu] Page ${currentPage}: total ${allNotesData.length} notes`);
- }
- // 移除监听器
- page.off('response', notesApiHandler);
- logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);
- // 转换为 WorkItem 格式
- for (const note of allNotesData) {
- // 转换时长为 mm:ss 格式
- const minutes = Math.floor(note.duration / 60);
- const seconds = note.duration % 60;
- const durationStr = note.duration > 0
- ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
- : '';
- // 转换状态
- let statusStr = 'published';
- if (note.status === 0) statusStr = 'draft';
- else if (note.status === 2) statusStr = 'reviewing';
- else if (note.status === 3) statusStr = 'rejected';
- worksList.push({
- videoId: note.noteId,
- title: note.title || '无标题',
- coverUrl: note.coverUrl,
- duration: durationStr,
- publishTime: note.publishTime,
- status: statusStr,
- playCount: note.viewCount,
- likeCount: note.likeCount,
- commentCount: note.commentCount,
- shareCount: note.shareCount,
- });
- }
- logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);
- // 更新作品数:直接使用获取到的 notes 数量(更准确)
- // 只有当 notes 为空时才使用 tags 中的 notes_count
- if (worksList.length > 0) {
- worksCount = worksList.length;
- logger.info(`[Xiaohongshu] Using actual notes count: ${worksCount}`);
- } else if (totalNotesCount > 0) {
- worksCount = totalNotesCount;
- logger.info(`[Xiaohongshu] Using notes count from tags: ${worksCount}`);
- }
- } catch (worksError) {
- logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
- }
- logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- } catch (error) {
- logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 解析中文数字(如 1.2万 -> 12000)
- */
- private parseChineseNumber(str: string): number {
- if (!str) return 0;
- let num = parseFloat(str);
- if (str.includes('万')) {
- num *= 10000;
- } else if (str.includes('亿')) {
- num *= 100000000;
- }
- return Math.floor(num);
- }
- /**
- * 获取平台配置
- */
- private getPlatformConfig(platform: PlatformType) {
- const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
- douyin: {
- homeUrl: 'https://creator.douyin.com/creator-micro/home',
- loginIndicators: ['login', 'passport', 'sso'],
- },
- bilibili: {
- homeUrl: 'https://member.bilibili.com/platform/home',
- loginIndicators: ['passport.bilibili.com', 'login'],
- },
- kuaishou: {
- homeUrl: 'https://cp.kuaishou.com/profile',
- loginIndicators: ['passport.kuaishou.com', 'login'],
- },
- xiaohongshu: {
- homeUrl: 'https://creator.xiaohongshu.com/',
- loginIndicators: ['login', 'passport'],
- },
- weixin_video: {
- homeUrl: 'https://channels.weixin.qq.com/platform',
- loginIndicators: ['login', 'passport'],
- },
- baijiahao: {
- homeUrl: 'https://baijiahao.baidu.com/builder/rc/home',
- loginIndicators: ['login', 'passport'],
- },
- toutiao: {
- homeUrl: 'https://mp.toutiao.com/profile_v4/index',
- loginIndicators: ['login', 'passport', 'sso'],
- },
- weibo: {
- homeUrl: 'https://weibo.com/u/',
- loginIndicators: ['login', 'passport'],
- },
- dayu: {
- homeUrl: 'https://mp.dayu.com/',
- loginIndicators: ['login', 'passport'],
- },
- };
- return configs[platform] || { homeUrl: '', loginIndicators: ['login'] };
- }
- /**
- * 百家号 - 直接通过 API 获取账号信息和作品列表
- */
- private async fetchBaijiahaoAccountInfoDirectApi(cookies: CookieData[]): Promise<AccountInfo> {
- logger.info(`[Baijiahao API] Fetching account info via direct API...`);
-
- const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
- const headers = {
- 'Accept': 'application/json, text/plain, */*',
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Cookie': cookieString,
- 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
- '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',
- };
- let accountInfo: AccountInfo = this.getDefaultAccountInfo('baijiahao');
- try {
- // 1. 获取账号基本信息 (appinfo API)
- logger.info(`[Baijiahao API] Step 1: Fetching appinfo...`);
- const appInfoResponse = await fetch('https://baijiahao.baidu.com/builder/app/appinfo', {
- method: 'GET',
- headers,
- });
-
- if (!appInfoResponse.ok) {
- logger.error(`[Baijiahao API] appinfo request failed: ${appInfoResponse.status}`);
- throw new Error(`appinfo request failed: ${appInfoResponse.status}`);
- }
-
- const appInfoData = await appInfoResponse.json() as {
- errno?: number;
- errmsg?: string;
- data?: {
- user?: {
- name?: string;
- avatar?: string;
- app_id?: string | number;
- userid?: number;
- status?: string;
- };
- };
- };
-
- logger.info(`[Baijiahao API] appinfo response: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
-
- if (appInfoData.errno !== 0) {
- logger.error(`[Baijiahao API] appinfo API error: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
- throw new Error(`appinfo API error: ${appInfoData.errmsg || 'Unknown error'}`);
- }
-
- if (!appInfoData.data?.user) {
- logger.error(`[Baijiahao API] No user data in appinfo response`);
- throw new Error('No user data in appinfo response');
- }
-
- const user = appInfoData.data.user;
- accountInfo.accountId = user.app_id ? `bjh_${user.app_id}` : accountInfo.accountId;
- accountInfo.accountName = user.name || accountInfo.accountName;
- // 处理头像 URL(可能是相对路径)
- if (user.avatar) {
- accountInfo.avatarUrl = user.avatar.startsWith('http')
- ? user.avatar
- : `https:${user.avatar}`;
- }
- logger.info(`[Baijiahao API] Got account info: name=${accountInfo.accountName}, id=${accountInfo.accountId}, avatar=${accountInfo.avatarUrl}`);
- // 2. 获取粉丝数 (growthInfo API)
- logger.info(`[Baijiahao API] Step 2: Fetching growth info...`);
- try {
- const growthInfoResponse = await fetch('https://baijiahao.baidu.com/cms-ui/rights/growth/get_info', {
- method: 'GET',
- headers,
- });
-
- if (growthInfoResponse.ok) {
- const growthData = await growthInfoResponse.json() as {
- errno?: number;
- errmsg?: string;
- data?: {
- total_fans?: number;
- };
- };
-
- logger.info(`[Baijiahao API] growth info response: errno=${growthData.errno}`);
-
- if (growthData.errno === 0 && growthData.data) {
- accountInfo.fansCount = growthData.data.total_fans || 0;
- logger.info(`[Baijiahao API] Got fans count: ${accountInfo.fansCount}`);
- } else {
- logger.warn(`[Baijiahao API] growth info API error: errno=${growthData.errno}, errmsg=${growthData.errmsg}`);
- }
- } else {
- logger.warn(`[Baijiahao API] growth info request failed: ${growthInfoResponse.status}`);
- }
- } catch (growthError) {
- logger.warn(`[Baijiahao API] Failed to fetch growth info (non-critical):`, growthError);
- // 粉丝数获取失败不影响整体流程
- }
- // 3. 获取作品列表 (分页获取所有作品)
- logger.info(`[Baijiahao API] Step 3: Fetching works list...`);
- const worksList: WorkItem[] = [];
- let currentPage = 1;
- const pageSize = 20;
- let hasMore = true;
- let totalWorks = 0;
- while (hasMore) {
- try {
- const listUrl = `https://baijiahao.baidu.com/pcui/article/lists?currentPage=${currentPage}&pageSize=${pageSize}&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0`;
-
- logger.info(`[Baijiahao API] Fetching works page ${currentPage}...`);
-
- const listResponse = await fetch(listUrl, {
- method: 'GET',
- headers,
- });
- if (!listResponse.ok) {
- logger.warn(`[Baijiahao API] Failed to fetch works list page ${currentPage}: ${listResponse.status}`);
- break;
- }
- const listData = await listResponse.json() as {
- errno?: number;
- errmsg?: string;
- data?: {
- list?: Array<{
- id?: string;
- title?: string;
- cover_images?: string[];
- create_time?: string;
- status?: string;
- read_count?: number;
- like_count?: number;
- comment_count?: number;
- share_count?: number;
- }>;
- total?: number;
- };
- };
- if (listData.errno !== 0) {
- logger.warn(`[Baijiahao API] API returned error on page ${currentPage}: errno=${listData.errno}, errmsg=${listData.errmsg}`);
- break;
- }
- const list = listData.data?.list || [];
- totalWorks = listData.data?.total || 0;
- logger.info(`[Baijiahao API] Got ${list.length} works on page ${currentPage}, total: ${totalWorks}`);
- for (const item of list) {
- worksList.push({
- videoId: item.id || `bjh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
- title: item.title || '',
- coverUrl: item.cover_images?.[0] || '',
- duration: '00:00',
- publishTime: item.create_time || new Date().toISOString(),
- status: item.status || 'published',
- playCount: item.read_count || 0,
- likeCount: item.like_count || 0,
- commentCount: item.comment_count || 0,
- shareCount: item.share_count || 0,
- });
- }
- // 检查是否还有更多
- if (list.length < pageSize) {
- hasMore = false;
- logger.info(`[Baijiahao API] No more works, stopping at page ${currentPage}`);
- } else {
- currentPage++;
- // 防止无限循环,最多获取 10 页(200 个作品)
- if (currentPage > 10) {
- logger.warn(`[Baijiahao API] Reached max pages (10), stopping. Total fetched: ${worksList.length}, API total: ${totalWorks}`);
- hasMore = false;
- }
- }
- } catch (pageError) {
- logger.error(`[Baijiahao API] Error fetching page ${currentPage}:`, pageError);
- break;
- }
- }
- accountInfo.worksList = worksList;
- accountInfo.worksCount = worksList.length;
- logger.info(`[Baijiahao API] Successfully fetched account info: name=${accountInfo.accountName}, fans=${accountInfo.fansCount}, works=${accountInfo.worksCount}`);
- return accountInfo;
- } catch (error) {
- logger.error(`[Baijiahao API] Failed to fetch account info:`, error);
- // 返回默认信息,但保留已获取的部分数据
- return accountInfo;
- }
- }
- /**
- * 通过 Python API 获取账号信息
- */
- private async fetchAccountInfoViaPython(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
- logger.info(`[Python API] Fetching account info for ${platform}...`);
- try {
- // 检查 Python 服务是否可用
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (!pythonAvailable) {
- logger.warn(`[Python API] Service not available, returning default info`);
- return this.getDefaultAccountInfo(platform);
- }
- // 构建 Cookie 字符串
- const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
- // 调用 Python API
- const response = await fetch(`${PYTHON_SERVICE_URL}/account_info`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- logger.warn(`[Python API] account_info returned ${response.status}`);
- return this.getDefaultAccountInfo(platform);
- }
- const result = await response.json() as {
- success: boolean;
- account_id?: string;
- account_name?: string;
- avatar_url?: string;
- fans_count?: number;
- works_count?: number;
- error?: string;
- need_login?: boolean;
- };
- logger.info(`[Python API] account_info result: success=${result.success}, name=${result.account_name}`);
- if (result.success && result.account_name) {
- return {
- accountId: result.account_id || `${platform}_${Date.now()}`,
- accountName: result.account_name,
- avatarUrl: result.avatar_url || '',
- fansCount: result.fans_count || 0,
- worksCount: result.works_count || 0,
- };
- }
- if (result.need_login) {
- logger.warn(`[Python API] Account needs re-login`);
- }
- logger.warn(`[Python API] Failed to get account info: ${result.error}`);
- return this.getDefaultAccountInfo(platform);
- } catch (error) {
- logger.error(`[Python API] Failed to fetch account info for ${platform}:`, error);
- return this.getDefaultAccountInfo(platform);
- }
- }
- /**
- * 获取默认账号信息
- */
- private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
- // 平台友好名称映射
- const platformNames: Record<string, string> = {
- douyin: '抖音',
- xiaohongshu: '小红书',
- kuaishou: '快手',
- weixin_video: '视频号',
- bilibili: 'B站',
- toutiao: '头条',
- baijiahao: '百家号',
- };
- const name = platformNames[platform] || platform;
- return {
- accountId: `${platform}_${Date.now()}`,
- accountName: `${name}账号`,
- avatarUrl: '',
- fansCount: 0,
- worksCount: 0,
- };
- }
- /**
- * 获取抖音评论 - 逐个选择作品获取评论
- */
- async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
- const browser = await chromium.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- const page = await context.newPage();
- // 导航到评论管理页面
- logger.info('Navigating to Douyin comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 点击"选择作品"按钮
- logger.info('Looking for "选择作品" button...');
- const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');
- if (selectWorkBtn) {
- await selectWorkBtn.click();
- await page.waitForTimeout(2000);
- logger.info('Clicked "选择作品" button');
- } else {
- // 如果没有选择作品按钮,可能已经有作品被选中,直接获取当前评论
- logger.info('No "选择作品" button found, fetching current comments...');
- const currentComments = await this.extractCommentsFromPage(page);
- if (currentComments.length > 0) {
- allWorkComments.push({
- videoId: 'current',
- videoTitle: '当前作品',
- videoCoverUrl: '',
- comments: currentComments,
- });
- }
- await page.close();
- await context.close();
- await browser.close();
- return allWorkComments;
- }
- // 获取作品列表
- const worksList = await page.evaluate(() => {
- const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];
- // 查找作品列表容器(弹窗中的作品选择列表)
- const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');
- workItems.forEach((item, index) => {
- const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
- const coverEl = item.querySelector('img, [class*="cover"]');
- const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
- let coverUrl = '';
- if (coverEl) {
- coverUrl = (coverEl as HTMLImageElement).src ||
- coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
- }
- // 获取 video ID(从数据属性或其他方式)
- const videoId = item.getAttribute('data-video-id') ||
- item.getAttribute('data-id') ||
- `video_${index}`;
- works.push({ videoId, title, coverUrl });
- });
- return works;
- });
- logger.info(`Found ${worksList.length} works in the selector`);
- // 如果有作品列表,逐个选择并获取评论
- if (worksList.length > 0) {
- for (let i = 0; i < worksList.length; i++) {
- try {
- logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);
- // 点击选择该作品
- const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
- if (workItem) {
- await workItem.click();
- await page.waitForTimeout(2000);
- // 点击确认按钮(如果有)
- const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
- if (confirmBtn) {
- await confirmBtn.click();
- await page.waitForTimeout(2000);
- }
- }
- // 等待评论加载
- await page.waitForTimeout(2000);
- // 提取评论
- const comments = await this.extractCommentsFromPage(page);
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: worksList[i].videoId,
- videoTitle: worksList[i].title,
- videoCoverUrl: worksList[i].coverUrl,
- comments,
- });
- logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
- }
- // 重新打开选择作品弹窗(如果需要继续选择其他作品)
- if (i < worksList.length - 1) {
- const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
- if (selectBtn) {
- await selectBtn.click();
- await page.waitForTimeout(2000);
- }
- }
- } catch (workError) {
- logger.warn(`Failed to process work ${i + 1}:`, workError);
- }
- }
- } else {
- // 没有找到作品列表,尝试直接从页面获取评论
- const comments = await this.extractCommentsFromPage(page);
- if (comments.length > 0) {
- // 获取当前显示的作品信息
- const currentWork = await page.evaluate(() => {
- const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
- const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');
- return {
- title: titleEl?.textContent?.trim() || '当前作品',
- coverUrl: (coverEl as HTMLImageElement)?.src || '',
- };
- });
- allWorkComments.push({
- videoId: 'current',
- videoTitle: currentWork.title,
- videoCoverUrl: currentWork.coverUrl,
- comments,
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('Error fetching Douyin comments:', error);
- await browser.close();
- return allWorkComments;
- }
- }
- /**
- * 从页面提取评论列表
- * 使用抖音创作者中心的精确选择器
- * 根据实际 HTML 结构:
- * - 评论容器: container-sXKyMs (或类似 container-xxx)
- * - 用户名: username-aLgaNB (或类似 username-xxx)
- * - 时间: time-NRtTXO (或类似 time-xxx)
- * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
- * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
- */
- private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
- return page.evaluate(() => {
- const comments: Array<{
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const seenContents = new Set<string>();
- // 方法1: 直接查找所有评论容器 (container-xxx 类名)
- // 评论容器通常包含 checkbox、avatar、content 等子元素
- const allContainers = document.querySelectorAll('[class*="container-"]');
- const commentContainers: Element[] = [];
- allContainers.forEach(container => {
- // 检查是否是评论容器:包含用户名和评论内容
- const hasUsername = container.querySelector('[class*="username-"]');
- const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
- if (hasUsername && hasCommentContent) {
- commentContainers.push(container);
- }
- });
- console.log(`Found ${commentContainers.length} comment containers`);
- // 如果方法1没找到,尝试方法2:通过评论内容元素向上查找
- if (commentContainers.length === 0) {
- const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
- console.log(`Found ${contentElements.length} content elements, searching parents...`);
- contentElements.forEach(contentEl => {
- let parent = contentEl.parentElement;
- // 向上查找最多 10 层
- for (let i = 0; i < 10 && parent; i++) {
- const className = parent.className || '';
- // 查找包含 container- 的父元素
- if (className.includes('container-')) {
- if (!commentContainers.includes(parent)) {
- commentContainers.push(parent);
- }
- break;
- }
- parent = parent.parentElement;
- }
- });
- }
- console.log(`Total comment containers: ${commentContainers.length}`);
- commentContainers.forEach((container, index) => {
- try {
- // 提取用户名 - 使用 username-xxx 选择器
- let authorName = '';
- const usernameEl = container.querySelector('[class*="username-"]');
- if (usernameEl && usernameEl.textContent) {
- authorName = usernameEl.textContent.trim();
- }
- if (!authorName) authorName = '未知用户';
- // 提取头像 - 从 avatar-xxx 容器内的 img 提取
- let authorAvatar = '';
- const avatarContainer = container.querySelector('[class*="avatar-"]');
- if (avatarContainer) {
- const avatarImg = avatarContainer.querySelector('img');
- if (avatarImg) {
- authorAvatar = avatarImg.src || '';
- }
- }
- // 提取时间 - 使用 time-xxx 选择器
- let commentTime = '';
- const timeEl = container.querySelector('[class*="time-"]');
- if (timeEl && timeEl.textContent) {
- commentTime = timeEl.textContent.trim();
- }
- // 提取评论内容 - 使用 comment-content-text-xxx 选择器
- let content = '';
- const contentEl = container.querySelector('[class*="comment-content-text-"]');
- if (contentEl && contentEl.textContent) {
- content = contentEl.textContent.trim();
- }
- // 跳过空内容
- if (!content || content.length < 1) {
- console.log(`[${index}] Skipping empty content`);
- return;
- }
- // 去重 (基于用户名+内容)
- const contentKey = `${authorName}||${content}`;
- if (seenContents.has(contentKey)) {
- console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
- return;
- }
- seenContents.add(contentKey);
- // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
- let likeCount = 0;
- const operationsEl = container.querySelector('[class*="operations-"]');
- if (operationsEl) {
- // 查找第一个 item-xxx,通常是点赞数
- const firstItem = operationsEl.querySelector('[class*="item-"]');
- if (firstItem) {
- const text = firstItem.textContent || '';
- const match = text.match(/(\d+)/);
- if (match) {
- likeCount = parseInt(match[1], 10);
- }
- }
- }
- // 生成唯一 ID
- const contentHash = content.slice(0, 30) + authorName + commentTime;
- const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;
- comments.push({
- commentId,
- authorId: authorName,
- authorName,
- authorAvatar,
- content,
- likeCount,
- commentTime,
- });
- console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
- } catch (err) {
- console.error(`[${index}] Error extracting comment:`, err);
- }
- });
- console.log(`Successfully extracted ${comments.length} comments`);
- return comments;
- });
- }
- /**
- * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
- * 使用无头浏览器,通过拦截网络请求直接获取 API 数据
- * 更稳定、更高效
- */
- async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
- const browser = await chromium.launch({
- headless: true, // 无头模式
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- // 存储捕获的 API 数据
- const capturedWorks: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- }> = [];
- const capturedComments: Map<string, CommentItem[]> = new Map();
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 监听网络响应
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听作品列表 API - 支持新旧两种接口
- // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
- // 旧接口: /creator/item/list (item_info_list 字段)
- if (url.includes('/work_list') || url.includes('/creator/item/list')) {
- const data = await response.json();
- // 新接口: aweme_list
- if (data?.aweme_list && data.aweme_list.length > 0) {
- for (const aweme of data.aweme_list) {
- const awemeId = String(aweme.aweme_id || '');
- if (!awemeId) continue;
- const statistics = aweme.statistics || {};
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- let title = aweme.item_title || '';
- if (!title) {
- const desc = aweme.desc || aweme.caption || '';
- title = desc.split('\n')[0].slice(0, 50) || '无标题';
- }
- let coverUrl = '';
- if (aweme.Cover?.url_list?.length > 0) {
- coverUrl = aweme.Cover.url_list[0];
- } else if (aweme.video?.cover?.url_list?.length > 0) {
- coverUrl = aweme.video.cover.url_list[0];
- }
- capturedWorks.push({
- awemeId,
- title,
- coverUrl,
- commentCount,
- });
- }
- logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
- }
- // 旧接口: item_info_list
- const itemList = data?.item_info_list || data?.item_list || [];
- if (itemList.length > 0) {
- for (const item of itemList) {
- capturedWorks.push({
- awemeId: item.item_id_plain || item.aweme_id || '',
- title: item.title || '无标题',
- coverUrl: item.cover_image_url || '',
- commentCount: item.comment_count || 0,
- });
- }
- logger.info(`[API] Captured ${itemList.length} works from item/list API`);
- }
- }
- // 监听评论列表 API(两种格式)
- // 格式1: /comment/list/select/ - 初始加载,返回 { comments: [...] }
- // 格式2: /creator/comment/list/ - 切换作品后,返回 { comment_info_list: [...] }
- if (url.includes('/comment/list') || url.includes('/comment/read')) {
- const data = await response.json();
- // 从 URL 中提取 aweme_id
- const awemeIdMatch = url.match(/aweme_id=(\d+)/);
- const awemeId = awemeIdMatch?.[1] || '';
- let comments: CommentItem[] = [];
- // 格式1: 初始加载的评论 API (comment/list/select)
- if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
- comments = data.comments.map((c: Record<string, unknown>) => {
- const user = c.user as Record<string, unknown> | undefined;
- const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
- const avatarUrls = avatarThumb?.url_list as string[] | undefined;
- return {
- commentId: String(c.cid || ''),
- authorId: String(user?.uid || ''),
- authorName: String(user?.nickname || '匿名'),
- authorAvatar: avatarUrls?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- };
- });
- logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
- }
- // 格式2: 切换作品后的评论 API (creator/comment/list)
- if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
- comments = data.comment_info_list.map((c: Record<string, unknown>) => {
- const userInfo = c.user_info as Record<string, unknown> | undefined;
- return {
- commentId: String(c.comment_id || ''),
- authorId: String(userInfo?.user_id || ''),
- authorName: String(userInfo?.screen_name || '匿名'),
- authorAvatar: String(userInfo?.avatar_url || ''),
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: awemeId, // 这种格式没有直接返回 aweme_id
- };
- });
- logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
- }
- if (comments.length > 0) {
- const videoId = comments[0]?.videoId || awemeId;
- if (videoId) {
- const existing = capturedComments.get(videoId) || [];
- capturedComments.set(videoId, [...existing, ...comments]);
- logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
- }
- }
- }
- } catch {
- // 忽略非 JSON 响应
- }
- });
- // 导航到创作者中心页面(设置好 Cookie 后)
- logger.info('[API Interception] Navigating to creator page...');
- await page.goto('https://creator.douyin.com/creator-micro/home', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[API Interception] Cookie expired');
- return [];
- }
- // 方式1:直接调用 API 获取作品列表(优先)
- logger.info('[API Interception] Fetching works via direct API...');
- let works = await this.fetchWorksDirectApi(page);
- // 方式2:如果直接调用失败,尝试通过页面触发 API
- if (works.length === 0) {
- logger.info('[API Interception] Direct API failed, trying page navigation...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'networkidle',
- timeout: 60000,
- });
- await page.waitForTimeout(3000);
- // 点击"选择作品"按钮触发作品列表 API
- const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
- if (selectBtn) {
- await selectBtn.click();
- await page.waitForTimeout(3000);
- }
- // 使用监听到的数据
- works = capturedWorks;
- }
- logger.info(`[API Interception] Total works: ${works.length}`);
- // 获取有评论的作品
- const worksWithComments = works.filter(w => w.commentCount > 0);
- logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);
- // 如果有评论的作品,需要导航到评论管理页面并逐个切换获取
- if (worksWithComments.length > 0) {
- // 先尝试直接调用 API 获取评论
- for (const work of worksWithComments) {
- logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);
- let comments = capturedComments.get(work.awemeId) || [];
- if (comments.length === 0) {
- comments = await this.fetchCommentsDirectApi(page, work.awemeId);
- }
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
- }
- }
- // 如果直接 API 没有获取到足够的评论,使用页面交互方式
- const worksNeedingPageMethod = worksWithComments.filter(w => {
- const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
- return !found || found.comments.length === 0;
- });
- if (worksNeedingPageMethod.length > 0) {
- logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);
- // works 是所有作品的列表(包括没有评论的),弹窗中的顺序应该和这个一致
- // worksWithComments 是有评论的作品列表
- logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
- logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);
- // 构建作品索引映射:在所有作品列表中,每个有评论的作品的索引是多少
- const workIndexMap = new Map<string, number>();
- works.forEach((w, idx) => {
- if (w.commentCount > 0) {
- workIndexMap.set(w.awemeId, idx);
- }
- });
- logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);
- // 导航到评论管理页面
- logger.info('[Page Method] Navigating to comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面加载
- await page.waitForTimeout(5000);
- // 用于存储最新捕获的评论和 aweme_id
- const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };
- // 设置监听器 - 捕获评论 API 响应
- page.on('response', async (response) => {
- const url = response.url();
- if (url.includes('/comment/list') || url.includes('/comment/read')) {
- try {
- const jsonData = await response.json();
- let parsedComments: CommentItem[] = [];
- let capturedAwemeId = '';
- // 从 URL 中提取 aweme_id(格式1有)
- const awemeIdMatch = url.match(/aweme_id=(\d+)/);
- capturedAwemeId = awemeIdMatch?.[1] || '';
- // 格式1: { comments: [...] }
- if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
- // 从评论中提取 aweme_id
- const firstComment = jsonData.comments[0] as Record<string, unknown>;
- if (!capturedAwemeId && firstComment.aweme_id) {
- capturedAwemeId = String(firstComment.aweme_id);
- }
- parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
- commentId: String((c as { cid?: string }).cid || ''),
- authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
- authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
- authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
- content: String((c as { text?: string }).text || ''),
- likeCount: Number((c as { digg_count?: number }).digg_count || 0),
- commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
- videoId: capturedAwemeId,
- }));
- logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
- }
- // 格式2: { comment_info_list: [...] }
- if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
- parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
- const userInfo = c.user_info as Record<string, unknown> | undefined;
- return {
- commentId: String(c.comment_id || ''),
- authorId: String(userInfo?.user_id || ''),
- authorName: String(userInfo?.screen_name || '匿名'),
- authorAvatar: String(userInfo?.avatar_url || ''),
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: '', // 格式2没有aweme_id,稍后填充
- };
- });
- logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
- }
- if (parsedComments.length > 0) {
- latestHolder.comments = parsedComments;
- latestHolder.awemeId = capturedAwemeId;
- }
- } catch {
- // 忽略
- }
- }
- });
- // 等待第一个作品的评论加载(格式1,有 aweme_id)
- await page.waitForTimeout(4000);
- // 处理第一个作品(页面加载时自动显示,格式1有aweme_id可以直接匹配)
- if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
- const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
- if (matchedWork) {
- allWorkComments.push({
- videoId: matchedWork.awemeId,
- videoTitle: matchedWork.title,
- videoCoverUrl: matchedWork.coverUrl,
- comments: latestHolder.comments,
- });
- logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
- }
- }
- // 遍历其他有评论的作品
- for (const work of worksWithComments) {
- // 检查是否已获取
- const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
- if (existing) {
- logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
- continue;
- }
- // 获取该作品在所有作品列表中的索引
- const workIndex = workIndexMap.get(work.awemeId);
- if (workIndex === undefined) {
- logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
- continue;
- }
- logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);
- try {
- // 清空之前的数据
- latestHolder.comments = [];
- latestHolder.awemeId = '';
- // 点击"选择作品"按钮
- await page.click('button:has-text("选择作品")');
- await page.waitForTimeout(2000);
- // 找到弹窗中的作品图片列表
- const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
- logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);
- if (workIndex < workImages.length) {
- // 点击对应索引的作品
- await workImages[workIndex].click();
- logger.info(`[Page Method] Clicked work image at index ${workIndex}`);
- // 等待评论 API 响应
- await page.waitForTimeout(4000);
- // 获取评论
- if (latestHolder.comments.length > 0) {
- // 使用当前 work 的 awemeId
- const comments = latestHolder.comments.map(c => ({
- ...c,
- videoId: work.awemeId,
- }));
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
- } else {
- // 尝试从页面提取
- const pageComments = await this.extractCommentsFromPage(page);
- if (pageComments.length > 0) {
- const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
- } else {
- logger.warn(`[Page Method] No comments for ${work.awemeId}`);
- }
- }
- } else {
- logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
- await page.keyboard.press('Escape');
- }
- await page.waitForTimeout(1000);
- } catch (e) {
- logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
- await page.keyboard.press('Escape').catch(() => { });
- await page.waitForTimeout(500);
- }
- }
- }
- }
- logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
- await context.close();
- } catch (error) {
- logger.error('[API Interception] Error:', error);
- } finally {
- await browser.close();
- }
- return allWorkComments;
- }
- /**
- * 直接调用评论 API 获取数据(支持分页获取所有评论)
- * 优先使用视频页面 API(获取全部评论),失败时才使用创作者 API
- */
- private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- // 优先尝试视频页面 API(获取全部评论)
- logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
- let comments = await this.fetchVideoPageCommentsApi(page, awemeId);
- if (comments.length > 0) {
- logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
- return comments;
- }
- // 如果视频页面 API 失败,尝试创作者评论 API(可能只返回部分评论)
- logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
- comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);
- return comments;
- }
- /**
- * 通过视频页面获取全部评论(主要方案)
- * 这个 API 能获取视频的所有评论,不仅仅是创作者回复过的
- */
- private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- const comments: CommentItem[] = [];
- const maxPages = 50;
- let cursor = 0;
- let hasMore = true;
- let pageCount = 0;
- try {
- // 导航到视频页面
- logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
- await page.goto(`https://www.douyin.com/video/${awemeId}`, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- const data = await page.evaluate(async ({ videoId, cursorValue }) => {
- try {
- 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=`;
- const resp = await fetch(url, {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'Referer': `https://www.douyin.com/video/${videoId}`,
- },
- });
- if (!resp.ok) {
- return { error: `HTTP ${resp.status}`, comments: [] };
- }
- return resp.json();
- } catch (e) {
- return { error: String(e), comments: [] };
- }
- }, { videoId: awemeId, cursorValue: cursor });
- if (data?.error) {
- logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
- }
- if (data?.comments && Array.isArray(data.comments)) {
- for (const c of data.comments) {
- comments.push({
- commentId: String(c.cid || ''),
- authorId: String(c.user?.uid || c.user?.sec_uid || ''),
- authorName: String(c.user?.nickname || '匿名'),
- authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- });
- }
- logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
- }
- hasMore = data?.has_more === true || data?.has_more === 1;
- cursor = data?.cursor || cursor + 50;
- if (!data?.comments || data.comments.length === 0) {
- hasMore = false;
- }
- }
- logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
- } catch (e) {
- logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
- }
- return comments;
- }
- /**
- * 创作者评论管理 API(备用方案)
- * 获取的是需要回复的评论
- */
- private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- const comments: CommentItem[] = [];
- const maxPages = 50;
- let cursor = 0;
- let hasMore = true;
- let pageCount = 0;
- try {
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- const data = await page.evaluate(async ({ videoId, cursorValue }) => {
- 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`;
- const resp = await fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return resp.json();
- }, { videoId: awemeId, cursorValue: cursor });
- if (data?.comments && Array.isArray(data.comments)) {
- for (const c of data.comments) {
- comments.push({
- commentId: String(c.cid || ''),
- authorId: String(c.user?.uid || ''),
- authorName: String(c.user?.nickname || '匿名'),
- authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- });
- }
- logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
- }
- hasMore = data?.has_more === true || data?.has_more === 1;
- cursor = data?.cursor || cursor + 50;
- if (!data?.comments || data.comments.length === 0) {
- hasMore = false;
- }
- }
- logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
- } catch (e) {
- logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
- }
- return comments;
- }
- /**
- * 直接调用抖音 API 获取作品列表
- * 使用新的 work_list 接口,支持分页加载
- * 返回作品列表和总作品数
- *
- * 注意:需要先导航到作品管理页面才能正确调用 API
- */
- private async fetchWorksDirectApi(page: Page): Promise<{
- works: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- createTime?: number;
- }>;
- total: number;
- }> {
- const works: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- createTime?: number;
- }> = [];
- let totalCount = 0; // 从 API 获取的总作品数
- try {
- // 首先导航到作品管理页面,确保 API 有正确的上下文和权限
- const contentManageUrl = 'https://creator.douyin.com/creator-micro/content/manage';
- const currentUrl = page.url();
-
- if (!currentUrl.includes('/content/manage')) {
- logger.info(`[DirectAPI] Navigating to content manage page...`);
- await page.goto(contentManageUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
-
- // 检查是否需要登录
- const newUrl = page.url();
- if (newUrl.includes('login') || newUrl.includes('passport')) {
- logger.warn('[DirectAPI] Not logged in, cannot fetch works');
- return { works, total: 0 };
- }
- }
- let hasMore = true;
- let maxCursor = 0;
- let pageCount = 0;
- const maxPages = 20; // 最多加载20页,防止无限循环
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- logger.info(`[DirectAPI] Fetching works page ${pageCount}, cursor: ${maxCursor}`);
- const data = await page.evaluate(async (cursor: number) => {
- // 使用新的 work_list API 接口
- // status: 0 表示获取全部已发布的作品
- // count: 每页获取数量
- 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`;
- const resp = await fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return resp.json();
- }, maxCursor);
- // 获取作品数
- const awemeList = data?.aweme_list || [];
- 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}`);
-
- // 检查 API 返回状态
- if (data?.status_code !== 0 && data?.status_code !== undefined) {
- logger.warn(`[DirectAPI] API returned error status_code: ${data.status_code}`);
- // status_code: 8 表示未授权,可能需要重新登录
- if (data.status_code === 8) {
- logger.warn('[DirectAPI] status_code 8: Not authorized, may need re-login');
- }
- break;
- }
- // 优先从第一个作品的 author.aweme_count 获取真实作品数(只在第一页获取)
- if (pageCount === 1 && awemeList.length > 0) {
- const firstAweme = awemeList[0];
- const authorAwemeCount = firstAweme?.author?.aweme_count;
- if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
- totalCount = authorAwemeCount;
- logger.info(`[DirectAPI] Using author.aweme_count as total works: ${totalCount}`);
- }
- }
- // 解析 aweme_list 中的作品数据
- logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);
- for (const aweme of awemeList) {
- const awemeId = String(aweme.aweme_id || '');
- if (!awemeId) continue;
- // 从 statistics 中获取评论数
- const statistics = aweme.statistics || {};
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- // 获取标题:优先使用 item_title,其次使用 desc(描述)
- let title = aweme.item_title || '';
- if (!title) {
- // 从 desc 中提取标题(取第一行或前50个字符)
- const desc = aweme.desc || aweme.caption || '';
- title = desc.split('\n')[0].slice(0, 50) || '无标题';
- }
- // 获取封面 URL:从 Cover.url_list 或 video.cover.url_list 中获取
- let coverUrl = '';
- if (aweme.Cover?.url_list?.length > 0) {
- coverUrl = aweme.Cover.url_list[0];
- } else if (aweme.video?.cover?.url_list?.length > 0) {
- coverUrl = aweme.video.cover.url_list[0];
- }
- works.push({
- awemeId,
- title,
- coverUrl,
- commentCount,
- createTime: aweme.create_time,
- });
- }
- // 检查是否有更多数据
- // 注意: 抖音 API 返回的 has_more 可能不准确,我们额外判断
- const apiHasMore = data?.has_more === true || data?.has_more === 1;
- // 更新游标:使用返回的 max_cursor
- if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
- // 只有当 max_cursor 有变化时才继续
- if (data.max_cursor !== maxCursor) {
- maxCursor = data.max_cursor;
- hasMore = apiHasMore && awemeList.length > 0;
- } else {
- // max_cursor 没变化,说明到底了
- hasMore = false;
- }
- } else if (awemeList.length > 0) {
- // 如果没有 max_cursor,使用最后一个作品的 create_time 作为游标
- const lastAweme = awemeList[awemeList.length - 1];
- if (lastAweme.create_time) {
- const newCursor = lastAweme.create_time;
- if (newCursor !== maxCursor) {
- maxCursor = newCursor;
- hasMore = apiHasMore;
- } else {
- hasMore = false;
- }
- } else {
- hasMore = false;
- }
- } else {
- // 没有获取到数据,停止循环
- hasMore = false;
- }
- logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);
- // 稍微延迟,避免请求过快
- if (hasMore) {
- await new Promise(resolve => setTimeout(resolve, 500));
- }
- }
- logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages, items count: ${totalCount}`);
- } catch (e) {
- logger.warn('[DirectAPI] Failed to fetch works:', e);
- }
- return { works, total: totalCount };
- }
- /**
- * 通过 Python API 获取评论 - 分作品逐个获取
- */
- private async fetchCommentsViaPythonApi(platform: 'douyin' | 'xiaohongshu', cookies: CookieData[]): Promise<WorkComments[]> {
- const allWorkComments: WorkComments[] = [];
- const cookieString = JSON.stringify(cookies);
- // 1. 先获取作品列表
- logger.info(`[${platform} Comments Python] Fetching works list...`);
- const worksResponse = await fetch(`${PYTHON_SERVICE_URL}/works`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- page: 0,
- page_size: 50,
- }),
- });
- if (!worksResponse.ok) {
- throw new Error(`Python API works returned ${worksResponse.status}`);
- }
- const worksResult = await worksResponse.json();
- if (!worksResult.success) {
- throw new Error(worksResult.error || 'Failed to get works');
- }
- const works = worksResult.works || [];
- logger.info(`[${platform} Comments Python] Got ${works.length} works`);
- // 2. 遍历作品获取评论
- for (const work of works) {
- const workId = work.work_id;
- if (!workId) continue;
- try {
- logger.info(`[${platform} Comments Python] Fetching comments for work ${workId}...`);
- const commentsResponse = await fetch(`${PYTHON_SERVICE_URL}/comments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- work_id: workId,
- }),
- });
- if (!commentsResponse.ok) {
- logger.warn(`[${platform} Comments Python] Comments API returned ${commentsResponse.status} for work ${workId}`);
- continue;
- }
- const commentsResult = await commentsResponse.json();
- if (!commentsResult.success) {
- logger.warn(`[${platform} Comments Python] Failed to get comments for work ${workId}: ${commentsResult.error}`);
- continue;
- }
- const comments: CommentItem[] = (commentsResult.comments || []).map((c: {
- comment_id: string;
- author_id: string;
- author_name: string;
- author_avatar: string;
- content: string;
- like_count: number;
- create_time: string;
- reply_count?: number;
- }) => ({
- commentId: c.comment_id,
- authorId: c.author_id,
- authorName: c.author_name,
- authorAvatar: c.author_avatar,
- content: c.content,
- likeCount: c.like_count,
- commentTime: c.create_time,
- replyCount: c.reply_count || 0,
- }));
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: workId,
- videoTitle: work.title || '',
- videoCoverUrl: work.cover_url || '',
- comments,
- });
- logger.info(`[${platform} Comments Python] Got ${comments.length} comments for work ${workId}`);
- }
- } catch (commentError) {
- logger.warn(`[${platform} Comments Python] Error fetching comments for work ${workId}:`, commentError);
- }
- }
- logger.info(`[${platform} Comments Python] Total: ${allWorkComments.length} works with comments`);
- return allWorkComments;
- }
- /**
- * 通过 Python API 获取抖音评论 - 一次性获取所有作品的评论(备用)
- */
- private async fetchDouyinCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
- const cookieString = JSON.stringify(cookies);
- logger.info('[Douyin Comments Python] Fetching all comments...');
- const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform: 'douyin',
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API all_comments returned ${response.status}`);
- }
- const result = await response.json();
- if (!result.success) {
- throw new Error(result.error || 'Failed to get all comments');
- }
- const workComments = result.work_comments || [];
- logger.info(`[Douyin Comments Python] Got ${workComments.length} works with comments`);
- // 转换数据格式
- const allWorkComments: WorkComments[] = workComments.map((wc: {
- work_id: string;
- title: string;
- cover_url: string;
- comments: Array<{
- comment_id: string;
- author_id: string;
- author_name: string;
- author_avatar: string;
- content: string;
- like_count: number;
- create_time: string;
- is_author?: boolean;
- }>;
- }) => ({
- videoId: wc.work_id,
- videoTitle: wc.title || '',
- videoCoverUrl: wc.cover_url || '',
- comments: (wc.comments || []).map(c => ({
- commentId: c.comment_id,
- authorId: c.author_id,
- authorName: c.author_name,
- authorAvatar: c.author_avatar,
- content: c.content,
- likeCount: c.like_count,
- commentTime: c.create_time,
- })),
- }));
- logger.info(`[Douyin Comments Python] Total: ${allWorkComments.length} works with comments`);
- return allWorkComments;
- }
- /**
- * 获取抖音评论 - 优先使用 Python API
- */
- async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 Python API(分作品获取)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Douyin Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('douyin', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Douyin Comments] Python API returned empty, falling back to Playwright...');
- } catch (pythonError) {
- logger.warn('[Douyin Comments] Python API failed:', pythonError);
- }
- }
- // 回退到 Playwright API 拦截方式
- const result = await this.fetchDouyinCommentsByApiInterception(cookies);
- if (result.length > 0) {
- return result;
- }
- // 如果 API 方式失败,使用旧的 DOM 解析方式作为备用
- logger.info('[Fallback] Using DOM parsing method...');
- const browser = await chromium.launch({
- headless: true, // 改为无头模式
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 导航到评论管理页面
- logger.info('Navigating to Douyin comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面完全加载
- logger.info('Waiting for page to fully load...');
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- logger.info(`Current URL: ${currentUrl}`);
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('Cookie expired, need re-login');
- await browser.close();
- return allWorkComments;
- }
- logger.info('Page loaded successfully');
- // 等待评论列表加载
- logger.info('Waiting for comments to load...');
- try {
- await page.waitForSelector('[class*="comment-content-text-"]', { timeout: 10000 });
- logger.info('Comments loaded');
- } catch {
- logger.warn('No comments found on initial load, will try to select works');
- }
- // 辅助函数:从当前页面提取评论
- const extractCommentsFromCurrentPage = async (): Promise<CommentItem[]> => {
- logger.info('Extracting comments from current page...');
- // 滚动页面加载所有评论
- await page.evaluate(async () => {
- // 滚动多次加载更多评论
- for (let i = 0; i < 10; i++) {
- window.scrollBy(0, 500);
- await new Promise(r => setTimeout(r, 800));
- }
- window.scrollTo(0, 0);
- });
- await page.waitForTimeout(2000);
- // 使用精确选择器提取评论
- const comments = await page.evaluate(() => {
- const result: Array<{
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const seenContents = new Set<string>();
- // 查找所有评论容器:包含 username 和 comment-content-text 的 container
- const allContainers = document.querySelectorAll('[class*="container-"]');
- const commentContainers: Element[] = [];
- allContainers.forEach(container => {
- const hasUsername = container.querySelector('[class*="username-"]');
- const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
- if (hasUsername && hasCommentContent) {
- commentContainers.push(container);
- }
- });
- console.log(`Found ${commentContainers.length} comment containers`);
- commentContainers.forEach((container, index) => {
- try {
- // 用户名
- const usernameEl = container.querySelector('[class*="username-"]');
- const authorName = usernameEl?.textContent?.trim() || '未知用户';
- // 时间
- const timeEl = container.querySelector('[class*="time-"]');
- const commentTime = timeEl?.textContent?.trim() || '';
- // 评论内容
- const contentEl = container.querySelector('[class*="comment-content-text-"]');
- const content = contentEl?.textContent?.trim() || '';
- if (!content) return;
- // 头像
- const avatarContainer = container.querySelector('[class*="avatar-"]');
- const avatarImg = avatarContainer?.querySelector('img');
- const authorAvatar = avatarImg?.src || '';
- // 去重
- const key = `${authorName}||${content}`;
- if (seenContents.has(key)) return;
- seenContents.add(key);
- // 点赞数
- let likeCount = 0;
- const opsEl = container.querySelector('[class*="operations-"]');
- if (opsEl) {
- const itemEl = opsEl.querySelector('[class*="item-"]');
- if (itemEl) {
- const match = itemEl.textContent?.match(/(\d+)/);
- if (match) likeCount = parseInt(match[1], 10);
- }
- }
- // 生成 ID
- const hash = content.slice(0, 30) + authorName + commentTime;
- const commentId = `dy_${btoa(encodeURIComponent(hash)).slice(0, 20)}`;
- result.push({
- commentId,
- authorId: authorName,
- authorName,
- authorAvatar,
- content,
- likeCount,
- commentTime,
- });
- console.log(`[${index}] ${authorName}: ${content.slice(0, 30)}`);
- } catch (e) {
- console.error(`Error at ${index}:`, e);
- }
- });
- return result;
- });
- logger.info(`Extracted ${comments.length} comments`);
- return comments;
- };
- // 辅助函数:获取当前显示的作品标题
- const getCurrentWorkTitle = async (): Promise<string> => {
- return page.evaluate(() => {
- // 查找作品标题 - 通常在页面顶部区域
- // 排除筛选器和按钮中的文本
- const excludeTexts = ['全部评论', '最新发布', '全部人群', '搜索', '选择作品', '评论管理'];
- // 方法1: 查找视频信息区域
- const videoInfoSelectors = [
- '[class*="video-info"] [class*="title"]',
- '[class*="work-info"] [class*="title"]',
- '[class*="content-info"] [class*="title"]',
- ];
- for (const selector of videoInfoSelectors) {
- const el = document.querySelector(selector);
- if (el?.textContent) {
- const text = el.textContent.trim();
- if (text.length > 5 && !excludeTexts.some(e => text.includes(e))) {
- return text;
- }
- }
- }
- // 方法2: 查找页面上较长的标题文本
- const allTexts = document.querySelectorAll('div, span, p');
- for (const el of Array.from(allTexts)) {
- const text = el.textContent?.trim() || '';
- if (text.length > 20 &&
- text.length < 200 &&
- !excludeTexts.some(e => text.includes(e)) &&
- !el.closest('button') &&
- !el.closest('[class*="select"]') &&
- !el.closest('[class*="filter"]')) {
- // 检查是否可能是作品标题(通常包含特定字符或格式)
- if (text.includes('#') || text.match(/[,。!?、]/)) {
- return text;
- }
- }
- }
- return '';
- });
- };
- // 步骤1: 先获取当前页面显示的评论(默认显示的第一个作品)
- logger.info('Step 1: Getting comments from default view...');
- const defaultTitle = await getCurrentWorkTitle();
- const defaultComments = await extractCommentsFromCurrentPage();
- if (defaultComments.length > 0) {
- allWorkComments.push({
- videoId: `video_${Date.now()}`,
- videoTitle: defaultTitle || '默认作品',
- videoCoverUrl: '',
- comments: defaultComments,
- });
- logger.info(`Got ${defaultComments.length} comments from default view, title: "${defaultTitle.slice(0, 50)}"`);
- }
- // 步骤2: 尝试点击"选择作品"按钮获取更多作品的评论
- logger.info('Step 2: Looking for "选择作品" button...');
- // 使用 locator 查找按钮
- const selectBtn = page.locator('text=选择作品').first();
- const btnCount = await selectBtn.count();
- logger.info(`Found ${btnCount} "选择作品" button(s)`);
- if (btnCount > 0) {
- logger.info('Clicking "选择作品" button...');
- await selectBtn.click();
- // 等待更长时间,确保弹窗完全加载
- logger.info('Waiting for work list modal to appear...');
- await page.waitForTimeout(5000);
- // 打印当前页面状态,帮助调试
- const modalInfo = await page.evaluate(() => {
- // 查找所有可能的弹窗元素
- const modals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="drawer"], [class*="dialog"], [role="dialog"]');
- const modalClasses = Array.from(modals).map(m => m.className).slice(0, 5);
- // 查找所有图片(作品封面)
- const images = document.querySelectorAll('img[src*="douyinpic"]');
- // 查找所有可能的卡片元素
- const cards = document.querySelectorAll('[class*="card"], [class*="item"]');
- const cardClasses = Array.from(cards).map(c => c.className).slice(0, 10);
- return {
- modalCount: modals.length,
- modalClasses,
- imageCount: images.length,
- cardCount: cards.length,
- cardClasses,
- };
- });
- logger.info(`Modal debug: ${JSON.stringify(modalInfo)}`);
- // 尝试多种选择器查找作品列表
- const workSelectors = [
- '[class*="video-card"]',
- '[class*="work-item"]',
- '[class*="content-item"]',
- '[class*="modal"] [class*="card"]',
- '[class*="modal"] img',
- '[class*="drawer"] [class*="card"]',
- '[class*="drawer"] img',
- '[role="dialog"] [class*="card"]',
- '[role="dialog"] img',
- '[class*="popup"] img',
- 'img[src*="douyinpic"]', // 直接找抖音图片
- ];
- let workElements: Awaited<ReturnType<typeof page.$$>> = [];
- let usedSelector = '';
- for (const selector of workSelectors) {
- const elements = await page.$$(selector);
- logger.info(`Selector "${selector}" found ${elements.length} elements`);
- if (elements.length > 0 && elements.length < 50) { // 避免选中太多无关元素
- workElements = elements;
- usedSelector = selector;
- break;
- }
- }
- logger.info(`Using selector "${usedSelector}", found ${workElements.length} work items`);
- if (workElements.length > 0) {
- // 首先获取所有作品的评论数信息
- // 根据 HTML 结构:
- // - 作品项容器: div.container-Lkxos9 (类名可能变化,使用 [class*="container-"])
- // - 标题: div.title-LUOP3b (类名可能变化,使用 [class*="title-"])
- // - 评论数: div.right-os7ZB9 > div (类名可能变化,使用 [class*="right-"] > div)
- const workInfoList = await page.evaluate(() => {
- const works: Array<{ index: number; title: string; commentCount: number }> = [];
- // 查找作品列表容器中的所有作品项
- // 根据用户提供的 HTML,作品项的类名是 container-Lkxos9
- const workContainers = document.querySelectorAll('[role="dialog"] [class*="container-"]');
- console.log(`Found ${workContainers.length} work containers`);
- workContainers.forEach((container, index) => {
- // 检查是否包含图片(确认是作品项而不是其他容器)
- const img = container.querySelector('img[src*="douyinpic"]');
- if (!img) {
- console.log(`Container ${index} has no douyinpic image, skipping`);
- return;
- }
- // 提取标题
- const titleEl = container.querySelector('[class*="title-"]');
- const title = titleEl?.textContent?.trim() || `作品 ${works.length + 1}`;
- // 提取评论数 - 在 right- 容器的最后一个 div 中
- let commentCount = 0;
- const rightContainer = container.querySelector('[class*="right-"]');
- if (rightContainer) {
- // 获取 right 容器下的所有直接 div 子元素
- const divs = rightContainer.querySelectorAll(':scope > div');
- if (divs.length > 0) {
- // 最后一个 div 包含评论数
- const lastDiv = divs[divs.length - 1];
- const text = lastDiv.textContent?.trim() || '0';
- const num = parseInt(text, 10);
- if (!isNaN(num)) {
- commentCount = num;
- }
- }
- }
- console.log(`Work ${works.length}: title="${title.slice(0, 30)}...", commentCount=${commentCount}`);
- works.push({
- index: works.length,
- title: title.slice(0, 100),
- commentCount
- });
- });
- // 如果上面的选择器没找到,尝试备用方法
- if (works.length === 0) {
- console.log('Primary selector failed, trying fallback...');
- // 直接查找包含 douyinpic 图片的元素的父容器
- const images = document.querySelectorAll('[role="dialog"] img[src*="douyinpic"]');
- images.forEach((img, index) => {
- // 向上查找到作品项容器
- let container = img.parentElement;
- while (container && !container.classList.toString().includes('container-')) {
- container = container.parentElement;
- }
- if (container) {
- const titleEl = container.querySelector('[class*="title-"]');
- const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
- // 查找评论数
- let commentCount = 0;
- const rightEl = container.querySelector('[class*="right-"]');
- if (rightEl) {
- const text = rightEl.textContent?.trim() || '';
- // 提取最后出现的数字
- const matches = text.match(/\d+/g);
- if (matches && matches.length > 0) {
- commentCount = parseInt(matches[matches.length - 1], 10);
- }
- }
- works.push({ index, title: title.slice(0, 100), commentCount });
- }
- });
- }
- return works;
- });
- logger.info(`Work info list (${workInfoList.length} items): ${JSON.stringify(workInfoList)}`);
- // 过滤出评论数 > 0 的作品,或者评论数未知(-1)的作品
- const worksWithComments = workInfoList.filter(w => w.commentCount > 0 || w.commentCount === -1);
- logger.info(`Found ${worksWithComments.length} works with comments > 0 or unknown (out of ${workInfoList.length})`);
- // 如果所有作品评论数都是0,则不处理任何作品
- const allZero = workInfoList.every(w => w.commentCount === 0);
- if (allZero) {
- logger.info('All works have 0 comments, skipping all');
- }
- // 如果没有找到评论数信息或有未知的,处理这些作品
- const indicesToProcess = allZero
- ? []
- : (worksWithComments.length > 0
- ? worksWithComments.map(w => w.index)
- : Array.from({ length: Math.min(workElements.length, 10) }, (_, i) => i));
- logger.info(`Will process work indices: ${indicesToProcess.join(', ')}`);
- // 遍历每个有评论的作品
- for (let idx = 0; idx < indicesToProcess.length; idx++) {
- const i = indicesToProcess[idx];
- try {
- const workInfo = workInfoList.find(w => w.index === i);
- logger.info(`Processing work ${idx + 1}/${indicesToProcess.length} (index=${i}, title="${workInfo?.title}", expectedComments=${workInfo?.commentCount})...`);
- // 重新打开选择作品弹窗
- if (idx > 0) {
- await selectBtn.click();
- await page.waitForTimeout(3000);
- }
- // 重新获取元素列表(因为 DOM 可能已变化)
- const currentItems = await page.$$(usedSelector);
- if (i < currentItems.length) {
- // 滚动到元素可见
- await currentItems[i].scrollIntoViewIfNeeded();
- await page.waitForTimeout(500);
- // 点击元素
- await currentItems[i].click();
- await page.waitForTimeout(4000);
- // 获取评论
- const title = await getCurrentWorkTitle();
- const comments = await extractCommentsFromCurrentPage();
- logger.info(`Work index=${i}: title="${title.slice(0, 50)}", comments=${comments.length}`);
- // 检查是否已经获取过这个作品的评论
- const exists = allWorkComments.some(w =>
- w.videoTitle === title ||
- (w.comments.length > 0 && comments.length > 0 &&
- w.comments[0].content === comments[0].content)
- );
- if (!exists && (comments.length > 0 || title)) {
- allWorkComments.push({
- videoId: `video_${Date.now()}_${i}`,
- videoTitle: title || workInfo?.title || `作品 ${i + 1}`,
- videoCoverUrl: '',
- comments,
- });
- logger.info(`Work index=${i}: Saved ${comments.length} comments`);
- } else {
- logger.info(`Work index=${i}: Skipped (duplicate or empty)`);
- }
- }
- } catch (err) {
- logger.warn(`Error processing work index=${i}:`, err);
- }
- }
- } else {
- logger.warn('No work items found in modal');
- }
- // 按 Escape 关闭弹窗
- try {
- await page.keyboard.press('Escape');
- await page.waitForTimeout(500);
- } catch { }
- } else {
- logger.warn('"选择作品" button not found, only default comments will be returned');
- }
- await page.close();
- await context.close();
- await browser.close();
- const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
- logger.info(`Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('Error fetching Douyin comments:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- /**
- * 通过 Python API 获取小红书评论 - 一次性获取所有作品的评论
- */
- private async fetchXiaohongshuCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
- const cookieString = JSON.stringify(cookies);
- logger.info('[Xiaohongshu Comments Python] Fetching all comments...');
- const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform: 'xiaohongshu',
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API all_comments returned ${response.status}`);
- }
- const result = await response.json();
- if (!result.success) {
- throw new Error(result.error || 'Failed to get all comments');
- }
- const workComments = result.work_comments || [];
- logger.info(`[Xiaohongshu Comments Python] Got ${workComments.length} works with comments`);
- // 转换数据格式
- const allWorkComments: WorkComments[] = workComments.map((wc: {
- work_id: string;
- title: string;
- cover_url: string;
- comments: Array<{
- comment_id: string;
- author_id: string;
- author_name: string;
- author_avatar: string;
- content: string;
- like_count: number;
- create_time: string;
- }>;
- }) => ({
- videoId: wc.work_id,
- videoTitle: wc.title || '',
- videoCoverUrl: wc.cover_url || '',
- comments: (wc.comments || []).map(c => ({
- commentId: c.comment_id,
- authorId: c.author_id,
- authorName: c.author_name,
- authorAvatar: c.author_avatar,
- content: c.content,
- likeCount: c.like_count,
- commentTime: c.create_time,
- })),
- }));
- logger.info(`[Xiaohongshu Comments Python] Total: ${allWorkComments.length} works with comments`);
- return allWorkComments;
- }
- /**
- * 获取小红书评论 - 优先使用 Python API
- */
- async fetchXiaohongshuCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 Python API(分作品获取)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Xiaohongshu Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('xiaohongshu', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Xiaohongshu Comments] Python API returned empty, falling back to Playwright...');
- } catch (pythonError) {
- logger.warn('[Xiaohongshu Comments] Python API failed:', pythonError);
- }
- }
- // 回退到 Playwright 方式
- const browser = await chromium.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.xiaohongshu.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 用于捕获评论数据
- const capturedComments: Map<string, CommentItem[]> = new Map();
- const capturedNotes: Array<{
- noteId: string;
- title: string;
- coverUrl: string;
- }> = [];
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听笔记列表 API
- if (url.includes('/api/galaxy/creator/content/note_list') ||
- url.includes('/api/galaxy/creator/notes')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
- const notes = data?.data?.notes || data?.data?.list || [];
- for (const note of notes) {
- capturedNotes.push({
- noteId: note.note_id || note.id || '',
- title: note.title || note.desc || '',
- coverUrl: note.cover?.url || note.cover || '',
- });
- }
- }
- // 监听评论列表 API
- if (url.includes('/api/sns/web/v2/comment/page') ||
- url.includes('/api/galaxy/creator/comment') ||
- url.includes('/api/sns/v1/note/comment')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
- const comments: CommentItem[] = [];
- const commentList = data?.data?.comments || data?.comments || [];
- for (const comment of commentList) {
- comments.push({
- commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
- authorId: comment.user_info?.user_id || comment.user_id || '',
- authorName: comment.user_info?.nickname || comment.nickname || '',
- authorAvatar: comment.user_info?.image || comment.avatar || '',
- content: comment.content || '',
- likeCount: comment.like_count || 0,
- commentTime: comment.create_time || comment.time || '',
- parentCommentId: comment.target_comment_id || undefined,
- });
- // 处理子评论
- const subComments = comment.sub_comments || comment.replies || [];
- for (const sub of subComments) {
- comments.push({
- commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
- authorId: sub.user_info?.user_id || sub.user_id || '',
- authorName: sub.user_info?.nickname || sub.nickname || '',
- authorAvatar: sub.user_info?.image || sub.avatar || '',
- content: sub.content || '',
- likeCount: sub.like_count || 0,
- commentTime: sub.create_time || sub.time || '',
- parentCommentId: comment.id || comment.comment_id || undefined,
- });
- }
- }
- // 尝试从 URL 获取笔记 ID
- const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
- const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;
- if (comments.length > 0) {
- const existing = capturedComments.get(noteId) || [];
- capturedComments.set(noteId, [...existing, ...comments]);
- }
- }
- } catch { }
- });
- // 导航到评论管理页面
- logger.info('[Xiaohongshu Comments] Navigating to comment management...');
- await page.goto('https://creator.xiaohongshu.com/creator/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
- await browser.close();
- return allWorkComments;
- }
- // 尝试加载更多评论
- for (let i = 0; i < 5; i++) {
- await page.evaluate(() => {
- window.scrollBy(0, 500);
- });
- await page.waitForTimeout(1000);
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 将捕获的评论转换为 WorkComments 格式
- for (const [noteId, comments] of capturedComments) {
- const noteInfo = capturedNotes.find(n => n.noteId === noteId);
- allWorkComments.push({
- videoId: noteId,
- videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
- videoCoverUrl: noteInfo?.coverUrl || '',
- comments,
- });
- }
- // 如果没有从 API 获取到评论,尝试从页面提取
- if (allWorkComments.length === 0) {
- logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');
- const pageComments = await page.evaluate(() => {
- const result: Array<{
- commentId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
- commentItems.forEach((item, index) => {
- try {
- const authorEl = item.querySelector('[class*="author"], [class*="name"]');
- const avatarEl = item.querySelector('img');
- const contentEl = item.querySelector('[class*="content"]');
- const timeEl = item.querySelector('[class*="time"]');
- const likeEl = item.querySelector('[class*="like"] span');
- result.push({
- commentId: `xhs_page_${index}`,
- authorName: authorEl?.textContent?.trim() || '',
- authorAvatar: avatarEl?.src || '',
- content: contentEl?.textContent?.trim() || '',
- likeCount: parseInt(likeEl?.textContent || '0') || 0,
- commentTime: timeEl?.textContent?.trim() || '',
- });
- } catch { }
- });
- return result;
- });
- if (pageComments.length > 0) {
- allWorkComments.push({
- videoId: 'page_comments',
- videoTitle: '页面评论',
- videoCoverUrl: '',
- comments: pageComments.map(c => ({
- ...c,
- authorId: '',
- })),
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
- logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('[Xiaohongshu Comments] Error:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- }
- export const headlessBrowserService = new HeadlessBrowserService();
|