| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191 |
- /// <reference lib="dom" />
- import { chromium, type BrowserContext, type Page } from 'playwright';
- import { logger } from '../utils/logger.js';
- import { extractDeclaredNotesCountFromPostedResponse } from '../utils/xiaohongshu.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' 或其他异常状态(兼容 normal 等常见正常状态)
- const userStatus = resp?.data?.user?.status;
- const isStatusOk = !userStatus || ['audit', 'pass', 'active', 'normal'].includes(String(userStatus));
- 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[];
- worksListComplete?: boolean;
- source?: 'python' | 'playwright' | 'api';
- pythonAvailable?: boolean;
- }
- export interface WorkItem {
- videoId?: string;
- title: string;
- coverUrl: string;
- /** 作品播放/详情页 URL,同步到 works.video_url */
- videoUrl?: string;
- duration: string;
- publishTime: string;
- status: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- collectCount?: 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;
- }
- export type CookieCheckSource = 'python' | 'api' | 'browser';
- export type CookieCheckReason =
- | 'valid'
- | 'need_login'
- | 'risk_control'
- | 'uncertain';
- export interface CookieCheckResult {
- isValid: boolean;
- needReLogin: boolean;
- uncertain: boolean;
- reason: CookieCheckReason;
- source: CookieCheckSource;
- message?: string;
- }
- /**
- * 无头浏览器服务 - 用于后台静默获取账号信息
- */
- class HeadlessBrowserService {
- /**
- * 检查 Cookie 是否有效
- * 优先使用 Python 服务(通过浏览器访问后台检测),回退到 API 检查
- */
- async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- const status = await this.checkCookieStatus(platform, cookies);
- return status.isValid || status.uncertain;
- }
- /**
- * 检查 Cookie 状态(有效 / 需要重新登录 / 不确定)
- */
- async checkCookieStatus(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
- logger.info(`[checkCookieStatus] Checking cookie for ${platform}, cookie count: ${cookies.length}`);
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- try {
- const result = await this.checkLoginStatusViaPython(platform, cookies);
- logger.info(
- `[checkCookieStatus] Python result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
- );
- return result;
- } catch (error) {
- logger.warn(`[Python API] Check login failed, falling back:`, error);
- }
- } else {
- logger.info(`[checkCookieStatus] Python service not available`);
- }
- const apiConfig = PLATFORM_API_CONFIG[platform];
- if (apiConfig) {
- const result = await this.checkCookieStatusByApi(platform, cookies, apiConfig);
- logger.info(
- `[checkCookieStatus] API result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
- );
- return result;
- }
- const result = await this.checkCookieStatusByBrowser(platform, cookies);
- logger.info(
- `[checkCookieStatus] Browser result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
- );
- return result;
- }
- private containsRiskKeywords(text: string): boolean {
- if (!text) return false;
- const lowered = text.toLowerCase();
- const keywords = [
- '验证码',
- '安全验证',
- '人机验证',
- '滑块',
- '风控',
- '风险',
- '访问受限',
- '行为异常',
- '系统检测到异常',
- '安全校验',
- 'captcha',
- 'verify',
- 'challenge',
- 'risk',
- 'security',
- 'safe',
- 'protect',
- 'blocked',
- ];
- return keywords.some(k => lowered.includes(k.toLowerCase()));
- }
- private async getPageBodyTextSafe(page: Page): Promise<string> {
- try {
- const content = await page.textContent('body');
- return (content || '').slice(0, 8000);
- } catch {
- return '';
- }
- }
- /**
- * 通过 Python 服务检查登录状态(浏览器访问后台页面,检测是否需要登录)
- */
- private async checkLoginStatusViaPython(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
- 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');
- }
- const message = result.message || result.error || '';
- if (!result.valid || result.need_login) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: this.containsRiskKeywords(message) ? 'risk_control' : 'need_login',
- source: 'python',
- message,
- };
- }
- if (this.containsRiskKeywords(message)) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'python',
- message,
- };
- }
- return {
- isValid: true,
- needReLogin: false,
- uncertain: false,
- reason: 'valid',
- source: 'python',
- message,
- };
- }
- /**
- * 通过 API 检查 Cookie 是否有效
- * 注意:API 返回不确定状态时会回退到浏览器检查,避免误判
- */
- private async checkCookieStatusByApi(
- platform: PlatformType,
- cookies: CookieData[],
- apiConfig: typeof PLATFORM_API_CONFIG[string]
- ): Promise<CookieCheckResult> {
- 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) {
- const rawText = JSON.stringify(data).slice(0, 2000);
- if (this.containsRiskKeywords(rawText)) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'api',
- message: 'API 返回疑似风控/验证页面',
- };
- }
- return {
- isValid: true,
- needReLogin: false,
- uncertain: false,
- reason: 'valid',
- source: 'api',
- };
- }
- // 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 {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'need_login',
- source: 'api',
- };
- }
- // 百家号特殊处理:API 用 Node fetch 调用时可能因分散认证等返回 errno !== 0,但 Cookie 在浏览器内仍有效
- // 因此当 API 判为无效时,回退到浏览器检查,避免“能登录后台却显示过期”
- if (platform === 'baijiahao') {
- const errno = (data as { errno?: number })?.errno;
- if (errno === 0 && isValid) {
- return { isValid: true, needReLogin: false, uncertain: false, reason: 'valid', source: 'api' };
- }
- if (errno === 0 && !isValid) {
- logger.warn(`[API] Baijiahao errno=0 but no user info, falling back to browser check`);
- return this.checkCookieStatusByBrowser(platform, cookies);
- }
- // errno 110 通常表示未登录,可直接判无效;其他 errno(如 10001402 分散认证)可能只是接口限制,用浏览器再判一次
- if (errno === 110) {
- logger.warn(`[API] Baijiahao errno=110 (not logged in), cookie invalid`);
- return { isValid: false, needReLogin: true, uncertain: false, reason: 'need_login', source: 'api' };
- }
- logger.info(`[API] Baijiahao errno=${errno}, falling back to browser check (may be dispersed auth)`);
- return this.checkCookieStatusByBrowser(platform, cookies);
- }
- // 不确定的状态(如 status_code=7),回退到浏览器检查
- logger.info(`[API] Uncertain status for ${platform} (statusCode=${statusCode}), falling back to browser check`);
- return this.checkCookieStatusByBrowser(platform, cookies);
- } catch (error) {
- logger.error(`API check cookie error for ${platform}:`, error);
- // API 检查失败时,回退到浏览器检查
- return this.checkCookieStatusByBrowser(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 checkCookieStatusByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
- // 对于抖音平台,使用 check/user 接口检查
- if (platform === 'douyin') {
- return this.checkDouyinLoginStatusByApi(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));
- const bodyText = await this.getPageBodyTextSafe(page);
- const isRiskControl = this.containsRiskKeywords(url) || this.containsRiskKeywords(bodyText);
- await page.close();
- await context.close();
- await browser.close();
- if (isLoginPage) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'need_login',
- source: 'browser',
- };
- }
- if (isRiskControl) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'browser',
- message: '检测到风控/验证页面',
- };
- }
- return {
- isValid: true,
- needReLogin: false,
- uncertain: false,
- reason: 'valid',
- source: 'browser',
- };
- } catch (error) {
- logger.error(`Browser check cookie error for ${platform}:`, error);
- await browser.close();
- return {
- isValid: false,
- needReLogin: false,
- uncertain: true,
- reason: 'uncertain',
- source: 'browser',
- message: error instanceof Error ? error.message : 'Browser check error',
- };
- }
- }
- /**
- * 抖音登录状态检查 - 通过监听 check/user 接口
- * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
- */
- private async checkDouyinLoginStatusByApi(cookies: CookieData[]): Promise<CookieCheckResult> {
- const browser = await chromium.launch({ headless: true });
- let isLoggedIn = false;
- let checkCompleted = false;
- let isRiskControl = 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}`);
- }
- const finalUrl = page.url();
- const bodyText = await this.getPageBodyTextSafe(page);
- isRiskControl = this.containsRiskKeywords(finalUrl) || this.containsRiskKeywords(bodyText);
- await page.close();
- await context.close();
- await browser.close();
- if (isRiskControl) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'browser',
- message: '检测到风控/验证页面',
- };
- }
- return {
- isValid: isLoggedIn,
- needReLogin: !isLoggedIn,
- uncertain: false,
- reason: isLoggedIn ? 'valid' : 'need_login',
- source: 'browser',
- };
- } catch (error) {
- logger.error('[Douyin] checkDouyinLoginByApi error:', error);
- try {
- await browser.close();
- } catch { }
- return {
- isValid: false,
- needReLogin: false,
- uncertain: true,
- reason: 'uncertain',
- source: 'browser',
- message: error instanceof Error ? error.message : 'Douyin check error',
- };
- }
- }
- /**
- * 访问平台后台页面并截图(用于 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[],
- onPage?: (info: {
- platform: PlatformType;
- page: string;
- pageSize: number;
- fetched: number;
- newCount: number;
- totalSoFar: number;
- declaredTotal?: number;
- hasMore: boolean;
- nextPage?: unknown;
- }) => void
- ): Promise<{
- works: WorkItem[];
- total?: number;
- }> {
- logger.info(`[Python API] Fetching works for ${platform} (auto pagination)...`);
- const cookieString = JSON.stringify(cookies);
- const pythonPlatform = platform === 'weixin_video' ? 'weixin' : platform;
- // 抖音 work_list 接口 count 最大 20,需与创作者中心一致
- const pageSize = platform === 'xiaohongshu' ? 20 : platform === 'douyin' ? 20 : 50;
- let maxPages = 30;
- const allWorks: WorkItem[] = [];
- const seenIds = new Set<string>();
- const legacyToCanonical = new Map<string, string>();
- let declaredTotal: number | undefined;
- let cursor: string | number = 0;
- const seenCursors = new Set<string>();
- // 抖音、小红书使用 cursor 分页;视频号使用 currentPage 页码(pageIndex 0,1,2...)
- const useCursorPagination = platform === 'xiaohongshu' || platform === 'douyin';
- for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
- const pageParam: number | string = useCursorPagination ? cursor : pageIndex;
- logger.info(`[Python API] Fetching works page=${String(pageParam)}, page_size=${pageSize} for ${platform}`);
- logger.info(`[Python API] 调用 Python /works: platform=${platform} -> pythonPlatform=${pythonPlatform}, page=${String(pageParam)}, url=${PYTHON_SERVICE_URL}`);
- const response: Response = await fetch(`${PYTHON_SERVICE_URL}/works`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- platform: pythonPlatform,
- cookie: cookieString,
- page: pageParam,
- page_size: pageSize,
- auto_paging: platform === 'xiaohongshu' && pageIndex === 0,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API returned ${response.status}`);
- }
- const result: any = await response.json();
- if (pageIndex === 0) {
- logger.info(`[Python API] Response for ${platform}: success=${result.success}, works_count=${result.works?.length || 0}, total=${result.total || 0}, has_more=${result.has_more}, error=${result.error || 'none'}`);
- if (result.error) {
- logger.warn(`[Python API] Error from Python service: ${result.error}`);
- }
- }
- if (!result.success) {
- logger.error(`[Python API] Python service returned error: ${result.error || 'Unknown error'}, full response: ${JSON.stringify(result).substring(0, 500)}`);
- throw new Error(result.error || 'Failed to get works');
- }
- if (typeof result.total === 'number' && result.total > 0) {
- declaredTotal = declaredTotal ? Math.max(declaredTotal, result.total) : result.total;
- if (pageIndex === 0) {
- maxPages = Math.min(400, Math.ceil(result.total / pageSize) + 5);
- }
- }
- const pageWorks: WorkItem[] = (result.works || []).map((work: {
- work_id: string;
- title: string;
- cover_url: string;
- video_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,
- videoUrl: work.video_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,
- collectCount: work.collect_count ?? 0,
- }));
- let newCount = 0;
- for (const w of pageWorks) {
- const titleForId = (w.title || '').trim();
- const publishTimeForId = (w.publishTime || '').trim();
- const legacyId = `${platform}_${titleForId}_${publishTimeForId}`.substring(0, 100);
- let canonicalId = (w.videoId || '').trim() || legacyId;
- if (platform === 'weixin_video') {
- const rawId = (w.videoId || '').trim();
- if (rawId) {
- legacyToCanonical.set(legacyId, rawId);
- canonicalId = rawId;
- } else {
- const mapped = legacyToCanonical.get(legacyId);
- if (mapped) canonicalId = mapped;
- }
- }
- if (!seenIds.has(canonicalId)) {
- seenIds.add(canonicalId);
- allWorks.push({
- ...w,
- videoId: canonicalId,
- });
- newCount++;
- }
- }
- logger.info(
- `[Python API] Page ${String(pageParam)} fetched=${pageWorks.length}, new=${newCount}, total=${allWorks.length}, has_more=${!!result.has_more}, declared_total=${declaredTotal || 0}, next_page=${String(result.next_page ?? '')}`
- );
- onPage?.({
- platform,
- page: String(pageParam),
- pageSize,
- fetched: pageWorks.length,
- newCount,
- totalSoFar: allWorks.length,
- declaredTotal,
- hasMore: !!result.has_more,
- nextPage: result.next_page,
- });
- if (useCursorPagination) {
- const next: any = result.next_page;
- const hasNextCursor = next !== undefined && next !== null && next !== '' && next !== -1 && next !== '-1';
- if (hasNextCursor) {
- const key = String(next);
- if (seenCursors.has(key)) break;
- seenCursors.add(key);
- cursor = next;
- } else {
- if (platform === 'douyin') break;
- cursor = (typeof cursor === 'number' ? cursor + 1 : pageIndex + 1);
- }
- // 抖音:仅当无下一页游标或本页 0 条时停止
- if (platform === 'douyin') {
- if (!hasNextCursor || pageWorks.length === 0) break;
- } else {
- const expectedMore = declaredTotal && declaredTotal > 0 ? allWorks.length < declaredTotal : !!result.has_more;
- if (!expectedMore || pageWorks.length === 0 || newCount === 0) break;
- }
- } else {
- if (!result.has_more || pageWorks.length === 0 || newCount === 0) break;
- }
- }
- logger.info(`[Python API] Total works fetched for ${platform}: ${allWorks.length}`);
- return { works: allWorks, total: declaredTotal };
- }
- /**
- * 获取账号信息(优先使用 Python API,回退到无头浏览器)
- */
- async fetchAccountInfo(
- platform: PlatformType,
- cookies: CookieData[],
- options?: {
- onWorksFetchProgress?: (info: {
- platform: PlatformType;
- page: string;
- pageSize: number;
- fetched: number;
- newCount: number;
- totalSoFar: number;
- declaredTotal?: number;
- hasMore: boolean;
- nextPage?: unknown;
- }) => void;
- }
- ): Promise<AccountInfo> {
- logger.info(`[fetchAccountInfo] Starting for platform: ${platform}`);
- let pythonAvailable = false;
- // 百家号:优先走 Python 的 /account_info(包含粉丝数、作品数),避免 Node 直连分散认证问题
- if (platform === 'baijiahao') {
- pythonAvailable = await this.checkPythonServiceAvailable();
- let info: AccountInfo;
- if (pythonAvailable) {
- logger.info(`[Python API] Service available, fetching account_info for baijiahao`);
- try {
- info = await this.fetchAccountInfoViaPython(platform, cookies);
- info.source = 'python';
- info.pythonAvailable = true;
- } catch (error) {
- logger.warn(`[Python API] Failed to fetch account_info for baijiahao, will still try /works:`, error);
- info = this.getDefaultAccountInfo(platform);
- info.source = 'python';
- info.pythonAvailable = true;
- }
- } else {
- logger.info(`[Python API] Service not available for baijiahao, falling back to direct API`);
- // Python 不可用时,回退到 Node 直连 API(可能仍会遇到分散认证问题)
- info = await this.fetchBaijiahaoAccountInfoDirectApi(cookies);
- info.source = 'api';
- info.pythonAvailable = false;
- }
- // 百家号同步作品需要全量:优先通过 Python /works 自动分页拉取
- if (pythonAvailable) {
- try {
- const { works: worksList, total: worksTotal } = await this.fetchWorksViaPython(
- platform,
- cookies,
- options?.onWorksFetchProgress
- );
- info.worksList = worksList;
- if (worksTotal && worksTotal > 0) {
- info.worksCount = worksTotal;
- info.worksListComplete = worksList.length >= worksTotal;
- } else if (worksList.length > 0) {
- info.worksCount = Math.max(info.worksCount || 0, worksList.length);
- info.worksListComplete = undefined;
- }
- info.source = 'python';
- info.pythonAvailable = true;
- } catch (error) {
- logger.warn(`[Python API] Failed to fetch works for baijiahao:`, error);
- }
- }
- return info;
- }
- // 对于支持的平台,尝试使用 Python API 获取作品列表和账号信息
- // 同步作品需要全量:这里会通过 Python /works 自动分页拉取
- const supportedPlatforms: PlatformType[] = ['douyin', 'xiaohongshu', 'kuaishou', 'weixin_video', 'baijiahao'];
- if (supportedPlatforms.includes(platform)) {
- pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info(`[Python API] Service available, trying to fetch works for ${platform}`);
- try {
- const { works: worksList, total: worksTotal } = await this.fetchWorksViaPython(
- platform,
- cookies,
- options?.onWorksFetchProgress
- );
- // 如果成功获取到作品,使用 Playwright 获取账号基本信息
- if (worksList.length > 0) {
- logger.info(`[Python API] Successfully fetched ${worksList.length} works for ${platform}`);
- try {
- let accountInfo: AccountInfo;
- // 对于小红书,优先使用 Python API 获取账号信息(因为 Node 端 Playwright 可能无法捕获到 API)
- if (platform === 'xiaohongshu') {
- try {
- accountInfo = await this.fetchAccountInfoViaPython(platform, cookies);
- } catch (e) {
- logger.warn(`[Python API] Failed to fetch account info for ${platform}, falling back to Playwright:`, e);
- accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- }
- } else {
- accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- }
- accountInfo.worksList = worksList;
- // 账号展示的作品数优先用 Python 返回的 total(更接近创作者中心“全部笔记”),否则回退到抓到的列表长度
- accountInfo.worksCount = worksTotal && worksTotal > 0 ? worksTotal : worksList.length;
- accountInfo.worksListComplete = worksTotal && worksTotal > 0 ? worksList.length >= worksTotal : undefined;
- accountInfo.source = 'python';
- accountInfo.pythonAvailable = true;
- 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 = worksTotal && worksTotal > 0 ? worksTotal : worksList.length;
- accountInfo.worksListComplete = worksTotal && worksTotal > 0 ? worksList.length >= worksTotal : undefined;
- accountInfo.source = 'python';
- accountInfo.pythonAvailable = true;
- return accountInfo;
- }
- }
- // 作品列表为空,尝试用 Playwright 获取账号信息
- if (worksTotal > 0 && worksList.length === 0) {
- logger.warn(`[Python API] Warning: API reported ${worksTotal} works but returned empty list for ${platform}`);
- logger.warn(`[Python API] This may indicate a bug in Python API or API format change`);
- } else {
- logger.info(`[Python API] Got empty works list for ${platform} (total=${worksTotal}), trying Playwright`);
- }
- } catch (pythonError) {
- logger.warn(`[Python API] Failed to fetch works for ${platform}:`, pythonError);
- logger.warn(`[Python API] Error details:`, pythonError instanceof Error ? pythonError.message : String(pythonError));
- }
- } else {
- logger.info(`[Python API] Service not available for ${platform}`);
- }
- }
- // 使用 Playwright 获取账号信息
- logger.info(`[Playwright] Fetching account info for ${platform}`);
- const info = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- info.source = 'playwright';
- info.pythonAvailable = pythonAvailable;
- return info;
- }
- /**
- * 使用 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: number | undefined;
- 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; collect_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;
- }
- }
- // 解析作品列表;video_url 使用 video.play_addr.url_list 的第一项
- 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] || '';
- const video = aweme.video as { play_addr?: { url_list?: string[] } } | undefined;
- const videoUrl = video?.play_addr?.url_list?.[0] || '';
- return {
- awemeId: String(aweme.aweme_id || ''),
- title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
- coverUrl,
- videoUrl,
- 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),
- collect_count: Number((statistics as any).collect_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);
- logger.info(`[Douyin] fetchWorksDirectApi returned: works.length=${apiResult.works.length}, total=${apiResult.total}`);
-
- 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,
- videoUrl: (w as { videoUrl?: string }).videoUrl || (w.awemeId ? `https://www.douyin.com/video/${w.awemeId}` : ''),
- duration: '00:00',
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: w.playCount,
- likeCount: w.likeCount,
- commentCount: w.commentCount,
- shareCount: w.shareCount,
- collectCount: w.collectCount,
- }));
- logger.info(`[Douyin] Got ${apiResult.works.length} works from API, total count: ${worksCount}`);
- } else {
- logger.warn(`[Douyin] fetchWorksDirectApi returned 0 works`);
- if (capturedData.worksList && capturedData.worksList.length > 0) {
- // 如果直接 API 调用失败,使用监听到的数据
- logger.info(`[Douyin] Falling back to intercepted API data: ${capturedData.worksList.length} works`);
- worksCount = capturedData.total || capturedData.worksList.length;
- worksList = capturedData.worksList.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- videoUrl: (w as { videoUrl?: string }).videoUrl || (w.awemeId ? `https://www.douyin.com/video/${w.awemeId}` : ''),
- 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,
- collectCount: w.statistics.collect_count,
- }));
- logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
- } else {
- logger.warn(`[Douyin] No works found: fetchWorksDirectApi returned 0, intercepted data also empty`);
- logger.warn(`[Douyin] This may indicate: cookie expired, API error, or account has no works`);
- }
- }
- } catch (error) {
- logger.error('Failed to fetch Douyin account info:', error);
- logger.error('Error details:', error instanceof Error ? error.stack : String(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: number | undefined;
- 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: number | undefined;
- 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: number | undefined;
- 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: number | undefined;
- 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');
- // 返回空信息,fansCount 为 undefined,避免重置为 0
- return { accountId, accountName, avatarUrl, fansCount: undefined, worksCount: 0 };
- }
- // 等待 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 !== undefined) {
- fansCount = capturedData.userInfo.fans;
- }
- if (capturedData.userInfo.notes !== undefined) {
- 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[] = [];
- let worksListComplete: boolean | undefined;
- 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 maxPages = 120;
- // 设置 API 响应监听器 - 在导航之前绑定
- let apiResponseReceived = false;
- let totalNotesCount = 0; // 从 tags 中获取的总作品数
- let stoppedByMaxPages = false;
- const seenNoteIds = new Set<string>();
- const upsertNotesFromPayload = (payload: any) => {
- if (!payload) return;
- const declaredTotal = extractDeclaredNotesCountFromPostedResponse(payload);
- if (declaredTotal > 0) {
- totalNotesCount = Math.max(totalNotesCount, declaredTotal);
- }
- if (totalNotesCount > 0) {
- const estimatedPages = Math.ceil(totalNotesCount / 20) + 5;
- maxPages = Math.max(maxPages, Math.min(500, estimatedPages));
- }
- const notes = payload.notes || [];
- for (const note of notes) {
- const noteId = note.id || '';
- if (!noteId || seenNoteIds.has(noteId)) continue;
- seenNoteIds.add(noteId);
- 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,
- title: note.display_title || '',
- coverUrl,
- status: note.tab_status || 1,
- publishTime: note.time || '',
- type: note.type || 'normal',
- 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,
- });
- }
- };
- const fetchNotesPage = async (pageNum: number) => {
- return 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',
- headers: {
- Accept: 'application/json',
- },
- }
- );
- return await response.json();
- }, pageNum);
- };
- 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;
- upsertNotesFromPayload(data.data);
- } else {
- }
- }
- } 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 {
- const apiResponse = await fetchNotesPage(0);
- logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
- if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
- upsertNotesFromPayload(apiResponse.data);
- }
- } catch (apiError) {
- logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
- }
- }
- if (allNotesData.length > 0) {
- let pageNum = 1;
- while (pageNum < maxPages) {
- if (totalNotesCount > 0 && seenNoteIds.size >= totalNotesCount) break;
- let nextResponse: any;
- try {
- nextResponse = await fetchNotesPage(pageNum);
- } catch (e) {
- logger.warn(`[Xiaohongshu] Page fetch failed: page=${pageNum}`, e);
- break;
- }
- if (!(nextResponse?.success || nextResponse?.code === 0) || !nextResponse?.data) break;
- const before = seenNoteIds.size;
- upsertNotesFromPayload(nextResponse.data);
- const after = seenNoteIds.size;
- if (after === before) break;
- pageNum++;
- await page.waitForTimeout(600);
- }
- if (pageNum >= maxPages) stoppedByMaxPages = true;
- }
- // 移除监听器
- 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,
- videoUrl: note.noteId ? `https://www.xiaohongshu.com/explore/${note.noteId}` : '',
- 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`);
- if (totalNotesCount > 0) {
- worksListComplete = worksList.length >= totalNotesCount;
- worksCount = totalNotesCount;
- } else if (worksList.length > 0) {
- worksListComplete = !stoppedByMaxPages;
- worksCount = worksList.length;
- }
- } 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, worksListComplete };
- } 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.html', '/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...`);
- // 构建 Cookie 字符串,确保格式正确
- const cookieString = cookies
- .map(c => `${c.name.trim()}=${c.value.trim()}`)
- .filter(c => c.includes('=')) // 过滤掉无效的 cookie
- .join('; ');
- logger.debug(`[Baijiahao API] Cookie string length: ${cookieString.length}, cookie count: ${cookies.length}`);
- const headers: Record<string, string> = {
- 'Accept': '*/*',
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Accept-Encoding': 'gzip, deflate, br',
- 'Connection': 'keep-alive',
- 'Cookie': cookieString,
- // 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
- // 'Origin': 'https://baijiahao.baidu.com',
- '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-Fetch-Dest': 'empty',
- // 'Sec-Fetch-Mode': 'cors',
- // 'Sec-Fetch-Site': 'same-origin',
- };
- let accountInfo: AccountInfo = this.getDefaultAccountInfo('baijiahao');
- // 标记哪些字段已成功获取
- let fansCountFetched = false;
- let worksCountFetched = false;
- 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) {
- const fansCount = growthData.data.total_fans;
- if (fansCount !== undefined && fansCount !== null) {
- accountInfo.fansCount = fansCount;
- fansCountFetched = true;
- logger.info(`[Baijiahao API] Got fans count: ${accountInfo.fansCount}`);
- } else {
- logger.warn(`[Baijiahao API] growth info API returned no fans count`);
- }
- } 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...`);
- setTimeout(() => {
- console.log('1000ms');
- }, 1000);
- const worksList: WorkItem[] = [];
- let currentPage = 1;
- const pageSize = 20;
- let hasMore = true;
- let totalWorks = 0;
- let worksListError = false;
- while (hasMore && !worksListError) {
- 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}...`);
- logger.debug(`[Baijiahao API] Request headers include Cookie: ${!!headers.Cookie}, Cookie length: ${headers.Cookie?.length || 0}`);
- const listResponse = await fetch(listUrl, {
- method: 'GET',
- headers,
- });
- if (!listResponse.ok) {
- const errorText = await listResponse.text();
- logger.warn(`[Baijiahao API] Failed to fetch works list page ${currentPage}: ${listResponse.status}`);
- logger.warn(`[Baijiahao API] Error response body: ${errorText}`);
- break;
- }
- const responseText = await listResponse.text();
- logger.info(`[Baijiahao API] ========== Works API Response (Page ${currentPage}) ==========`);
- logger.info(`[Baijiahao API] Full response: ${responseText}`);
- logger.info(`[Baijiahao API] ============================================================`);
- const listData = JSON.parse(responseText) as {
- errno?: number;
- errmsg?: string;
- data?: {
- list?: Array<{
- id?: string;
- article_id?: string;
- title?: string;
- cover_images?: string | string[];
- created_at?: string;
- create_time?: string;
- status?: string;
- read_amount?: number;
- read_count?: number;
- like_amount?: number;
- like_count?: number;
- comment_amount?: number;
- comment_count?: number;
- share_amount?: number;
- share_count?: number;
- }>;
- page?: {
- currentPage?: number;
- pageSize?: number;
- totalCount?: number;
- totalPage?: number;
- };
- total?: number; // 兼容旧格式
- };
- };
- // 处理分散认证问题 (errno=10001402),重试一次
- if (listData.errno === 10001402) {
- logger.warn(`[Baijiahao API] Dispersed authentication issue (errno=10001402) on page ${currentPage}, retrying after 3 seconds...`);
- logger.debug(`[Baijiahao API] Request URL: ${listUrl}`);
- logger.debug(`[Baijiahao API] Cookie header present: ${!!headers.Cookie}, length: ${headers.Cookie?.length || 0}`);
- await new Promise(resolve => setTimeout(resolve, 3000));
- // 重试一次,确保 headers 包含 Cookie
- const retryResponse = await fetch(listUrl, {
- method: 'GET',
- headers: {
- ...headers,
- 'Cookie': cookieString, // 确保 Cookie 被正确传递
- },
- });
- if (retryResponse.ok) {
- const retryResponseText = await retryResponse.text();
- logger.info(`[Baijiahao API] ========== Works API Retry Response (Page ${currentPage}) ==========`);
- logger.info(`[Baijiahao API] Full retry response: ${retryResponseText}`);
- logger.info(`[Baijiahao API] ============================================================`);
- const retryData = JSON.parse(retryResponseText) as typeof listData;
- if (retryData.errno === 0) {
- logger.info(`[Baijiahao API] Retry successful for page ${currentPage}`);
- Object.assign(listData, retryData);
- } else if (retryData.errno === 10001402) {
- logger.error(`[Baijiahao API] Retry still failed with errno=10001402, cookie may be invalid or expired`);
- logger.error(`[Baijiahao API] Retry response data: ${JSON.stringify(retryData, null, 2)}`);
- // 如果重试仍然失败,可能是 Cookie 问题,记录详细信息
- logger.error(`[Baijiahao API] Cookie info: ${cookieString.substring(0, 200)}...`);
- // 标记错误,但不完全失败,继续返回已获取的账号信息
- worksListError = true;
- logger.warn(`[Baijiahao API] Works list fetch failed, but will return other account info (name, fans count)`);
- break;
- } else {
- logger.warn(`[Baijiahao API] Retry still failed: errno=${retryData.errno}, errmsg=${retryData.errmsg}`);
- break;
- }
- } else {
- logger.warn(`[Baijiahao API] Retry request failed: ${retryResponse.status}`);
- break;
- }
- }
- if (listData.errno !== 0) {
- logger.warn(`[Baijiahao API] API returned error on page ${currentPage}: errno=${listData.errno}, errmsg=${listData.errmsg}`);
- logger.warn(`[Baijiahao API] Error response data: ${JSON.stringify(listData, null, 2)}`);
- // 如果不是 10001402 错误,标记为错误但继续返回其他信息
- if (listData.errno !== 10001402) {
- worksListError = true;
- logger.warn(`[Baijiahao API] Works list fetch failed with errno=${listData.errno}, but will return other account info`);
- }
- break;
- }
- const list = listData.data?.list || [];
- // 优先使用 data.page.totalCount,如果没有则使用 data.total(兼容旧格式)
- totalWorks = listData.data?.page?.totalCount || listData.data?.total || 0;
- logger.info(`[Baijiahao API] Got ${list.length} works on page ${currentPage}, total: ${totalWorks}`);
- for (const item of list) {
- // 处理 cover_images 可能是字符串(JSON)或数组
- let coverUrl = '';
- if (item.cover_images) {
- if (Array.isArray(item.cover_images)) {
- coverUrl = item.cover_images[0] || '';
- } else if (typeof item.cover_images === 'string') {
- try {
- const coverArray = JSON.parse(item.cover_images);
- if (Array.isArray(coverArray) && coverArray.length > 0) {
- coverUrl = typeof coverArray[0] === 'string' ? coverArray[0] : coverArray[0]?.src || coverArray[0]?.ori_src || '';
- }
- } catch {
- coverUrl = item.cover_images;
- }
- }
- }
- worksList.push({
- videoId: item.id || item.article_id || `bjh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
- title: item.title || '',
- coverUrl: coverUrl,
- videoUrl: item.url || item.article_url || '',
- duration: '00:00',
- publishTime: item.created_at || item.create_time || new Date().toISOString(),
- status: item.status || 'published',
- playCount: item.read_amount || item.read_count || 0,
- likeCount: item.like_amount || item.like_count || 0,
- commentCount: item.comment_amount || item.comment_count || 0,
- shareCount: item.share_amount || 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;
- // 使用 API 返回的 total 字段作为作品总数,而不是已获取的作品列表长度
- // 因为可能只获取了部分作品(最多 10 页),但 total 是真实的总数
- if (totalWorks > 0) {
- accountInfo.worksCount = totalWorks;
- worksCountFetched = true;
- } else if (worksList.length > 0) {
- // 如果 API 没有返回 total,但获取到了作品列表,使用列表长度
- accountInfo.worksCount = worksList.length;
- worksCountFetched = true;
- }
- if (worksListError) {
- logger.warn(`[Baijiahao API] Works list fetch encountered errors, but returning partial account info`);
- logger.info(`[Baijiahao API] Account info (partial): name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched})`);
- } else {
- logger.info(`[Baijiahao API] Successfully fetched account info: name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched}, API total: ${totalWorks}, fetched list: ${worksList.length})`);
- }
- 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,
- 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: undefined,
- 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...');
- const apiResult = await this.fetchWorksDirectApi(page);
- let works = apiResult.works;
- // 方式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;
- videoUrl?: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- collectCount: number;
- createTime?: number;
- }>;
- total: number;
- }> {
- const works: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- videoUrl?: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- collectCount: 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}`);
- logger.warn(`[DirectAPI] Error message: ${data?.err_msg || data?.errMsg || 'unknown'}`);
- // status_code: 8 表示未授权,可能需要重新登录
- if (data.status_code === 8) {
- logger.warn('[DirectAPI] status_code 8: Not authorized, may need re-login');
- }
- // 如果是第一页就出错,记录更详细的错误信息
- if (pageCount === 1) {
- logger.error(`[DirectAPI] First page failed with status_code ${data.status_code}, cannot fetch works`);
- logger.error(`[DirectAPI] Response data: ${JSON.stringify(data).substring(0, 500)}`);
- }
- break;
- }
-
- // 如果 status_code 是 0 但 aweme_list 为空,记录警告
- if (data?.status_code === 0 && awemeList.length === 0 && pageCount === 1) {
- logger.warn(`[DirectAPI] API returned success but aweme_list is empty on first page`);
- logger.warn(`[DirectAPI] Response data: ${JSON.stringify(data).substring(0, 500)}`);
- }
- // 优先从第一个作品的 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 playCount = parseInt(String(statistics.play_count || '0'), 10);
- const likeCount = parseInt(String(statistics.digg_count || '0'), 10); // 抖音用 digg_count 表示点赞
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- const shareCount = parseInt(String(statistics.share_count || '0'), 10);
- const collectCount = parseInt(String(statistics.collect_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];
- }
- // 入库 video_url 使用 play_addr.url_list 的第一项
- const videoUrl = aweme.video?.play_addr?.url_list?.[0] || '';
- works.push({
- awemeId,
- title,
- coverUrl,
- videoUrl,
- playCount,
- likeCount,
- commentCount,
- shareCount,
- collectCount,
- 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}`);
-
- // 如果总作品数 > 0 但实际获取到的作品数为 0,记录警告
- if (totalCount > 0 && works.length === 0) {
- logger.warn(`[DirectAPI] Warning: API reported ${totalCount} works but fetched 0 works`);
- logger.warn(`[DirectAPI] This may indicate: API error, cookie expired, or permission issue`);
- }
- } catch (e) {
- logger.error('[DirectAPI] Failed to fetch works:', e);
- logger.error('[DirectAPI] Error details:', e instanceof Error ? e.stack : String(e));
- }
- return { works, total: totalCount };
- }
- /**
- * 通过 Python API 获取评论 - 分作品逐个获取
- */
- private async fetchCommentsViaPythonApi(platform: 'douyin' | 'xiaohongshu' | 'weixin', 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;
- parent_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,
- parentCommentId: c.parent_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;
- }
- }
- /**
- * 获取微信视频号评论 - 优先使用 Python API
- */
- async fetchWeixinVideoCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 Python API(分作品获取)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Weixin Video Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('weixin', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Weixin Video Comments] Python API returned empty, falling back to Playwright...');
- } catch (pythonError) {
- logger.warn('[Weixin Video 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 || '.weixin.qq.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[Weixin Video Comments] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 用于捕获评论数据
- const capturedComments: Map<string, CommentItem[]> = new Map();
- const capturedWorks: Array<{
- workId: string;
- title: string;
- coverUrl: string;
- }> = [];
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听作品列表 API
- if (url.includes('/mmfinderassistant-bin/post/post_list')) {
- const data = await response.json();
- logger.info(`[Weixin Video API] Works list: ${JSON.stringify(data).slice(0, 500)}`);
- const posts = data?.data?.list || [];
- for (const post of posts) {
- capturedWorks.push({
- workId: post.objectNonce || post.id || '',
- title: post.title || post.desc || '',
- coverUrl: post.cover?.url || post.cover || '',
- });
- }
- }
- // 监听评论列表 API
- if (url.includes('/mmfinderassistant-bin/comment/comment_list')) {
- const data = await response.json();
- logger.info(`[Weixin Video API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
- const comments: CommentItem[] = [];
- const commentList = data?.data?.commentList || data?.comments || [];
- for (const comment of commentList) {
- comments.push({
- commentId: comment.commentId || comment.id || `weixin_${Date.now()}`,
- authorId: comment.commenterInfo?.identifier || comment.authorId || '',
- authorName: comment.commenterInfo?.nickName || comment.nickname || comment.nick_name || '',
- authorAvatar: comment.commenterInfo?.headUrl || comment.avatar || '',
- content: comment.content || '',
- likeCount: comment.likeCnt || comment.like_count || 0,
- commentTime: comment.createTime || comment.create_time || '',
- parentCommentId: comment.parentCommentId || undefined,
- });
- // 处理子评论
- const subComments = comment.subCommentList || comment.sub_comments || [];
- for (const sub of subComments) {
- comments.push({
- commentId: sub.commentId || sub.id || `weixin_sub_${Date.now()}`,
- authorId: sub.commenterInfo?.identifier || sub.authorId || '',
- authorName: sub.commenterInfo?.nickName || sub.nickname || sub.nick_name || '',
- authorAvatar: sub.commenterInfo?.headUrl || sub.avatar || '',
- content: sub.content || '',
- likeCount: sub.likeCnt || sub.like_count || 0,
- commentTime: sub.createTime || sub.create_time || '',
- parentCommentId: comment.commentId || comment.id || undefined,
- });
- }
- }
- // 尝试从 URL 获取作品 ID
- const workIdMatch = url.match(/objectNonce=([^&]+)/) || url.match(/workId=([^&]+)/);
- const workId = workIdMatch?.[1] || `work_${Date.now()}`;
- if (comments.length > 0) {
- const existing = capturedComments.get(workId) || [];
- capturedComments.set(workId, [...existing, ...comments]);
- }
- }
- } catch { }
- });
- // 导航到评论管理页面
- logger.info('[Weixin Video Comments] Navigating to comment management...');
- await page.goto('https://channels.weixin.qq.com/platform/interaction/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Weixin Video 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 [workId, comments] of capturedComments) {
- const workInfo = capturedWorks.find(w => w.workId === workId);
- allWorkComments.push({
- videoId: workId,
- videoTitle: workInfo?.title || `作品 ${workId.slice(0, 10)}`,
- videoCoverUrl: workInfo?.coverUrl || '',
- comments,
- });
- }
- // 如果没有从 API 获取到评论,尝试从页面提取
- if (allWorkComments.length === 0) {
- logger.info('[Weixin Video 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: `weixin_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(`[Weixin Video Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('[Weixin Video Comments] Error:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- }
- export const headlessBrowserService = new HeadlessBrowserService();
|