有时候需要扒取知乎的问答内容让AI来帮忙写一篇综合性较强的文章,于是让AI帮我写了个油猴子脚本,可以一键提取标题和所有回答内容,然后下载到本地的txt文件,记录下这个油猴子脚本:
// ==UserScript==
// @name 知乎问答内容导出工具
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 提取知乎问答的问题及所有答案内容,并导出为TXT文件
// @author 您的名字
// @match https://www.zhihu.com/question/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 创建导出按钮
function createExportButton() {
const button = document.createElement('button');
button.textContent = '导出问答内容';
button.style.position = 'fixed';
button.style.top = '20px';
button.style.right = '20px';
button.style.zIndex = '9999';
button.style.padding = '10px 15px';
button.style.backgroundColor = '#0f88eb';
button.style.color = 'white';
button.style.border = 'none';
button.style.borderRadius = '4px';
button.style.cursor = 'pointer';
button.style.fontSize = '14px';
button.style.boxShadow = '0 2px 6px rgba(0,0,0,0.1)';
// 添加按钮点击事件
button.addEventListener('click', exportContent);
// 将按钮添加到页面
document.body.appendChild(button);
}
// 提取问题标题
function getQuestionTitle() {
const titleElement = document.querySelector('h1.QuestionHeader-title');
return titleElement ? titleElement.textContent.trim() : '未找到问题标题';
}
// 提取所有答案
function getAnswers() {
const answerElements = document.querySelectorAll('.ContentItem.AnswerItem');
const answers = [];
answerElements.forEach((element, index) => {
// 提取作者
const authorMeta = element.querySelector('.AuthorInfo meta[itemprop="name"]');
const author = authorMeta ? authorMeta.content : `匿名用户${index + 1}`;
// 提取回答内容
const contentElement = element.querySelector('.RichText.ztext.CopyrightRichText-richText');
let content = '';
if (contentElement) {
// 处理段落
const paragraphs = contentElement.querySelectorAll('p');
paragraphs.forEach(p => {
content += p.textContent.trim() + '\n\n';
});
// 去除多余空行
content = content.trim();
} else {
content = '未找到回答内容';
}
answers.push({
author,
content
});
});
return answers;
}
// 导出内容为TXT文件
function exportContent() {
// 获取问题和答案
const questionTitle = getQuestionTitle();
const answers = getAnswers();
// 构建文本内容
let textContent = `问题:${questionTitle}\n\n`;
textContent += `共${answers.length}个回答\n\n`;
answers.forEach((answer, index) => {
textContent += `--- 回答 ${index + 1} ---`;
textContent += `\n作者:${answer.author}\n\n`;
textContent += `内容:\n${answer.content}\n\n`;
textContent += `--- 回答结束 ---\n\n`;
});
// 创建下载链接
const blob = new Blob([textContent], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
// 生成文件名(使用问题标题的前20个字符)
const fileName = `${questionTitle.substring(0, 20).replace(/[\/:*?"<>|]/g, '')}_知乎问答.txt`;
a.download = fileName;
// 触发下载
document.body.appendChild(a);
a.click();
// 清理
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 0);
}
// 页面加载完成后添加按钮
window.addEventListener('load', function() {
// 等待页面完全加载
setTimeout(createExportButton, 2000);
});
})();
有需要的朋友也可以拿去使用!
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...