| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175 |
- /// <reference lib="dom" />
- import { chromium, type BrowserContext, type Page } from 'playwright';
- import { logger } from '../utils/logger.js';
- import type { PlatformType } from '@media-manager/shared';
- // 抖音 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;
- },
- },
- };
- export interface AccountInfo {
- accountId: string;
- accountName: string;
- avatarUrl: string;
- fansCount: number;
- worksCount: number;
- worksList?: WorkItem[];
- }
- export interface WorkItem {
- videoId?: string;
- title: string;
- coverUrl: string;
- duration: string;
- publishTime: string;
- status: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- }
- export interface CommentItem {
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- parentCommentId?: string;
- videoId?: string;
- videoTitle?: string;
- videoCoverUrl?: string;
- }
- export interface WorkComments {
- videoId: string;
- videoTitle: string;
- videoCoverUrl: string;
- comments: CommentItem[];
- }
- export interface CookieData {
- name: string;
- value: string;
- domain: string;
- path: string;
- }
- /**
- * 无头浏览器服务 - 用于后台静默获取账号信息
- */
- class HeadlessBrowserService {
- /**
- * 检查 Cookie 是否有效
- * 优先使用 API 检查,如果平台不支持 API 则使用浏览器检查
- */
- async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- // 优先使用 API 检查(更快更可靠)
- const apiConfig = PLATFORM_API_CONFIG[platform];
- if (apiConfig) {
- return this.checkCookieValidByApi(platform, cookies, apiConfig);
- }
- // 其他平台使用浏览器检查
- return this.checkCookieValidByBrowser(platform, cookies);
- }
- /**
- * 通过 API 检查 Cookie 是否有效
- */
- private async checkCookieValidByApi(
- platform: PlatformType,
- cookies: CookieData[],
- apiConfig: typeof PLATFORM_API_CONFIG[string]
- ): Promise<boolean> {
- try {
- // 构建 Cookie 字符串(所有 Cookie 拼接)
- const cookieString = cookies
- .map(c => `${c.name}=${c.value}`)
- .join('; ');
- logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);
- // 发起 API 请求,模拟浏览器请求
- const response = await fetch(apiConfig.checkUrl, {
- method: 'GET',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Cache-Control': 'no-cache',
- 'Cookie': cookieString,
- 'Pragma': 'no-cache',
- 'Referer': this.getPlatformReferer(platform),
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
- 'sec-ch-ua-mobile': '?0',
- 'sec-ch-ua-platform': '"Windows"',
- 'sec-fetch-dest': 'empty',
- 'sec-fetch-mode': 'cors',
- 'sec-fetch-site': 'same-origin',
- },
- });
- const data = await response.json();
- const isValid = apiConfig.isValidResponse(data);
- logger.info(`API check cookie for ${platform}: valid=${isValid}, status_code=${(data as { status_code?: number })?.status_code}`);
- return isValid;
- } catch (error) {
- logger.error(`API check cookie error for ${platform}:`, error);
- // API 检查失败时,回退到浏览器检查
- return this.checkCookieValidByBrowser(platform, cookies);
- }
- }
- /**
- * 获取平台 Referer
- */
- private getPlatformReferer(platform: PlatformType): string {
- const referers: Record<string, string> = {
- douyin: 'https://creator.douyin.com/',
- bilibili: 'https://member.bilibili.com/',
- kuaishou: 'https://cp.kuaishou.com/',
- };
- return referers[platform] || '';
- }
- /**
- * 通过浏览器检查 Cookie 是否有效(检查是否被重定向到登录页)
- */
- private async checkCookieValidByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- // 对于抖音平台,使用 check/user 接口检查
- if (platform === 'douyin') {
- return this.checkDouyinLoginByApi(cookies);
- }
- const browser = await chromium.launch({ headless: true });
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- const config = this.getPlatformConfig(platform);
- // 访问平台主页
- await page.goto(config.homeUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- const url = page.url();
- logger.info(`Browser check cookie for ${platform}: URL=${url}`);
- // 检查是否被重定向到登录页
- const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));
- await page.close();
- await context.close();
- await browser.close();
- return !isLoginPage;
- } catch (error) {
- logger.error(`Browser check cookie error for ${platform}:`, error);
- await browser.close();
- return false;
- }
- }
- /**
- * 抖音登录状态检查 - 通过监听 check/user 接口
- * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
- */
- async checkDouyinLoginByApi(cookies: CookieData[]): Promise<boolean> {
- const browser = await chromium.launch({ headless: true });
- let isLoggedIn = false;
- let checkCompleted = false;
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- // 监听 check/user 接口响应
- page.on('response', async (response) => {
- const url = response.url();
- if (url.includes(DOUYIN_API.CHECK_USER)) {
- try {
- const data = await response.json();
- // result: true 表示已登录
- isLoggedIn = data?.result === true && data?.status_code === 0;
- checkCompleted = true;
- logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
- } catch {
- // 忽略解析错误
- }
- }
- });
- // 访问创作者首页,触发 check/user 接口
- await page.goto(DOUYIN_API.CREATOR_HOME, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待接口响应或超时
- const startTime = Date.now();
- while (!checkCompleted && Date.now() - startTime < 10000) {
- await page.waitForTimeout(500);
- }
- // 如果没有收到 check/user 响应,检查 URL 是否被重定向到登录页
- if (!checkCompleted) {
- const currentUrl = page.url();
- isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
- logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
- }
- await page.close();
- await context.close();
- await browser.close();
- return isLoggedIn;
- } catch (error) {
- logger.error('[Douyin] checkDouyinLoginByApi error:', error);
- try {
- await browser.close();
- } catch { }
- return false;
- }
- }
- /**
- * 获取账号信息(使用无头浏览器)
- */
- async fetchAccountInfo(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;
- default:
- accountInfo = this.getDefaultAccountInfo(platform);
- }
- await page.close();
- await context.close();
- await browser.close();
- return accountInfo;
- } catch (error) {
- logger.error('HeadlessBrowser fetchAccountInfo error:', error);
- await browser.close();
- return this.getDefaultAccountInfo(platform);
- }
- }
- /**
- * 获取抖音账号信息 - 通过 API 方式获取
- * 1. 监听 check/user 接口验证登录状态
- * 2. 通过 work_list API 获取作品数和作品列表
- */
- private async fetchDouyinAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `douyin_${Date.now()}`;
- let accountName = '抖音账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- let worksList: WorkItem[] = [];
- let isLoggedIn = false;
- // 用于存储从 API 捕获的数据
- const capturedData: {
- userInfo?: {
- nickname?: string;
- avatar?: string;
- uid?: string;
- sec_uid?: string;
- unique_id?: string; // 抖音号(如 Ethanfly9392)
- short_id?: string; // 短ID
- follower_count?: number;
- };
- worksList?: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- duration: number;
- createTime: number;
- statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number };
- }>;
- total?: number;
- } = {};
- try {
- // 从 Cookie 获取用户 ID
- const uidCookie = cookies.find(c =>
- ['passport_uid', 'uid', 'ssid'].includes(c.name)
- );
- if (uidCookie?.value) {
- accountId = `douyin_${uidCookie.value}`;
- }
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听 check/user 接口 - 验证登录状态
- if (url.includes(DOUYIN_API.CHECK_USER)) {
- const data = await response.json();
- isLoggedIn = data?.result === true && data?.status_code === 0;
- logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
- }
- // 监听 work_list 接口 - 获取作品列表
- if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
- const data = await response.json();
- if (data?.aweme_list) {
- // 获取总数
- if (data.total !== undefined) {
- capturedData.total = data.total;
- }
- // 解析作品列表
- capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
- const statistics = aweme.statistics as Record<string, unknown> || {};
- const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
- const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';
- return {
- awemeId: String(aweme.aweme_id || ''),
- title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
- coverUrl,
- duration: Number(aweme.duration || 0),
- createTime: Number(aweme.create_time || 0),
- statistics: {
- play_count: Number(statistics.play_count || 0),
- digg_count: Number(statistics.digg_count || 0),
- comment_count: Number(statistics.comment_count || 0),
- share_count: Number(statistics.share_count || 0),
- },
- };
- });
- logger.info(`[Douyin API] work_list: total=${capturedData.total}, items=${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 apiWorks = await this.fetchWorksDirectApi(page);
- if (apiWorks.length > 0) {
- worksCount = apiWorks.length;
- worksList = apiWorks.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- duration: '00:00',
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: 0,
- likeCount: 0,
- commentCount: w.commentCount,
- shareCount: 0,
- }));
- logger.info(`[Douyin] Got ${worksCount} works from API`);
- } else if (capturedData.worksList && capturedData.worksList.length > 0) {
- // 如果直接 API 调用失败,使用监听到的数据
- worksCount = capturedData.total || capturedData.worksList.length;
- worksList = capturedData.worksList.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- duration: this.formatDuration(w.duration),
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: w.statistics.play_count,
- likeCount: w.statistics.digg_count,
- commentCount: w.statistics.comment_count,
- shareCount: w.statistics.share_count,
- }));
- logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
- }
- } catch (error) {
- logger.warn('Failed to fetch Douyin account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- }
- /**
- * 格式化视频时长
- */
- private formatDuration(ms: number): string {
- if (!ms) return '00:00';
- const seconds = Math.floor(ms / 1000);
- const minutes = Math.floor(seconds / 60);
- const remainingSeconds = seconds % 60;
- return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
- }
- /**
- * 获取B站账号信息
- */
- private async fetchBilibiliAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `bilibili_${Date.now()}`;
- let accountName = 'B站账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- try {
- const uidCookie = cookies.find(c => c.name === 'DedeUserID');
- if (uidCookie?.value) {
- accountId = `bilibili_${uidCookie.value}`;
- }
- await page.goto('https://member.bilibili.com/platform/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 获取用户名
- const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
- if (nameEl) {
- const text = await nameEl.textContent();
- if (text?.trim()) {
- accountName = text.trim();
- }
- }
- // 获取头像
- const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
- if (avatarEl) {
- const src = await avatarEl.getAttribute('src');
- if (src) {
- avatarUrl = src;
- }
- }
- } catch (error) {
- logger.warn('Failed to fetch Bilibili account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取快手账号信息
- */
- private async fetchKuaishouAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `kuaishou_${Date.now()}`;
- let accountName = '快手账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- try {
- const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
- if (uidCookie?.value) {
- accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
- }
- await page.goto('https://cp.kuaishou.com/profile', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 获取用户名
- const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
- if (nameEl) {
- const text = await nameEl.textContent();
- if (text?.trim()) {
- accountName = text.trim();
- }
- }
- // 获取头像
- const avatarEl = await page.$('[class*="avatar"] img');
- if (avatarEl) {
- const src = await avatarEl.getAttribute('src');
- if (src) {
- avatarUrl = src;
- }
- }
- } catch (error) {
- logger.warn('Failed to fetch Kuaishou account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取小红书账号信息 - 通过 API 方式获取
- */
- private async fetchXiaohongshuAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `xiaohongshu_${Date.now()}`;
- let accountName = '小红书账号';
- let avatarUrl = '';
- let fansCount = 0;
- let worksCount = 0;
- // 用于存储捕获的数据
- const capturedData: {
- userInfo?: {
- nickname?: string;
- avatar?: string;
- userId?: string;
- redId?: string;
- fans?: number;
- notes?: number;
- };
- } = {};
- try {
- // 从 Cookie 获取用户 ID
- const userIdCookie = cookies.find(c =>
- c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
- );
- if (userIdCookie?.value) {
- accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
- }
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听用户信息 API
- if (url.includes('/api/galaxy/creator/home/personal_info') ||
- url.includes('/api/sns/web/v1/user/selfinfo') ||
- url.includes('/user/selfinfo')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));
- // 解析用户信息
- const userInfo = data?.data?.user_info || data?.data || data;
- if (userInfo) {
- capturedData.userInfo = {
- nickname: userInfo.nickname || userInfo.name || userInfo.userName,
- avatar: userInfo.image || userInfo.avatar || userInfo.images,
- userId: userInfo.user_id || userInfo.userId,
- redId: userInfo.red_id || userInfo.redId,
- fans: userInfo.fans || userInfo.fansCount,
- notes: userInfo.notes || userInfo.noteCount,
- };
- logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
- }
- }
- // 监听创作者主页数据
- if (url.includes('/api/galaxy/creator/home/home_page') ||
- url.includes('/api/galaxy/creator/data')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));
- if (data?.data) {
- const homeData = data.data;
- // 获取粉丝数和笔记数
- if (homeData.fans_count !== undefined) {
- capturedData.userInfo = capturedData.userInfo || {};
- capturedData.userInfo.fans = homeData.fans_count;
- }
- if (homeData.note_count !== undefined) {
- capturedData.userInfo = capturedData.userInfo || {};
- capturedData.userInfo.notes = homeData.note_count;
- }
- }
- }
- } catch {
- // 忽略非 JSON 响应
- }
- });
- // 导航到小红书创作者中心
- logger.info('[Xiaohongshu] Navigating to creator center...');
- await page.goto('https://creator.xiaohongshu.com/creator/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Xiaohongshu] Cookie expired, needs login');
- return this.getDefaultAccountInfo('xiaohongshu');
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 如果 API 没有捕获到数据,尝试从页面提取
- if (!capturedData.userInfo?.nickname) {
- logger.info('[Xiaohongshu] API did not return data, extracting from page...');
- // 尝试获取用户名
- const nameSelectors = [
- '[class*="nickname"]',
- '[class*="user-name"]',
- '[class*="userName"]',
- '.user-info .name',
- '[class*="creator"] [class*="name"]',
- ];
- for (const selector of nameSelectors) {
- const el = await page.$(selector);
- if (el) {
- const text = await el.textContent();
- if (text?.trim() && text.trim().length < 50) {
- accountName = text.trim();
- logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
- break;
- }
- }
- }
- // 尝试获取头像
- const avatarSelectors = [
- '[class*="avatar"] img',
- '[class*="user-avatar"] img',
- '.user-info img',
- '[class*="creator"] img[src*="sns"]',
- ];
- for (const selector of avatarSelectors) {
- const el = await page.$(selector);
- if (el) {
- const src = await el.getAttribute('src');
- if (src && src.startsWith('http')) {
- avatarUrl = src;
- logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
- break;
- }
- }
- }
- // 尝试获取粉丝数
- const statsText = await page.textContent('body');
- const fansMatch = statsText?.match(/粉丝[::\s]*(\d+(?:\.\d+)?[万亿]?)/);
- if (fansMatch) {
- fansCount = this.parseChineseNumber(fansMatch[1]);
- logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
- }
- const notesMatch = statsText?.match(/笔记[::\s]*(\d+)/);
- if (notesMatch) {
- worksCount = parseInt(notesMatch[1], 10);
- logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
- }
- }
- // 使用捕获的数据
- if (capturedData.userInfo) {
- if (capturedData.userInfo.nickname) {
- accountName = capturedData.userInfo.nickname;
- }
- if (capturedData.userInfo.avatar) {
- avatarUrl = capturedData.userInfo.avatar;
- }
- if (capturedData.userInfo.userId) {
- accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
- } else if (capturedData.userInfo.redId) {
- accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
- }
- if (capturedData.userInfo.fans) {
- fansCount = capturedData.userInfo.fans;
- }
- if (capturedData.userInfo.notes) {
- worksCount = capturedData.userInfo.notes;
- }
- }
- logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
- // 获取作品列表 - 通过监听 API 接口
- const worksList: WorkItem[] = [];
- try {
- logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');
- // 存储所有捕获的笔记数据
- const allNotesData: Array<{
- noteId: string;
- title: string;
- coverUrl: string;
- status: number;
- publishTime: string;
- type: string;
- duration: number;
- likeCount: number;
- commentCount: number;
- collectCount: number;
- viewCount: number;
- shareCount: number;
- }> = [];
- let currentPage = 0;
- let hasMorePages = true;
- const maxPages = 20; // 最多获取20页,防止无限循环
- // 设置 API 响应监听器 - 在导航之前绑定
- let apiResponseReceived = false;
- let totalNotesCount = 0; // 从 tags 中获取的总作品数
- const notesApiHandler = async (response: import('playwright').Response) => {
- const url = response.url();
- try {
- // 监听小红书笔记列表 API
- // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
- if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
- url.includes('/api/sns/v5/creator/note/user/posted') ||
- url.includes('creator/note/user/posted')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);
- if ((data?.success || data?.code === 0) && data?.data) {
- apiResponseReceived = true;
- // 从 tags 中获取总作品数
- // tags 数组中 id="special.note_time_desc" 的项("所有笔记")包含总数
- if (data.data.tags && Array.isArray(data.data.tags)) {
- const allNotesTag = data.data.tags.find((tag: { id?: string; notes_count?: number }) =>
- tag.id === 'special.note_time_desc'
- );
- if (allNotesTag?.notes_count !== undefined) {
- totalNotesCount = allNotesTag.notes_count;
- logger.info(`[Xiaohongshu API] Total notes count from tags: ${totalNotesCount}`);
- }
- }
- const notes = data.data.notes || [];
- for (const note of notes) {
- // 根据 API 返回格式解析数据
- // images_list 是数组,第一个元素包含 url
- // 将 http:// 转换为 https:// 以确保图片能正常加载
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- logger.info(`[Xiaohongshu API] Note: id=${note.id}, title="${note.display_title}", cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
- allNotesData.push({
- noteId: note.id || '',
- title: note.display_title || '',
- coverUrl: coverUrl,
- status: note.tab_status || 1, // 1=已发布
- publishTime: note.time || '',
- type: note.type || 'normal', // video/normal
- duration: duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- // 检查是否还有更多页面
- // page=-1 表示没有更多数据
- if (data.data.page === -1 || notes.length === 0) {
- hasMorePages = false;
- logger.info(`[Xiaohongshu API] No more pages (page indicator: ${data.data.page})`);
- }
- } else {
- hasMorePages = false;
- }
- }
- } catch (e) {
- // 只在有相关 URL 时打印警告
- if (url.includes('creator/note')) {
- logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
- }
- }
- };
- // 先绑定监听器
- page.on('response', notesApiHandler);
- logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');
- // 导航到笔记管理页面
- await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
- waitUntil: 'networkidle', // 等待网络空闲,确保 API 已响应
- timeout: 30000,
- });
- // 等待初始页面加载和 API 响应
- await page.waitForTimeout(5000);
- logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);
- // 如果监听器没有捕获到数据,尝试直接调用 API
- if (allNotesData.length === 0) {
- logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');
- try {
- // 直接在页面上下文中调用 API
- const apiResponse = await page.evaluate(async () => {
- const response = await fetch('https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=0', {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return await response.json();
- });
- logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
- if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
- // 从 tags 中获取总作品数
- if (apiResponse.data.tags && Array.isArray(apiResponse.data.tags)) {
- const allNotesTag = apiResponse.data.tags.find((tag: { id?: string; notes_count?: number }) =>
- tag.id === 'special.note_time_desc'
- );
- if (allNotesTag?.notes_count !== undefined) {
- totalNotesCount = allNotesTag.notes_count;
- logger.info(`[Xiaohongshu API Direct] Total notes count from tags: ${totalNotesCount}`);
- }
- }
- const notes = apiResponse.data.notes || [];
- for (const note of notes) {
- // 将 http:// 转换为 https://
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- logger.info(`[Xiaohongshu API Direct] Note: id=${note.id}, cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);
- allNotesData.push({
- noteId: note.id || '',
- title: note.display_title || '',
- coverUrl: coverUrl,
- status: note.tab_status || 1,
- publishTime: note.time || '',
- type: note.type || 'normal',
- duration: duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- // 获取更多页面
- let pageNum = 1;
- let lastPage = apiResponse.data.page;
- while (lastPage !== -1 && pageNum < maxPages) {
- const nextResponse = await page.evaluate(async (p) => {
- const response = await fetch(`https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}`, {
- method: 'GET',
- credentials: 'include',
- });
- return await response.json();
- }, pageNum);
- if (nextResponse?.data?.notes?.length > 0) {
- for (const note of nextResponse.data.notes) {
- // 将 http:// 转换为 https://
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- allNotesData.push({
- noteId: note.id || '',
- title: note.display_title || '',
- coverUrl: coverUrl,
- status: note.tab_status || 1,
- publishTime: note.time || '',
- type: note.type || 'normal',
- duration: duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- pageNum++;
- lastPage = nextResponse.data.page;
- if (lastPage === -1) break;
- } else {
- break;
- }
- }
- }
- } catch (apiError) {
- logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
- }
- }
- // 如果还是没有数据,尝试滚动加载
- if (allNotesData.length === 0) {
- logger.info('[Xiaohongshu] Still no notes, trying scroll to trigger API...');
- await page.waitForTimeout(2000);
- }
- // 滚动加载更多页面(如果通过监听器获取的数据)
- while (hasMorePages && currentPage < maxPages && allNotesData.length > 0 && apiResponseReceived) {
- currentPage++;
- const previousCount = allNotesData.length;
- // 滚动到页面底部触发加载更多
- await page.evaluate(() => {
- window.scrollTo(0, document.body.scrollHeight);
- });
- // 等待新数据加载
- await page.waitForTimeout(2000);
- // 如果没有新数据,退出循环
- if (allNotesData.length === previousCount) {
- logger.info(`[Xiaohongshu] No new notes loaded after scroll, stopping at page ${currentPage}`);
- break;
- }
- logger.info(`[Xiaohongshu] Page ${currentPage}: total ${allNotesData.length} notes`);
- }
- // 移除监听器
- page.off('response', notesApiHandler);
- logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);
- // 转换为 WorkItem 格式
- for (const note of allNotesData) {
- // 转换时长为 mm:ss 格式
- const minutes = Math.floor(note.duration / 60);
- const seconds = note.duration % 60;
- const durationStr = note.duration > 0
- ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
- : '';
- // 转换状态
- let statusStr = 'published';
- if (note.status === 0) statusStr = 'draft';
- else if (note.status === 2) statusStr = 'reviewing';
- else if (note.status === 3) statusStr = 'rejected';
- worksList.push({
- videoId: note.noteId,
- title: note.title || '无标题',
- coverUrl: note.coverUrl,
- duration: durationStr,
- publishTime: note.publishTime,
- status: statusStr,
- playCount: note.viewCount,
- likeCount: note.likeCount,
- commentCount: note.commentCount,
- shareCount: note.shareCount,
- });
- }
- logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);
- // 更新作品数:优先使用从 API tags 获取的总数
- if (totalNotesCount > 0) {
- worksCount = totalNotesCount;
- logger.info(`[Xiaohongshu] Using total notes count from API: ${worksCount}`);
- } else if (worksList.length > 0) {
- worksCount = worksList.length;
- logger.info(`[Xiaohongshu] Using works list length: ${worksCount}`);
- }
- } catch (worksError) {
- logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
- }
- logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- } catch (error) {
- logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 解析中文数字(如 1.2万 -> 12000)
- */
- private parseChineseNumber(str: string): number {
- if (!str) return 0;
- let num = parseFloat(str);
- if (str.includes('万')) {
- num *= 10000;
- } else if (str.includes('亿')) {
- num *= 100000000;
- }
- return Math.floor(num);
- }
- /**
- * 获取平台配置
- */
- private getPlatformConfig(platform: PlatformType) {
- const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
- douyin: {
- homeUrl: 'https://creator.douyin.com/creator-micro/home',
- loginIndicators: ['login', 'passport', 'sso'],
- },
- bilibili: {
- homeUrl: 'https://member.bilibili.com/platform/home',
- loginIndicators: ['passport.bilibili.com', 'login'],
- },
- kuaishou: {
- homeUrl: 'https://cp.kuaishou.com/profile',
- loginIndicators: ['passport.kuaishou.com', 'login'],
- },
- xiaohongshu: {
- homeUrl: 'https://creator.xiaohongshu.com/',
- loginIndicators: ['login', 'passport'],
- },
- weixin: {
- homeUrl: 'https://channels.weixin.qq.com/platform',
- 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'] };
- }
- /**
- * 获取默认账号信息
- */
- private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
- return {
- accountId: `${platform}_${Date.now()}`,
- accountName: `${platform}账号`,
- avatarUrl: '',
- fansCount: 0,
- worksCount: 0,
- };
- }
- /**
- * 获取抖音评论 - 逐个选择作品获取评论
- */
- async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
- const browser = await chromium.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- const page = await context.newPage();
- // 导航到评论管理页面
- logger.info('Navigating to Douyin comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 点击"选择作品"按钮
- logger.info('Looking for "选择作品" button...');
- const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');
- if (selectWorkBtn) {
- await selectWorkBtn.click();
- await page.waitForTimeout(2000);
- logger.info('Clicked "选择作品" button');
- } else {
- // 如果没有选择作品按钮,可能已经有作品被选中,直接获取当前评论
- logger.info('No "选择作品" button found, fetching current comments...');
- const currentComments = await this.extractCommentsFromPage(page);
- if (currentComments.length > 0) {
- allWorkComments.push({
- videoId: 'current',
- videoTitle: '当前作品',
- videoCoverUrl: '',
- comments: currentComments,
- });
- }
- await page.close();
- await context.close();
- await browser.close();
- return allWorkComments;
- }
- // 获取作品列表
- const worksList = await page.evaluate(() => {
- const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];
- // 查找作品列表容器(弹窗中的作品选择列表)
- const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');
- workItems.forEach((item, index) => {
- const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
- const coverEl = item.querySelector('img, [class*="cover"]');
- const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
- let coverUrl = '';
- if (coverEl) {
- coverUrl = (coverEl as HTMLImageElement).src ||
- coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
- }
- // 获取 video ID(从数据属性或其他方式)
- const videoId = item.getAttribute('data-video-id') ||
- item.getAttribute('data-id') ||
- `video_${index}`;
- works.push({ videoId, title, coverUrl });
- });
- return works;
- });
- logger.info(`Found ${worksList.length} works in the selector`);
- // 如果有作品列表,逐个选择并获取评论
- if (worksList.length > 0) {
- for (let i = 0; i < worksList.length; i++) {
- try {
- logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);
- // 点击选择该作品
- const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
- if (workItem) {
- await workItem.click();
- await page.waitForTimeout(2000);
- // 点击确认按钮(如果有)
- const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
- if (confirmBtn) {
- await confirmBtn.click();
- await page.waitForTimeout(2000);
- }
- }
- // 等待评论加载
- await page.waitForTimeout(2000);
- // 提取评论
- const comments = await this.extractCommentsFromPage(page);
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: worksList[i].videoId,
- videoTitle: worksList[i].title,
- videoCoverUrl: worksList[i].coverUrl,
- comments,
- });
- logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
- }
- // 重新打开选择作品弹窗(如果需要继续选择其他作品)
- if (i < worksList.length - 1) {
- const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
- if (selectBtn) {
- await selectBtn.click();
- await page.waitForTimeout(2000);
- }
- }
- } catch (workError) {
- logger.warn(`Failed to process work ${i + 1}:`, workError);
- }
- }
- } else {
- // 没有找到作品列表,尝试直接从页面获取评论
- const comments = await this.extractCommentsFromPage(page);
- if (comments.length > 0) {
- // 获取当前显示的作品信息
- const currentWork = await page.evaluate(() => {
- const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
- const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');
- return {
- title: titleEl?.textContent?.trim() || '当前作品',
- coverUrl: (coverEl as HTMLImageElement)?.src || '',
- };
- });
- allWorkComments.push({
- videoId: 'current',
- videoTitle: currentWork.title,
- videoCoverUrl: currentWork.coverUrl,
- comments,
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('Error fetching Douyin comments:', error);
- await browser.close();
- return allWorkComments;
- }
- }
- /**
- * 从页面提取评论列表
- * 使用抖音创作者中心的精确选择器
- * 根据实际 HTML 结构:
- * - 评论容器: container-sXKyMs (或类似 container-xxx)
- * - 用户名: username-aLgaNB (或类似 username-xxx)
- * - 时间: time-NRtTXO (或类似 time-xxx)
- * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
- * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
- */
- private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
- return page.evaluate(() => {
- const comments: Array<{
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const seenContents = new Set<string>();
- // 方法1: 直接查找所有评论容器 (container-xxx 类名)
- // 评论容器通常包含 checkbox、avatar、content 等子元素
- const allContainers = document.querySelectorAll('[class*="container-"]');
- const commentContainers: Element[] = [];
- allContainers.forEach(container => {
- // 检查是否是评论容器:包含用户名和评论内容
- const hasUsername = container.querySelector('[class*="username-"]');
- const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
- if (hasUsername && hasCommentContent) {
- commentContainers.push(container);
- }
- });
- console.log(`Found ${commentContainers.length} comment containers`);
- // 如果方法1没找到,尝试方法2:通过评论内容元素向上查找
- if (commentContainers.length === 0) {
- const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
- console.log(`Found ${contentElements.length} content elements, searching parents...`);
- contentElements.forEach(contentEl => {
- let parent = contentEl.parentElement;
- // 向上查找最多 10 层
- for (let i = 0; i < 10 && parent; i++) {
- const className = parent.className || '';
- // 查找包含 container- 的父元素
- if (className.includes('container-')) {
- if (!commentContainers.includes(parent)) {
- commentContainers.push(parent);
- }
- break;
- }
- parent = parent.parentElement;
- }
- });
- }
- console.log(`Total comment containers: ${commentContainers.length}`);
- commentContainers.forEach((container, index) => {
- try {
- // 提取用户名 - 使用 username-xxx 选择器
- let authorName = '';
- const usernameEl = container.querySelector('[class*="username-"]');
- if (usernameEl && usernameEl.textContent) {
- authorName = usernameEl.textContent.trim();
- }
- if (!authorName) authorName = '未知用户';
- // 提取头像 - 从 avatar-xxx 容器内的 img 提取
- let authorAvatar = '';
- const avatarContainer = container.querySelector('[class*="avatar-"]');
- if (avatarContainer) {
- const avatarImg = avatarContainer.querySelector('img');
- if (avatarImg) {
- authorAvatar = avatarImg.src || '';
- }
- }
- // 提取时间 - 使用 time-xxx 选择器
- let commentTime = '';
- const timeEl = container.querySelector('[class*="time-"]');
- if (timeEl && timeEl.textContent) {
- commentTime = timeEl.textContent.trim();
- }
- // 提取评论内容 - 使用 comment-content-text-xxx 选择器
- let content = '';
- const contentEl = container.querySelector('[class*="comment-content-text-"]');
- if (contentEl && contentEl.textContent) {
- content = contentEl.textContent.trim();
- }
- // 跳过空内容
- if (!content || content.length < 1) {
- console.log(`[${index}] Skipping empty content`);
- return;
- }
- // 去重 (基于用户名+内容)
- const contentKey = `${authorName}||${content}`;
- if (seenContents.has(contentKey)) {
- console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
- return;
- }
- seenContents.add(contentKey);
- // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
- let likeCount = 0;
- const operationsEl = container.querySelector('[class*="operations-"]');
- if (operationsEl) {
- // 查找第一个 item-xxx,通常是点赞数
- const firstItem = operationsEl.querySelector('[class*="item-"]');
- if (firstItem) {
- const text = firstItem.textContent || '';
- const match = text.match(/(\d+)/);
- if (match) {
- likeCount = parseInt(match[1], 10);
- }
- }
- }
- // 生成唯一 ID
- const contentHash = content.slice(0, 30) + authorName + commentTime;
- const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;
- comments.push({
- commentId,
- authorId: authorName,
- authorName,
- authorAvatar,
- content,
- likeCount,
- commentTime,
- });
- console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
- } catch (err) {
- console.error(`[${index}] Error extracting comment:`, err);
- }
- });
- console.log(`Successfully extracted ${comments.length} comments`);
- return comments;
- });
- }
- /**
- * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
- * 使用无头浏览器,通过拦截网络请求直接获取 API 数据
- * 更稳定、更高效
- */
- async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
- const browser = await chromium.launch({
- headless: true, // 无头模式
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- // 存储捕获的 API 数据
- const capturedWorks: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- }> = [];
- const capturedComments: Map<string, CommentItem[]> = new Map();
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 监听网络响应
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听作品列表 API - 支持新旧两种接口
- // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
- // 旧接口: /creator/item/list (item_info_list 字段)
- if (url.includes('/work_list') || url.includes('/creator/item/list')) {
- const data = await response.json();
- // 新接口: aweme_list
- if (data?.aweme_list && data.aweme_list.length > 0) {
- for (const aweme of data.aweme_list) {
- const awemeId = String(aweme.aweme_id || '');
- if (!awemeId) continue;
- const statistics = aweme.statistics || {};
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- let title = aweme.item_title || '';
- if (!title) {
- const desc = aweme.desc || aweme.caption || '';
- title = desc.split('\n')[0].slice(0, 50) || '无标题';
- }
- let coverUrl = '';
- if (aweme.Cover?.url_list?.length > 0) {
- coverUrl = aweme.Cover.url_list[0];
- } else if (aweme.video?.cover?.url_list?.length > 0) {
- coverUrl = aweme.video.cover.url_list[0];
- }
- capturedWorks.push({
- awemeId,
- title,
- coverUrl,
- commentCount,
- });
- }
- logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
- }
- // 旧接口: item_info_list
- const itemList = data?.item_info_list || data?.item_list || [];
- if (itemList.length > 0) {
- for (const item of itemList) {
- capturedWorks.push({
- awemeId: item.item_id_plain || item.aweme_id || '',
- title: item.title || '无标题',
- coverUrl: item.cover_image_url || '',
- commentCount: item.comment_count || 0,
- });
- }
- logger.info(`[API] Captured ${itemList.length} works from item/list API`);
- }
- }
- // 监听评论列表 API(两种格式)
- // 格式1: /comment/list/select/ - 初始加载,返回 { comments: [...] }
- // 格式2: /creator/comment/list/ - 切换作品后,返回 { comment_info_list: [...] }
- if (url.includes('/comment/list') || url.includes('/comment/read')) {
- const data = await response.json();
- // 从 URL 中提取 aweme_id
- const awemeIdMatch = url.match(/aweme_id=(\d+)/);
- const awemeId = awemeIdMatch?.[1] || '';
- let comments: CommentItem[] = [];
- // 格式1: 初始加载的评论 API (comment/list/select)
- if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
- comments = data.comments.map((c: Record<string, unknown>) => {
- const user = c.user as Record<string, unknown> | undefined;
- const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
- const avatarUrls = avatarThumb?.url_list as string[] | undefined;
- return {
- commentId: String(c.cid || ''),
- authorId: String(user?.uid || ''),
- authorName: String(user?.nickname || '匿名'),
- authorAvatar: avatarUrls?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- };
- });
- logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
- }
- // 格式2: 切换作品后的评论 API (creator/comment/list)
- if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
- comments = data.comment_info_list.map((c: Record<string, unknown>) => {
- const userInfo = c.user_info as Record<string, unknown> | undefined;
- return {
- commentId: String(c.comment_id || ''),
- authorId: String(userInfo?.user_id || ''),
- authorName: String(userInfo?.screen_name || '匿名'),
- authorAvatar: String(userInfo?.avatar_url || ''),
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: awemeId, // 这种格式没有直接返回 aweme_id
- };
- });
- logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
- }
- if (comments.length > 0) {
- const videoId = comments[0]?.videoId || awemeId;
- if (videoId) {
- const existing = capturedComments.get(videoId) || [];
- capturedComments.set(videoId, [...existing, ...comments]);
- logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
- }
- }
- }
- } catch {
- // 忽略非 JSON 响应
- }
- });
- // 导航到创作者中心页面(设置好 Cookie 后)
- logger.info('[API Interception] Navigating to creator page...');
- await page.goto('https://creator.douyin.com/creator-micro/home', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[API Interception] Cookie expired');
- return [];
- }
- // 方式1:直接调用 API 获取作品列表(优先)
- logger.info('[API Interception] Fetching works via direct API...');
- let works = await this.fetchWorksDirectApi(page);
- // 方式2:如果直接调用失败,尝试通过页面触发 API
- if (works.length === 0) {
- logger.info('[API Interception] Direct API failed, trying page navigation...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'networkidle',
- timeout: 60000,
- });
- await page.waitForTimeout(3000);
- // 点击"选择作品"按钮触发作品列表 API
- const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
- if (selectBtn) {
- await selectBtn.click();
- await page.waitForTimeout(3000);
- }
- // 使用监听到的数据
- works = capturedWorks;
- }
- logger.info(`[API Interception] Total works: ${works.length}`);
- // 获取有评论的作品
- const worksWithComments = works.filter(w => w.commentCount > 0);
- logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);
- // 如果有评论的作品,需要导航到评论管理页面并逐个切换获取
- if (worksWithComments.length > 0) {
- // 先尝试直接调用 API 获取评论
- for (const work of worksWithComments) {
- logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);
- let comments = capturedComments.get(work.awemeId) || [];
- if (comments.length === 0) {
- comments = await this.fetchCommentsDirectApi(page, work.awemeId);
- }
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
- }
- }
- // 如果直接 API 没有获取到足够的评论,使用页面交互方式
- const worksNeedingPageMethod = worksWithComments.filter(w => {
- const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
- return !found || found.comments.length === 0;
- });
- if (worksNeedingPageMethod.length > 0) {
- logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);
- // works 是所有作品的列表(包括没有评论的),弹窗中的顺序应该和这个一致
- // worksWithComments 是有评论的作品列表
- logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
- logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);
- // 构建作品索引映射:在所有作品列表中,每个有评论的作品的索引是多少
- const workIndexMap = new Map<string, number>();
- works.forEach((w, idx) => {
- if (w.commentCount > 0) {
- workIndexMap.set(w.awemeId, idx);
- }
- });
- logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);
- // 导航到评论管理页面
- logger.info('[Page Method] Navigating to comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面加载
- await page.waitForTimeout(5000);
- // 用于存储最新捕获的评论和 aweme_id
- const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };
- // 设置监听器 - 捕获评论 API 响应
- page.on('response', async (response) => {
- const url = response.url();
- if (url.includes('/comment/list') || url.includes('/comment/read')) {
- try {
- const jsonData = await response.json();
- let parsedComments: CommentItem[] = [];
- let capturedAwemeId = '';
- // 从 URL 中提取 aweme_id(格式1有)
- const awemeIdMatch = url.match(/aweme_id=(\d+)/);
- capturedAwemeId = awemeIdMatch?.[1] || '';
- // 格式1: { comments: [...] }
- if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
- // 从评论中提取 aweme_id
- const firstComment = jsonData.comments[0] as Record<string, unknown>;
- if (!capturedAwemeId && firstComment.aweme_id) {
- capturedAwemeId = String(firstComment.aweme_id);
- }
- parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
- commentId: String((c as { cid?: string }).cid || ''),
- authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
- authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
- authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
- content: String((c as { text?: string }).text || ''),
- likeCount: Number((c as { digg_count?: number }).digg_count || 0),
- commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
- videoId: capturedAwemeId,
- }));
- logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
- }
- // 格式2: { comment_info_list: [...] }
- if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
- parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
- const userInfo = c.user_info as Record<string, unknown> | undefined;
- return {
- commentId: String(c.comment_id || ''),
- authorId: String(userInfo?.user_id || ''),
- authorName: String(userInfo?.screen_name || '匿名'),
- authorAvatar: String(userInfo?.avatar_url || ''),
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: '', // 格式2没有aweme_id,稍后填充
- };
- });
- logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
- }
- if (parsedComments.length > 0) {
- latestHolder.comments = parsedComments;
- latestHolder.awemeId = capturedAwemeId;
- }
- } catch {
- // 忽略
- }
- }
- });
- // 等待第一个作品的评论加载(格式1,有 aweme_id)
- await page.waitForTimeout(4000);
- // 处理第一个作品(页面加载时自动显示,格式1有aweme_id可以直接匹配)
- if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
- const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
- if (matchedWork) {
- allWorkComments.push({
- videoId: matchedWork.awemeId,
- videoTitle: matchedWork.title,
- videoCoverUrl: matchedWork.coverUrl,
- comments: latestHolder.comments,
- });
- logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
- }
- }
- // 遍历其他有评论的作品
- for (const work of worksWithComments) {
- // 检查是否已获取
- const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
- if (existing) {
- logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
- continue;
- }
- // 获取该作品在所有作品列表中的索引
- const workIndex = workIndexMap.get(work.awemeId);
- if (workIndex === undefined) {
- logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
- continue;
- }
- logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);
- try {
- // 清空之前的数据
- latestHolder.comments = [];
- latestHolder.awemeId = '';
- // 点击"选择作品"按钮
- await page.click('button:has-text("选择作品")');
- await page.waitForTimeout(2000);
- // 找到弹窗中的作品图片列表
- const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
- logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);
- if (workIndex < workImages.length) {
- // 点击对应索引的作品
- await workImages[workIndex].click();
- logger.info(`[Page Method] Clicked work image at index ${workIndex}`);
- // 等待评论 API 响应
- await page.waitForTimeout(4000);
- // 获取评论
- if (latestHolder.comments.length > 0) {
- // 使用当前 work 的 awemeId
- const comments = latestHolder.comments.map(c => ({
- ...c,
- videoId: work.awemeId,
- }));
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
- } else {
- // 尝试从页面提取
- const pageComments = await this.extractCommentsFromPage(page);
- if (pageComments.length > 0) {
- const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
- } else {
- logger.warn(`[Page Method] No comments for ${work.awemeId}`);
- }
- }
- } else {
- logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
- await page.keyboard.press('Escape');
- }
- await page.waitForTimeout(1000);
- } catch (e) {
- logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
- await page.keyboard.press('Escape').catch(() => { });
- await page.waitForTimeout(500);
- }
- }
- }
- }
- logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
- await context.close();
- } catch (error) {
- logger.error('[API Interception] Error:', error);
- } finally {
- await browser.close();
- }
- return allWorkComments;
- }
- /**
- * 直接调用评论 API 获取数据(支持分页获取所有评论)
- * 优先使用视频页面 API(获取全部评论),失败时才使用创作者 API
- */
- private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- // 优先尝试视频页面 API(获取全部评论)
- logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
- let comments = await this.fetchVideoPageCommentsApi(page, awemeId);
- if (comments.length > 0) {
- logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
- return comments;
- }
- // 如果视频页面 API 失败,尝试创作者评论 API(可能只返回部分评论)
- logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
- comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);
- return comments;
- }
- /**
- * 通过视频页面获取全部评论(主要方案)
- * 这个 API 能获取视频的所有评论,不仅仅是创作者回复过的
- */
- private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- const comments: CommentItem[] = [];
- const maxPages = 50;
- let cursor = 0;
- let hasMore = true;
- let pageCount = 0;
- try {
- // 导航到视频页面
- logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
- await page.goto(`https://www.douyin.com/video/${awemeId}`, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- const data = await page.evaluate(async ({ videoId, cursorValue }) => {
- try {
- const url = `https://www.douyin.com/aweme/v1/web/comment/list/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&item_type=0&insert_ids=&whale_cut_token=&cut_version=1&rcFT=&aid=6383&device_platform=web_pc&verifyFp=&fp=&msToken=`;
- const resp = await fetch(url, {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'Referer': `https://www.douyin.com/video/${videoId}`,
- },
- });
- if (!resp.ok) {
- return { error: `HTTP ${resp.status}`, comments: [] };
- }
- return resp.json();
- } catch (e) {
- return { error: String(e), comments: [] };
- }
- }, { videoId: awemeId, cursorValue: cursor });
- if (data?.error) {
- logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
- }
- if (data?.comments && Array.isArray(data.comments)) {
- for (const c of data.comments) {
- comments.push({
- commentId: String(c.cid || ''),
- authorId: String(c.user?.uid || c.user?.sec_uid || ''),
- authorName: String(c.user?.nickname || '匿名'),
- authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- });
- }
- logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
- }
- hasMore = data?.has_more === true || data?.has_more === 1;
- cursor = data?.cursor || cursor + 50;
- if (!data?.comments || data.comments.length === 0) {
- hasMore = false;
- }
- }
- logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
- } catch (e) {
- logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
- }
- return comments;
- }
- /**
- * 创作者评论管理 API(备用方案)
- * 获取的是需要回复的评论
- */
- private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- const comments: CommentItem[] = [];
- const maxPages = 50;
- let cursor = 0;
- let hasMore = true;
- let pageCount = 0;
- try {
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- const data = await page.evaluate(async ({ videoId, cursorValue }) => {
- const url = `https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&comment_select_options=0&sort_options=0&channel_id=618&app_id=2906&aid=2906&device_platform=webapp`;
- const resp = await fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return resp.json();
- }, { videoId: awemeId, cursorValue: cursor });
- if (data?.comments && Array.isArray(data.comments)) {
- for (const c of data.comments) {
- comments.push({
- commentId: String(c.cid || ''),
- authorId: String(c.user?.uid || ''),
- authorName: String(c.user?.nickname || '匿名'),
- authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- });
- }
- logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
- }
- hasMore = data?.has_more === true || data?.has_more === 1;
- cursor = data?.cursor || cursor + 50;
- if (!data?.comments || data.comments.length === 0) {
- hasMore = false;
- }
- }
- logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
- } catch (e) {
- logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
- }
- return comments;
- }
- /**
- * 直接调用抖音 API 获取作品列表
- * 使用新的 work_list 接口,支持分页加载
- */
- private async fetchWorksDirectApi(page: Page): Promise<Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- createTime?: number;
- }>> {
- const works: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- createTime?: number;
- }> = [];
- try {
- 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: 不传或传空表示获取全部状态的作品
- // count: 每页获取数量,增加到20减少请求次数
- const url = `https://creator.douyin.com/janus/douyin/creator/pc/work_list?scene=star_atlas&device_platform=android&count=20&max_cursor=${cursor}&cookie_enabled=true&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_online=true&timezone_name=Asia%2FShanghai&aid=1128`;
- const resp = await fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return resp.json();
- }, maxCursor);
- logger.info(`[DirectAPI] API response: has_more=${data?.has_more}, max_cursor=${data?.max_cursor}, aweme_list_length=${data?.aweme_list?.length || 0}`);
- // 解析 aweme_list 中的作品数据
- const awemeList = data?.aweme_list || [];
- logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);
- for (const aweme of awemeList) {
- const awemeId = String(aweme.aweme_id || '');
- if (!awemeId) continue;
- // 从 statistics 中获取评论数
- const statistics = aweme.statistics || {};
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- // 获取标题:优先使用 item_title,其次使用 desc(描述)
- let title = aweme.item_title || '';
- if (!title) {
- // 从 desc 中提取标题(取第一行或前50个字符)
- const desc = aweme.desc || aweme.caption || '';
- title = desc.split('\n')[0].slice(0, 50) || '无标题';
- }
- // 获取封面 URL:从 Cover.url_list 或 video.cover.url_list 中获取
- let coverUrl = '';
- if (aweme.Cover?.url_list?.length > 0) {
- coverUrl = aweme.Cover.url_list[0];
- } else if (aweme.video?.cover?.url_list?.length > 0) {
- coverUrl = aweme.video.cover.url_list[0];
- }
- works.push({
- awemeId,
- title,
- coverUrl,
- commentCount,
- createTime: aweme.create_time,
- });
- }
- // 检查是否有更多数据
- // 注意: 抖音 API 返回的 has_more 可能不准确,我们额外判断
- const apiHasMore = data?.has_more === true || data?.has_more === 1;
- // 更新游标:使用返回的 max_cursor
- if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
- // 只有当 max_cursor 有变化时才继续
- if (data.max_cursor !== maxCursor) {
- maxCursor = data.max_cursor;
- hasMore = apiHasMore && awemeList.length > 0;
- } else {
- // max_cursor 没变化,说明到底了
- hasMore = false;
- }
- } else if (awemeList.length > 0) {
- // 如果没有 max_cursor,使用最后一个作品的 create_time 作为游标
- const lastAweme = awemeList[awemeList.length - 1];
- if (lastAweme.create_time) {
- const newCursor = lastAweme.create_time;
- if (newCursor !== maxCursor) {
- maxCursor = newCursor;
- hasMore = apiHasMore;
- } else {
- hasMore = false;
- }
- } else {
- hasMore = false;
- }
- } else {
- // 没有获取到数据,停止循环
- hasMore = false;
- }
- logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);
- // 稍微延迟,避免请求过快
- if (hasMore) {
- await new Promise(resolve => setTimeout(resolve, 500));
- }
- }
- logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages`);
- } catch (e) {
- logger.warn('[DirectAPI] Failed to fetch works:', e);
- }
- return works;
- }
- /**
- * 获取抖音评论 (旧版 - DOM解析方式)
- * 模拟点击"选择作品"按钮,依次点击作品获取评论
- * 作为备用方案
- */
- async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 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;
- }
- }
- /**
- * 获取小红书评论
- */
- async fetchXiaohongshuCommentsViaApi(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 || '.xiaohongshu.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 用于捕获评论数据
- const capturedComments: Map<string, CommentItem[]> = new Map();
- const capturedNotes: Array<{
- noteId: string;
- title: string;
- coverUrl: string;
- }> = [];
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听笔记列表 API
- if (url.includes('/api/galaxy/creator/content/note_list') ||
- url.includes('/api/galaxy/creator/notes')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
- const notes = data?.data?.notes || data?.data?.list || [];
- for (const note of notes) {
- capturedNotes.push({
- noteId: note.note_id || note.id || '',
- title: note.title || note.desc || '',
- coverUrl: note.cover?.url || note.cover || '',
- });
- }
- }
- // 监听评论列表 API
- if (url.includes('/api/sns/web/v2/comment/page') ||
- url.includes('/api/galaxy/creator/comment') ||
- url.includes('/api/sns/v1/note/comment')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
- const comments: CommentItem[] = [];
- const commentList = data?.data?.comments || data?.comments || [];
- for (const comment of commentList) {
- comments.push({
- commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
- authorId: comment.user_info?.user_id || comment.user_id || '',
- authorName: comment.user_info?.nickname || comment.nickname || '',
- authorAvatar: comment.user_info?.image || comment.avatar || '',
- content: comment.content || '',
- likeCount: comment.like_count || 0,
- commentTime: comment.create_time || comment.time || '',
- parentCommentId: comment.target_comment_id || undefined,
- });
- // 处理子评论
- const subComments = comment.sub_comments || comment.replies || [];
- for (const sub of subComments) {
- comments.push({
- commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
- authorId: sub.user_info?.user_id || sub.user_id || '',
- authorName: sub.user_info?.nickname || sub.nickname || '',
- authorAvatar: sub.user_info?.image || sub.avatar || '',
- content: sub.content || '',
- likeCount: sub.like_count || 0,
- commentTime: sub.create_time || sub.time || '',
- parentCommentId: comment.id || comment.comment_id || undefined,
- });
- }
- }
- // 尝试从 URL 获取笔记 ID
- const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
- const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;
- if (comments.length > 0) {
- const existing = capturedComments.get(noteId) || [];
- capturedComments.set(noteId, [...existing, ...comments]);
- }
- }
- } catch { }
- });
- // 导航到评论管理页面
- logger.info('[Xiaohongshu Comments] Navigating to comment management...');
- await page.goto('https://creator.xiaohongshu.com/creator/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
- await browser.close();
- return allWorkComments;
- }
- // 尝试加载更多评论
- for (let i = 0; i < 5; i++) {
- await page.evaluate(() => {
- window.scrollBy(0, 500);
- });
- await page.waitForTimeout(1000);
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 将捕获的评论转换为 WorkComments 格式
- for (const [noteId, comments] of capturedComments) {
- const noteInfo = capturedNotes.find(n => n.noteId === noteId);
- allWorkComments.push({
- videoId: noteId,
- videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
- videoCoverUrl: noteInfo?.coverUrl || '',
- comments,
- });
- }
- // 如果没有从 API 获取到评论,尝试从页面提取
- if (allWorkComments.length === 0) {
- logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');
- const pageComments = await page.evaluate(() => {
- const result: Array<{
- commentId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
- commentItems.forEach((item, index) => {
- try {
- const authorEl = item.querySelector('[class*="author"], [class*="name"]');
- const avatarEl = item.querySelector('img');
- const contentEl = item.querySelector('[class*="content"]');
- const timeEl = item.querySelector('[class*="time"]');
- const likeEl = item.querySelector('[class*="like"] span');
- result.push({
- commentId: `xhs_page_${index}`,
- authorName: authorEl?.textContent?.trim() || '',
- authorAvatar: avatarEl?.src || '',
- content: contentEl?.textContent?.trim() || '',
- likeCount: parseInt(likeEl?.textContent || '0') || 0,
- commentTime: timeEl?.textContent?.trim() || '',
- });
- } catch { }
- });
- return result;
- });
- if (pageComments.length > 0) {
- allWorkComments.push({
- videoId: 'page_comments',
- videoTitle: '页面评论',
- videoCoverUrl: '',
- comments: pageComments.map(c => ({
- ...c,
- authorId: '',
- })),
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
- logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('[Xiaohongshu Comments] Error:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- }
- export const headlessBrowserService = new HeadlessBrowserService();
|