知识库 · AI 智能体
6、爬取指定公众号文章
使用极致了数据平台API结合n8n工作流,爬取指定微信公众号历史文章并自动同步至Notion数据库。包含biz参数配置、API Key设置、Notion集成授权及定时触发等完整操作步骤。
6、爬取指定公众号文章
2025年9月28日修改
这里比较有难度,需要自学能力较强
完整工作流:
Notion的配置需要科学上网,最好再下载notion软件到电脑上,更加方便后续使用
微信公众号里面沉淀了很多大量高质量的内容,但是很多时候没办法比较准确的爬取对应的内容,我们可以去尝试找一些第三方服务平台,给我们提供爬取公众号指定账号文章的能力。
上面提供了公众号平台的一系列API,https://www.dajiala.com/main/interface?actnav=0&selectCategory
我们主要使用下图的这个API爬取指定账号的历史文章,
可以看到请求一次6分8分左右,获取5篇文章,100篇文章也才只是一块多,还是挺便宜了。
这个工作流要从0-1运行起来还是比较麻烦的,我会在群里发这个工作流,大家需要的话后续我再复制完整的工作流即可。
这个文档主要是给大家分享具体怎么让这个工作流成功跑起来。
把上面得到的biz数据复制到N8N工作流 指定公众号节点中
上面的biz 要和下面的name一一对应,不然最后到notion表格中数据就对不上了
APIkey在极致了数据网页登录后右上角获取。
要让指定公众号往前查几页,这里填写对应的页数,一页五篇。
notion权限设置
配置Notion权限
通过下图方式很方便地把notion与n8n进行连接,链接地址:https://www.notion.com/my-integrations
记得在这个给予对应的权限,才能正常访问
在对应的表格要增加该账号集成
接着在N8N配置好API KEY,然后能够从下拉框拉取这些数据的
Notion数据库表头要这样设置,才能和我们工作流里面的内容一一对应。
执行完工作流后,notion中会有类似下面的内容
如果需要每天定时触发,触发器改成schedule 定时触发器,设置好时间即可
完整工作流详细代码参考
代码块
{
"name": "公众号文章同步工作流 一键爬取指定页数所有内容",
"nodes": [
{
"parameters": {},
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [
-1440,
304
],
"id": "6191ecf2-735c-4536-b020-ff19b1733b39",
"name": "When clicking ‘Execute workflow’"
},
{
"parameters": {
"options": {}
},
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [
-560,
304
],
"id": "50869163-5471-497e-968e-facd24c99e8b",
"name": "Loop Over Items"
},
{
"parameters": {
"method": "POST",
"url": "https://www.dajiala.com/fbmain/monitor/v3/post_history",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"biz\": \"{{ $json.key }}\",\n \"url\": \"\",\n \"name\": \"{{ $json.value }}\",\n \"page\": 2,\n \"key\": \"{{ $('指定公众号').item.json.key }}\",\n \"verifycode\": \"\"\n}",
"options": {
"redirect": {
"redirect": {}
}
}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-288,
320
],
"id": "a88a64c9-0cab-40b0-8caf-e15d83126282",
"name": "HTTP Request"
},
{
"parameters": {
"url": "={{ $json.url }}",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Accept",
"value": "*/*"
},
{
"name": "Accept-Encoding",
"value": "deflate, gzip"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
},
{
"name": "Host",
"value": "mp.weixin.qq.com"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
896,
192
],
"id": "907d72a7-3270-448a-9495-3597d98d0424",
"name": "HTTP Request1"
},
{
"parameters": {
"operation": "extractHtmlContent",
"extractionValues": {
"values": [
{
"key": "data",
"cssSelector": "#page-content"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.html",
"typeVersion": 1.2,
"position": [
1120,
192
],
"id": "41e5d615-ae9e-4404-bf13-69cf8ad22fdb",
"name": "HTML"
},
{
"parameters": {},
"type": "n8n-nodes-base.limit",
"typeVersion": 1,
"position": [
-784,
304
],
"id": "baf5e037-97df-42e2-affd-4c3acaf7a302",
"name": "Limit"
},
{
"parameters": {
"fieldToSplitOut": "data",
"options": {}
},
"type": "n8n-nodes-base.splitOut",
"typeVersion": 1,
"position": [
688,
288
],
"id": "ebb182ec-74b8-4630-a9a1-6e1fd8e06cab",
"name": "Split Out1"
},
{
"parameters": {
"jsCode": "/**\n * 将Markdown文本转换为纯文本\n * @param {string} markdown - 输入的Markdown格式文本\n * @returns {string} - 转换后的纯文本字符串\n */\nfunction markdownToText(markdown) {\n if (!markdown) return '';\n\n let text = markdown;\n\n // 移除代码块\n text = text.replace(/```[\\s\\S]*?```/g, '');\n text = text.replace(/`([^`]+)`/g, '$1');\n\n // 移除标题符号\n text = text.replace(/^#{1,6}\\s+/gm, '');\n\n // 移除粗体和斜体\n text = text.replace(/[*_]{2}([^*_]+)[*_]{2}/g, '$1'); // 粗体\n text = text.replace(/[*_]([^*_]+)[*_]/g, '$1'); // 斜体\n\n // 处理链接\n text = text.replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1'); // [文本](链接)\n text = text.replace(/\\[([^\\]]+)\\]\\[[^\\]]*\\]/g, '$1'); // [文本][引用]\n\n // 移除图片标记\n text = text.replace(/!\\[([^\\]]*?)\\]\\([^)]+\\)/g, '$1');\n \n // 处理各种非标准格式的图片标记\n text = text.replace(/!图片\\s*\\)/g, '');\n text = text.replace(/!图片\\s*$/g, '');\n text = text.replace(/!图片[\\s\\S]*?\\)/g, '');\n text = text.replace(/^\\s*\\)\\s*$/gm, '');\n text = text.replace(/^\\s*$/gm, '');\n\n // 处理列表\n text = text.replace(/^[\\s]*[\\-*+]\\s+/gm, ''); // 无序列表\n text = text.replace(/^[\\s]*\\d+\\.\\s+/gm, ''); // 有序列表\n\n // 处理引用\n text = text.replace(/^\\s*>\\s+/gm, '');\n\n // 处理水平分割线\n text = text.replace(/^\\s*[-*_]{3,}\\s*$/gm, '\\n');\n\n // 移除SVG相关标签及其内容\n text = text.replace(/<svg[^>]*>(([\\s\\S]*?)<\\/svg>)?/gi, '');\n \n // 增强SVG标签清理\n const svgElements = 'svg|rect|circle|path|line|polygon|polyline|g|defs|use|symbol|ellipse|text|image|clipPath|mask|pattern|filter|marker|linearGradient|radialGradient|stop|tspan|textPath|animate|animateMotion|animateTransform|set|foreignObject|switch|desc|title|metadata';\n text = text.replace(new RegExp(`<(${svgElements})(\\\\s[^>]*)?\\\\/?>`,'gi'), '');\n text = text.replace(new RegExp(`<\\\\/(${svgElements})>`,'gi'), '');\n \n // 移除单独的SVG标签片段\n text = text.replace(/[\\s']+(?:rect|circle|path|g|svg|defs|use|symbol)\\s*\\/?/gi, ' ');\n text = text.replace(/[\\s']+\\/(?:rect|circle|path|g|svg|defs|use|symbol)\\s*/gi, ' ');\n \n // 移除括号内的SVG标签片段\n text = text.replace(/\\([^\\)]*?(?:rect|circle|path|g|svg)[^\\)]*?\\)/gi, '');\n \n // 清理SVG属性和标签片段\n text = text.replace(/['\"\\s]+(fill|x|y|width|height|rx|ry|cx|cy|r|d|points|viewBox|xmlns)=['\"]?[^'\">\\s]*['\"]?/gi, ' ');\n text = text.replace(/\\s+(?:\\/)?(?:rect|circle|path|g|svg|defs|use|symbol|ellipse|text)(?:\\s+|\\/)/gi, ' ');\n text = text.replace(/\\s+\\/(?:rect|circle|path|g|svg|defs|use|symbol|ellipse|text)(?:\\s+|$)/gi, ' ');\n \n // 移除SVG和HTML常见属性\n const commonAttributes = 'xmlns|version|viewBox|width|height|class|style|id|fill|stroke|d|points|transform|x|y|cx|cy|r|x1|y1|x2|y2|dx|dy|offset|gradientUnits|spreadMethod|patternUnits|patternTransform|markerWidth|markerHeight|refX|refY|orient|font-size|font-family|text-anchor|alignment-baseline|href|xlink:href|preserveAspectRatio';\n text = text.replace(new RegExp(`\\\\s+(${commonAttributes})=[\\\"\\']([^\\\"\\']*)[\\\"\\'](?:\\\\s+|$)`,'gi'), ' ');\n \n // 移除data URI和编码内容\n text = text.replace(/data:(?:[^;]+;)*(?:base64,)?[a-zA-Z0-9+/]+={0,2}/g, '');\n text = text.replace(/%[0-9a-fA-F]{2}/g, ' ');\n \n // 最终清理:移除任何剩余的SVG相关内容\n text = text.replace(/\\([^\\)]*(?:svg|rect|g|path|circle)[^\\)]*\\)/gi, '');\n text = text.replace(/'[^']*(?:svg|rect|g|path|circle)[^']*'/gi, '');\n text = text.replace(/\"[^\"]*(?:svg|rect|g|path|circle)[^\"]*\"/gi, '');\n text = text.replace(/(?:\\/)?(?:svg|rect|g|path|circle|defs|use|symbol)(?:\\/)?/gi, '');\n \n // 移除其他HTML标签\n text = text.replace(/<[^>]+>/g, '');\n\n // 处理转义字符\n text = text.replace(/\\\\([\\\\`*_{}\\[\\]()#+\\-.!])/g, '$1');\n\n // 清理多余的空行\n text = text.replace(/\\n\\s*\\n/g, '\\n\\n');\n text = text.replace(/^\\s+|\\s+$/g, '');\n\n return text;\n}\n\n/**\n * 将文本按指定长度分段\n * @param {string} text - 输入文本\n * @param {number} segmentLength - 每段文本的最大长度\n * @returns {string[]} - 分段后的文本数组\n */\nfunction splitTextIntoSegments(text, segmentLength = 1800) {\n const segments = [];\n let remainingText = text;\n\n while (remainingText.length > 0) {\n if (remainingText.length <= segmentLength) {\n segments.push(remainingText);\n break;\n }\n\n let endIndex = segmentLength;\n // 尝试在句子或段落边界处分段\n const nextParagraph = remainingText.indexOf('\\n\\n', endIndex - 100);\n const nextSentence = remainingText.indexOf('. ', endIndex - 100);\n\n if (nextParagraph !== -1 && nextParagraph < endIndex + 100) {\n endIndex = nextParagraph;\n } else if (nextSentence !== -1 && nextSentence < endIndex + 100) {\n endIndex = nextSentence + 1;\n }\n\n segments.push(remainingText.substring(0, endIndex).trim());\n remainingText = remainingText.substring(endIndex).trim();\n }\n\n return segments;\n}\n\n// 获取所有输入数据项\nconst inputItems = $input.all();\nconst results = [];\n\n// 遍历处理每个输入数据项\nfor (let i = 0; i < inputItems.length; i++) {\n const currentItem = inputItems[i];\n const markdownInput = currentItem.json.data;\n \n if (!markdownInput) {\n // 如果没有数据,跳过这个项目\n continue;\n }\n \n const plainText = markdownToText(markdownInput);\n const textSegments = splitTextIntoSegments(plainText);\n\n // 将文本段落转换为规范的block对象格式\n const blocks = textSegments.map(segment => ({\n object: 'block',\n type: 'paragraph',\n paragraph: {\n rich_text: [\n {\n type: 'text',\n annotations: {\n bold: false,\n strikethrough: false,\n underline: false,\n italic: false,\n code: false,\n color: 'default'\n },\n text: {\n content: segment\n }\n }\n ]\n }\n }));\n\n // 只返回blocks字段\n results.push({\n json: {\n blocks: blocks\n }\n });\n}\n\nreturn results;\n"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
1344,
192
],
"id": "5b0e3f27-8802-4387-88d3-e7c1bca41d54",
"name": "将Markdown文本转换为纯文本"
},
{
"parameters": {
"method": "PATCH",
"url": "=https://api.notion.com/v1/blocks/{{ $json.id }}/children",
"authentication": "predefinedCredentialType",
"nodeCredentialType": "notionApi",
"sendBody": true,
"bodyParameters": {
"parameters": [
{
"name": "children",
"value": "={{ $json.blocks }}"
}
]
},
"options": {
"batching": {
"batch": {
"batchSize": 1,
"batchInterval": 5000
}
}
}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
1776,
480
],
"id": "ed58af3c-0e6e-49c2-9933-5d3ff8388335",
"name": "HTTP Request2",
"credentials": {
"notionApi": {
"id": "qlqMpY4lIuX0Wu2u",
"name": "Notion account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"mode": "combine",
"combineBy": "combineByPosition",
"options": {}
},
"type": "n8n-nodes-base.merge",
"typeVersion": 3.2,
"position": [
1568,
288
],
"id": "7bf8d804-b5ad-4887-ad68-ec35bb5e7bb8",
"name": "Merge"
},
{
"parameters": {
"jsCode": "const array1 = $input.first().json.biz;\nconst array2 = $input.first().json.name;\nconst combined = [];\n\nfor (let i = 0; i < array1.length; i++) {\n combined.push({\n key: array1[i],\n value: array2[i]\n });\n}\n\nreturn combined.map(item => ({ json: item }));\n"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-1008,
304
],
"id": "33152439-4e7b-4d98-8108-1891eb31b35a",
"name": "Code"
},
{
"parameters": {
"content": "## 文章同步完成后动作\n- 发送飞书通知\n- 执行内容加工工作流,如:日报工作流、小红书发布工作流等",
"height": 360,
"color": 6
},
"type": "n8n-nodes-base.stickyNote",
"position": [
2304,
-304
],
"typeVersion": 1,
"id": "c61cd82d-74ad-4ad2-b38a-341c7069cbcb",
"name": "Sticky Note"
},
{
"parameters": {
"resource": "databasePage",
"databaseId": {
"__rl": true,
"value": "23dd7566-179e-809d-b59b-d75f7ec78a62",
"mode": "list",
"cachedResultName": "AI资讯",
"cachedResultUrl": "https://www.notion.so/23dd7566179e809db59bd75f7ec78a62"
},
"title": "={{ $json.title }}",
"propertiesUi": {
"propertyValues": [
{
"key": "标题|title",
"title": "={{ $json.title }}"
},
{
"key": "url|rich_text",
"textContent": "={{ $json.url }} "
},
{
"key": "发布时间|rich_text",
"textContent": "={{ $json.post_time_str }}"
},
{
"key": "公众号名称|rich_text",
"textContent": "={{ $('Loop Over Items').item.json.value }}"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.notion",
"typeVersion": 2.2,
"position": [
1344,
400
],
"id": "4623d5c4-5bc3-4e76-a005-dd9b6f38622c",
"name": "Create a database page",
"retryOnFail": true,
"credentials": {
"notionApi": {
"id": "qlqMpY4lIuX0Wu2u",
"name": "Notion account"
}
}
},
{
"parameters": {
"assignments": {
"assignments": [
{
"id": "1aead2d8-db32-4837-a7bc-4f654b159db4",
"name": "biz",
"value": "=[\"MzIyMzA5NjEyMA==\", \"Mzg3MTk3NzYzNw==\",\"MzIzNjc1NzUzMw==\",\"MzI3MTA0MTk1MA==\",\"MzA3MzI4MjgzMw==\"]",
"type": "array"
},
{
"id": "3152a413-b0db-4206-a571-c80df9a90b2b",
"name": "name",
"value": "[\"数字生命卡兹克\",\"卡尔的AI沃茨\",\"量子位\",\"新智元\",\"机器之心\"]",
"type": "array"
},
{
"id": "742495c8-fb2c-4664-8fb0-91dea7d4ce94",
"name": "key",
"value": "",
"type": "string"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.set",
"typeVersion": 3.4,
"position": [
-1216,
304
],
"id": "e3b75fa5-9631-468d-b866-72a50885ec95",
"name": "指定公众号"
},
{
"parameters": {
"options": {
"reset": false
}
},
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [
208,
416
],
"id": "dcf96165-b72f-4694-94bb-4083b8e94db7",
"name": "Loop Over Items1",
"retryOnFail": true
},
{
"parameters": {
"method": "POST",
"url": "https://www.dajiala.com/fbmain/monitor/v3/post_history",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"biz\": \"{{ $('Loop Over Items').item.json.key }}\",\n \"url\": \"\",\n \"name\": \"{{ $('Loop Over Items').item.json.value }}\",\n \"page\": {{ $('Loop Over Items1').item.json.page }},\n \"key\": \"{{ $('指定公众号').item.json.key }}\",\n \"verifycode\": \"\"\n}",
"options": {
"redirect": {
"redirect": {}
}
}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
448,
432
],
"id": "76d66882-79de-4f78-a8ee-f9db6b1c87bc",
"name": "HTTP Request3"
},
{
"parameters": {
"jsCode": "//let count = $json.now_page - 1;\n\n//return {json: {count}};\n\nconst totalPages = Number($input.first().json.now_page ?? 1);\n\n// <=1 页就不循环\nif (!totalPages || totalPages <= 1) {\n return [];\n}\n\n// 例:now_page=9,则生成 8,7,6,...,1\nconst items = [];\nfor (let p = totalPages - 1; p >= 1; p--) {\n items.push({ json: { page: p } });\n}\nreturn items;\n\n\n\n"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-32,
416
],
"id": "b2476255-1d07-4c87-93f3-d5c54e4683b3",
"name": "Code1"
},
{
"parameters": {
"content": "## HTTP Request\n里面的页面填的是多少,就爬取这些页面中的所有文章"
},
"type": "n8n-nodes-base.stickyNote",
"typeVersion": 1,
"position": [
64,
1072
],
"id": "9c8005e5-95bd-4ad3-ae4a-c38281341f64",
"name": "Sticky Note1"
}
],
"pinData": {},
"connections": {
"When clicking ‘Execute workflow’": {
"main": [
[
{
"node": "指定公众号",
"type": "main",
"index": 0
}
]
]
},
"Loop Over Items": {
"main": [
[],
[
{
"node": "HTTP Request",
"type": "main",
"index": 0
}
]
]
},
"HTTP Request": {
"main": [
[
{
"node": "Code1",
"type": "main",
"index": 0
},
{
"node": "Split Out1",
"type": "main",
"index": 0
}
]
]
},
"HTTP Request1": {
"main": [
[
{
"node": "HTML",
"type": "main",
"index": 0
}
]
]
},
"HTML": {
"main": [
[
{
"node": "将Markdown文本转换为纯文本",
"type": "main",
"index": 0
}
]
]
},
"Limit": {
"main": [
[
{
"node": "Loop Over Items",
"type": "main",
"index": 0
}
]
]
},
"Split Out1": {
"main": [
[
{
"node": "HTTP Request1",
"type": "main",
"index": 0
},
{
"node": "Create a database page",
"type": "main",
"index": 0
}
]
]
},
"将Markdown文本转换为纯文本": {
"main": [
[
{
"node": "Merge",
"type": "main",
"index": 0
}
]
]
},
"Merge": {
"main": [
[
{
"node": "HTTP Request2",
"type": "main",
"index": 0
}
]
]
},
"Code": {
"main": [
[
{
"node": "Limit",
"type": "main",
"index": 0
}
]
]
},
"HTTP Request2": {
"main": [
[
{
"node": "Loop Over Items",
"type": "main",
"index": 0
}
]
]
},
"Create a database page": {
"main": [
[
{
"node": "Merge",
"type": "main",
"index": 1
}
]
]
},
"指定公众号": {
"main": [
[
{
"node": "Code",
"type": "main",
"index": 0
}
]
]
},
"Loop Over Items1": {
"main": [
[],
[
{
"node": "HTTP Request3",
"type": "main",
"index": 0
}
]
]
},
"HTTP Request3": {
"main": [
[
{
"node": "Split Out1",
"type": "main",
"index": 0
},
{
"node": "Loop Over Items1",
"type": "main",
"index": 0
}
]
]
},
"Code1": {
"main": [
[
{
"node": "Loop Over Items1",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "3e820704-2968-4c83-9ece-8463451ac612",
"meta": {
"templateCredsSetupCompleted": true,
"instanceId": "be33e7a4c93bf3fbad46ee9dd2261c1867b920251d4e05c1a2fedf55455fa8e4"
},
"id": "7iVDfDONgYZzxK6V",
"tags": []
}