如果主域名相同,这确实不算跨域。在这种情况下,我们可以访问和操作 `iframe` 的内容。下面是一个如何从 `iframe` 中提取表格数据的示例:
- // ==UserScript==
- // @name 导出网页信息到文件
- // @namespace http://tampermonkey.net/
- // @version 0.1
- // @description 导出当前网页中的部分信息到CSV文件
- // @author wp231957
- // @match *://*/*
- // @grant none
- // ==/UserScript==
- (function() {
- 'use strict';
- // 创建导出按钮
- const button = document.createElement('button');
- button.textContent = '导出表格数据';
- button.style.position = 'fixed';
- button.style.top = '10px';
- button.style.right = '10px';
- button.style.zIndex = 1000; // 确保按钮在其它元素之上
- document.body.appendChild(button);
- button.addEventListener('click', () => {
- // 获取 iframe 元素
- const iframe = document.getElementById('iframe0');
- if (!iframe) {
- alert('无法找到 iframe!');
- return;
- }
- // 尝试访问 iframe 内容
- const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
- if (!iframeDoc) {
- alert('无法访问 iframe 的内容!');
- return;
- }
- const rows = Array.from(iframeDoc.querySelectorAll('table tbody tr'));
- alert('提取到的行数: ' + rows.length);
- // 找到你需要的表格和列,比如提取第1, 2, 3列(索引从0开始)
- const data = rows.map(row => {
- const cells = row.querySelectorAll('td');
- return [cells[0] ? cells[0].textContent : '', cells[1] ? cells[1].textContent : '', cells[2] ? cells[2].textContent : '']; // 提取第1, 2和第3列
- });
- // 将数据转换为CSV格式
- const csvContent = "data:text/csv;charset=utf-8," + data.map(e => e.join(",")).join("\n");
- // 创建下载链接
- const encodedUri = encodeURI(csvContent);
- const link = document.createElement("a");
- link.setAttribute("href", encodedUri);
- link.setAttribute("download", "table_data.csv");
- document.body.appendChild(link);
- // 点击下载链接
- link.click();
- // 清除下载链接
- document.body.removeChild(link);
- });
- })();
复制代码
这段代码大致包含以下几个步骤:
1. **创建导出按钮**:创建按钮并添加到页面。
2. **按钮点击事件处理**:在点击按钮时进入事件处理器。
3. **获取 iframe 内容**:获取 `iframe` 元素,并尝试访问其内容。
4. **提取表格数据**:从 `iframe` 中提取目标表格的行和列数据。
5. **转换数据格式并下载**:将提取的数据转换成 CSV 格式,并自动下载。
在 `iframeDoc.querySelectorAll('table tbody tr')` 中,你可以根据实际情况调整选择器来准确定位需要提取的表格。希望这个脚本能够满足你的需求!如果有任何问题,欢迎继续交流!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。