✅工作流实战:舆情分析助手——微博内容提取
我们拿到前5页网页爬取后的结果之后,就需要把里面的微博内容解析出来,前面说过了,直接用他的json内置的prompt方式解析会出现丢数据的情况,于是我想到的是自己写代码解析,于是:


新建一个微博内容提取的code节点,其中的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| function parseWeiboTime(raw) { raw = raw.trim(); let year = NOW.getFullYear(); const candidate = new Date(year, month, day, h, m, 0); const dt = new Date(year, month, day, h, m, 0); const pad = n => n.to String().padStart(2, '0'); return `${ dt.getFullYear() }-${ pad(dt.getMonth() + 1) }-${ pad(dt.getDate()) } ${ pad(dt.getHours()) }:${ pad(dt.getMinutes()) }:00`; } for (const item of $input.all()) { for (const block of blocks) { const userPattern = /\[!\[.*?\]\((https?:\/\/[^\s\)]+)\)\]\((https?:\/\/[^\s\)]+)\)\s*\n\s*\[([^\]]+)\]\((https?:\/\/[^\s\)]+)\)(?:\s*\n\s*\[!\[.*?\]\(.*?\)\])?\s*\n\s*\[([^\]]+)\]\((https?:\/\/[^\s\)]+)\)/; const userMatch = block.match(userPattern); if (!userMatch) continue; const username = userMatch[3]; const userLink = userMatch[4]; const rawPostTime = userMatch[5]; const postTimeLink = userMatch[6]; let rawContent = block.slice(userMatch.index + userMatch[0].length).trim(); const cutOffIndex = rawContent.search(/\n-\s*(\[\]\(https?:\/\/.*?\.(?:jpg|png|g if)\)|\d+|转发|评论|赞)/i); if (cutOffIndex !== -1) { rawContent = rawContent.slice(0, cutOffIndex).trim(); } let content = rawContent .replace(/\[展开 _c_\]\([^)]*\)/g, '') .replace(/收起 _d_/g, '') .replace(/\s+/g, ' ') .trim(); content = content.replace(/^来自\s*\[[^\]]+\]\([^)]*\)\s*/, '').trim(); const imageUrls = [...new Set([...inlineImages, ...listImages])]; const hashtags = [...new Set( content.match(/#([^#\s]+)#?/g)?.map(tag => tag.replace(/^#|#$| $/g, '')) || [] )]; const weiboId = extractWeiboId(postTimeLink); posts.push({ weiboId, username, userLink, postTime, } return posts;
|
值得注意的是关于时间的处理,一方面是微博显示的时间有很多种,比如xx秒前,XX分钟前,今天xx:xx、xx月xx日 xx:xx等等,而且时区默认还不太对,所以我们大多数代码都在处理这个时间的问题。
关于时区,N8N默认是美国时区,我们可以在启动的时候指定时区:
TZ=Asia/Shanghai GENERIC_TIMEZONE=Asia/Shanghai npx n8n
经过这个节点处理字后,就是几个时间处理和判断的节点,主要是做了些限制:只爬取24小时内的数据。这个不展开说了,大家到时候把我的配置导入n8n查看下就行了。
