|  | 
 
 发表于 2024-7-18 09:59:45
|
显示全部楼层 
| 
 这就有趣了!你发现了网页中的内容嵌套在`iframe`中。在这种情况下,我们需要先访问`iframe`的内容,然后再从`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) {
            const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
            
            // 找到你需要的表格和列,比如提取第1,2,3列(索引从0开始)
            const rows = Array.from(iframeDocument.querySelectorAll('table tbody tr'));
            
            // 调试用弹窗,检查提取到的行
            alert('提取到的行数: ' + rows.length);
            const data = rows.map(row => {
                const cells = row.querySelectorAll('td');
                return cells ? [cells[0].textContent, cells[1].textContent, 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);
        } else {
            alert('未找到 iframe 内容');
        }
    });
})();
 这个脚本做了以下几件事:
 
 1. 创建一个按钮并添加到页面中。
 2. 当点击按钮时,获取`iframe`的内容。
 3. 从`iframe`中找到指定的表格数据。
 4. 将表格数据转换为CSV格式并生成下载链接。
 
 请确保你的`iframe`的id是正确的。如果你的`iframe`在JavaScript加载后是动态创建的,你可能还需要等到`iframe`加载完成后再执行这些操作。
 
 以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
 | 
 |