有167人阅读过
使用浏览器插件自动提取网页中的指定字段
发布于2023/12/01 更新于2023/12/01
[ 教程仅保证更新时有效,请自行测试。]
发布于2023/12/01 更新于2023/12/01
[ 教程仅保证更新时有效,请自行测试。]
[ 教程仅保证更新时有效,请自行测试。]
成品:
源代码
// 检查页面中是否存在具有 class 为 "cell" 的元素,并查看其文本内容是否包含 "评分",以确定是所需处理的页面
var cellElements = document.querySelectorAll('.cell');
var shouldExecute = Array.from(cellElements).some(function(cellElement) {
return cellElement.textContent.includes('评分');
});
// 如果存在包含 "评分" 的内容,则执行操作
if (shouldExecute) {
// 获取当前页面中所有 class 为 "qtext", "prompt", "r0", "r1", "rightanswer" 的元素
var elementsToRetrieve = document.querySelectorAll('.qtext, .prompt, .r0, .r1, .rightanswer');
// 创建新的页面窗口
var newWindow = window.open();
newWindow.document.write('<html><head><title>Content</title></head><body><ul></ul></body></html>');
// 在新页面中显示获取到的文本内容
var ulElement = newWindow.document.querySelector('ul');
// 遍历获取到的所有元素,并将非空、不包含 body 类的文本内容添加到新页面中
elementsToRetrieve.forEach(function(element, index) {
var text = element.textContent.trim(); // 获取元素内的文本内容,并去除两侧空格
if (text !== '' && !element.classList.contains('media-body')) {
var liElement = newWindow.document.createElement('div');
// 在 rightanswer 部分内容上方插入一行包含星号的文本
if (element.classList.contains('rightanswer')) {
var starLine = newWindow.document.createElement('div');
starLine.textContent = '**********'; // 星号行
ulElement.appendChild(starLine);
}
liElement.textContent = text;
ulElement.appendChild(liElement);
// 如果当前元素是 rightanswer 类型,并且不是最后一个元素,则在其下方添加分隔线
if (element.classList.contains('rightanswer') && index < elementsToRetrieve.length - 1) {
var separatorElement = newWindow.document.createElement('span');
separatorElement.textContent = '--------------------------------------------------'; // 指定字符分割
ulElement.appendChild(separatorElement);
}
}
});
}文章对你有帮助吗?
- 一般[0]

- 很赞[0]

- 没用[0]

- 垃圾[0]

- 无语[0]


