当前位置: 首页 > ds >正文

开发浏览器插件-保存页面元素数据为json或csv

主要功能是获取页面列表元素数据并保存为JSON或CSV格式。
插件包含manifest.json配置文件、后台脚本background.js、内容脚本content.js、弹出窗口popup.html及其相关JS/CSS文件。
核心功能通过changePageColor函数实现,该函数提取页面中特定class的元素数据,支持JSON和CSV两种导出格式。

文件夹目录结构

插件配置文件 manifest.json

{"manifest_version": 3,"name": "我的第一个扩展","version": "1.0","description": "一个简单的浏览器扩展示例","action": {"default_popup": "popup.html","default_icon": {"16": "icon16.png"}},"permissions": ["activeTab","scripting"],"background": {"service_worker": "background.js"},"icons": {"16": "icon16.png"},"content_scripts": [{"matches": ["<all_urls>"],"js": ["content.js"]}]
}

background.js

// 后台脚本,持续运行的扩展进程
console.log("后台脚本已加载");// 示例:监听浏览器事件
chrome.runtime.onInstalled.addListener(() => {console.log("扩展已安装或更新");
});// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {console.log("收到消息:", message);sendResponse({ reply: "消息已收到" });
});

content.js

console.log("内容脚本已加载到当前页面");// 示例:在所有页面上添加一个小标记
const marker = document.createElement('div');
marker.textContent = '我的扩展已加载WF';
marker.style.position = 'fixed';
marker.style.bottom = '10px';
marker.style.right = '10px';
marker.style.backgroundColor = 'yellow';
marker.style.padding = '5px';
marker.style.zIndex = '9999';
document.body.appendChild(marker);

popup.html

<!DOCTYPE html>
<html><meta charset="utf-8"></meta>
<head><style>body {width: 300px;padding: 10px;font-family: Arial, sans-serif;}button {padding: 8px 12px;background: #4CAF50;color: white;border: none;border-radius: 4px;cursor: pointer;}</style>
</head>
<body><h2>我的扩展</h2><p>这是一个简单的浏览器扩展</p><button id="changeColor">改变页面颜色</button><!-- 浏览器插件-新版本(采集数据demo) --><script src="popup.js"></script>
</body>
</html>

popup.js

document.getElementById('changeColor').addEventListener('click', async () => {try {console.log("按钮点击事件触发");const tabsAll = await chrome.tabs.query({});const tabs = await chrome.tabs.query({ active: true, currentWindow: true });if (!tabs || tabs.length === 0) {throw new Error("没有找到活动标签页");}const tab = tabs[0];if (!tab.id) {throw new Error("标签页ID无效");}console.log("准备执行脚本,标签页ID:", tab.id);await chrome.scripting.executeScript({target: { tabId: tab.id },func: changePageColor,args: [tabsAll, tab]});console.log("脚本执行成功");} catch (error) {console.error("执行脚本失败:", error);// 可选:在弹出窗口中显示错误信息const errorElement = document.createElement('div');errorElement.style.color = 'red';errorElement.textContent = `错误: ${error.message}`;document.body.appendChild(errorElement);}
});function changePageColor(tabs, tab) {console.log(tabs);console.log(tab);try {const randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);console.log("正在改变背景颜色为:", randomColor);document.body.style.backgroundColor = randomColor;// 获取 ul class="datu" 的所有 li 元素const datuList = document.querySelectorAll('.datu li');console.log(datuList)// 循环获取 div class="datu-mingzi" 为药品名称 div class="datu-compamy" 为厂家const datuInfo = [];for (let i = 0; i < datuList.length; i++) {const datu = datuList[i];const mingzi = datu.querySelector('.datu-mingzi');datuInfo.push({mingzi: mingzi.innerText});}console.log(datuInfo);// 将数据保存为 JSON 文件// const blob = new Blob([JSON.stringify(datuInfo, null, 2)], { type: 'application/json' });// const link = document.createElement('a');// link.href = URL.createObjectURL(blob);// link.download = 'datuInfo.json';// link.click();// 转换 JSON 数据为 CSVfunction convertToCSV(jsonData) {const keys = Object.keys(jsonData[0]);  // 获取对象的键名(表头)const header = keys.join(',');          // 生成表头const rows = jsonData.map(row => keys.map(key => row[key]).join(','));  // 生成每行数据return [header, ...rows].join('\n');  // 返回最终的 CSV 字符串}const csvData = convertToCSV(datuInfo);// 创建 CSV 文件并下载const blob = new Blob([csvData], { type: 'text/csv' });const link = document.createElement('a');link.href = URL.createObjectURL(blob);link.download = 'datuInfo.csv';link.click();chrome.runtime.sendMessage({ action: 'someAction', data: 'myData' }, (response) => {console.log('收到背景页的响应:', response.reply);});} catch (error) {console.error("内容脚本执行出错:", error);}
}

styles.css

body{font-family: Arial;width:250px;padding:10px;background:#f8f9fa;
}button{background:#007bff;border: none;color: white;padding:10px;width:100%;cursor: pointer;border-radius:5px;
}

http://www.xdnf.cn/news/16118.html

相关文章:

  • 2.9学习DOM和BOM (主要是获取元素的操作)
  • 苍穹外卖DAY10
  • 如何用 LUKS 和 cryptsetup 为 Linux 配置加密
  • Flink框架:keyBy实现按键逻辑分区
  • Linux物理地址空间入门:从硬件到内核内存的基石
  • 网络设备功能对照表
  • Pytorch张量
  • 云原生技术与应用-Kubernetes Pod调度基础
  • jdk25浅谈
  • 深度学习-常用环境配置
  • 使用 Tailwind CSS 控制元素在移动端不显示
  • MySQL 核心知识点梳理(2)
  • C++ 分配内存释放内存
  • 深度学习 ---神经网络以及数据准备
  • 清理磁盘空间
  • LiteCoT:难度感知的推理链压缩与高效蒸馏框架
  • NISP-PTE基础实操——代码审计
  • 从实践出发--探究C/C++空类的大小,真的是1吗?
  • 微店关键词搜索接口深度开发指南
  • 有关Maven的个人笔记总结
  • ssh2-sftp-client 简化 sftp 文件传输的 node库
  • python实现接收九数云的异常分析指标推送通知
  • C++基础数据结构
  • Java IO 流详解:从基础到实战,彻底掌握输入输出编程
  • A316-HF-DAC-V1:专业USB HiFi音频解码器评估板技术解析
  • 牛客网题解 | 单词识别
  • 关于Ajax的学习笔记
  • 二叉树实现堆,咕咕咕
  • 结构型模式-架构解耦与扩展实践
  • Linux的目录