JavaScript 控制台脚本实战:3步实现 CSDN 文章纯净 PDF 导出(2024版)

在技术文档阅读和整理过程中,CSDN 作为国内知名的开发者社区,常常是我们获取技术资料的重要来源。然而,平台页面中的侧边栏、广告、推荐内容等冗余元素,往往会影响阅读体验和后续的资料归档。本文将介绍一种高效的方法,通过浏览器控制台脚本,快速提取 CSDN 文章核心内容,并导出为纯净的 PDF 文件。

1. 理解 CSDN 页面结构

CSDN 的文章页面通常包含以下几个主要部分:

  • 顶部导航栏 :包含登录状态、搜索框等
  • 文章标题区域 :标题、作者信息、发布时间等
  • 文章正文区域 :核心内容所在
  • 侧边栏 :相关推荐、广告等内容
  • 底部区域 :版权声明、相关文章推荐等

为了实现纯净 PDF 导出,我们需要精确识别并提取文章正文区域,同时移除其他干扰元素。以下是 CSDN 文章页面的典型 DOM 结构:

<div class="main-container">
  <div class="blog-content-box">
    <div class="article-header-box">
      <!-- 文章标题区域 -->
    </div>
    <div class="article-content">
      <!-- 文章正文内容 -->
    </div>
  </div>
  <div class="recommend-box">
    <!-- 推荐内容 -->
  </div>
</div>

2. 三步实现纯净 PDF 导出

2.1 第一步:识别并提取文章核心内容

首先,我们需要通过 JavaScript 选择器定位到文章的核心内容区域。根据 2024 年 CSDN 的最新页面结构,文章正文通常位于 div.article-content 元素中。

// 获取文章核心内容
const articleContent = document.querySelector('div.article-content');
if (!articleContent) {
  console.error('无法找到文章内容区域,请检查页面结构是否变化');
  return;
}

2.2 第二步:移除干扰元素

为了确保导出的 PDF 只包含文章核心内容,我们需要移除以下常见干扰元素:

  1. 顶部导航栏和标题区域
  2. 侧边栏和相关推荐
  3. 底部评论和推荐区域
  4. 浮动广告和工具栏

以下是完整的清理脚本:

// 移除顶部导航和标题区域
document.querySelectorAll('header, .nav-container, .blog-header-box').forEach(el => el.remove());

// 移除侧边栏
document.querySelectorAll('.csdn-side-toolbar, .blog-container-aside').forEach(el => el.remove());

// 移除底部区域
document.querySelectorAll('.comment-box, .recommend-box, .blog-footer-bottom').forEach(el => el.remove());

// 移除浮动元素
document.querySelectorAll('.toolbar-container, .meau-drop').forEach(el => el.remove());

// 移除广告
document.querySelectorAll('.ad-box, .p4p-tag').forEach(el => el.remove());

// 确保文章内容宽度填满页面
document.querySelector('main').style.width = '100%';

2.3 第三步:优化打印样式并触发打印

为了确保 PDF 导出效果最佳,我们需要调整页面样式,然后调用浏览器的打印功能:

// 添加打印优化样式
const style = document.createElement('style');
style.textContent = `
  @media print {
    body * {
      visibility: hidden;
    }
    .article-content, .article-content * {
      visibility: visible;
    }
    .article-content {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      padding: 0;
      margin: 0;
    }
    pre, code {
      white-space: pre-wrap !important;
    }
  }
`;
document.head.appendChild(style);

// 触发打印
setTimeout(() => {
  window.print();
}, 500);

3. 完整脚本与一键执行

将上述步骤整合为一个完整的脚本,可以通过浏览器控制台一键执行:

(function() {
  'use strict';
  
  // 1. 获取文章内容
  const article = document.querySelector('div.article-content');
  if (!article) {
    console.error('文章内容区域未找到,请检查选择器');
    return;
  }
  
  // 2. 清理页面
  const elementsToRemove = [
    'header', '.nav-container', '.blog-header-box',
    '.csdn-side-toolbar', '.blog-container-aside',
    '.comment-box', '.recommend-box', '.blog-footer-bottom',
    '.toolbar-container', '.meau-drop',
    '.ad-box', '.p4p-tag'
  ];
  
  elementsToRemove.forEach(selector => {
    document.querySelectorAll(selector).forEach(el => el.remove());
  });
  
  // 3. 调整布局
  document.querySelector('main').style.width = '100%';
  article.style.maxWidth = '100%';
  article.style.padding = '0';
  article.style.margin = '0';
  
  // 4. 添加打印样式
  const style = document.createElement('style');
  style.textContent = `
    @media print {
      body * { visibility: hidden; }
      .article-content, .article-content * { visibility: visible; }
      .article-content {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
      }
      pre, code { white-space: pre-wrap !important; }
    }
  `;
  document.head.appendChild(style);
  
  // 5. 触发打印
  setTimeout(() => {
    window.print();
  }, 1000);
})();

4. 高级技巧与问题排查

4.1 处理代码折叠区域

CSDN 文章中的长代码块常常会被折叠,我们需要确保这些内容在 PDF 中完全展开:

// 展开所有折叠的代码块
document.querySelectorAll('.hide-preCode-bt').forEach(btn => {
  btn.click();
});

// 确保代码块可见
document.querySelectorAll('pre').forEach(pre => {
  pre.style.maxHeight = 'none';
  pre.style.overflow = 'visible';
});

4.2 应对页面结构变化

如果脚本失效,可能是 CSDN 更新了页面结构。可以通过以下方法排查:

  1. 使用开发者工具检查元素
  2. 更新选择器以匹配新的 DOM 结构
  3. 测试脚本在不同文章页面的兼容性

4.3 优化 PDF 输出质量

为了获得更高质量的 PDF 输出,可以在打印对话框中进行以下设置:

设置项 推荐值 说明
布局 纵向 更适合技术文档阅读
纸张大小 A4 标准打印尺寸
边距 无 最大化利用页面空间
背景图形 勾选 确保代码高亮等样式保留

5. 脚本自动化与浏览器扩展

对于需要频繁导出 PDF 的用户,可以考虑将脚本封装为浏览器扩展,实现一键操作。以下是简单的扩展实现思路:

  1. manifest.json - 定义扩展基本信息
{
  "manifest_version": 3,
  "name": "CSDN PDF Exporter",
  "version": "1.0",
  "action": {
    "default_icon": "icon.png",
    "default_title": "Export CSDN Article to PDF"
  },
  "permissions": ["activeTab", "scripting"],
  "background": {
    "service_worker": "background.js"
  }
}
  1. background.js - 处理按钮点击事件
chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    files: ['content-script.js']
  });
});
  1. content-script.js - 包含核心清理和打印逻辑

这种扩展方式可以避免每次都需要手动复制粘贴脚本,大大提升工作效率。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐