1. 浏览器环境 (前端 JavaScript):使用 fetch API 或 XMLHttpRequest
  2. Node.js 环境 (后端 JavaScript):使用内置的 https/http 模块或第三方库如 axiosnode-fetch

下面我将为你详细介绍这两种方式,并提供完整的实例代码。

js远程获取网页源代码实例
(图片来源网络,侵删)

浏览器环境 (前端 JavaScript)

在前端,由于浏览器的同源策略,直接通过 JavaScript 请求另一个不同域名的网页源代码会受到限制,除非目标服务器明确支持 CORS (Cross-Origin Resource Sharing)

方法 1: 使用 fetch API (现代推荐)

fetch 是现代浏览器中用于网络请求的强大 API,基于 Promise,语法更简洁。

核心代码:

// 要获取的目标网页 URL
const targetUrl = 'https://jsonplaceholder.typicode.com/posts/1'; // 使用一个支持 CORS 的公共 API 作为示例
fetch(targetUrl)
  .then(response => {
    // 检查响应是否成功
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    // 将响应体解析为文本格式
    return response.text();
  })
  .then(htmlSource => {
    // 在这里获取到源代码
    console.log('获取到的源代码:', htmlSource);
    // 你可以将源代码显示在页面上
    document.getElementById('source-code').textContent = htmlSource;
  })
  .catch(error => {
    // 捕获并处理请求过程中可能发生的错误
    console.error('获取源代码时出错:', error);
  });

完整实例 (HTML + JS):

js远程获取网页源代码实例
(图片来源网络,侵删)

创建一个 index.html 文件,将以下代码粘贴进去,然后用浏览器打开即可看到效果。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">JS 获取远程网页源代码</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    textarea { width: 100%; height: 400px; margin-top: 20px; font-family: monospace; }
    button { padding: 10px 15px; font-size: 16px; cursor: pointer; }
  </style>
</head>
<body>
  <h1>JS 获取远程网页源代码</h1>
  <p>点击下方按钮,获取一个示例网页的源代码。</p>
  <button id="fetch-btn">获取源代码</button>
  <h2>获取到的源代码:</h2>
  <textarea id="source-code" readonly placeholder="源代码将显示在这里..."></textarea>
  <script>
    document.getElementById('fetch-btn').addEventListener('click', () => {
      // 重要提示:请确保目标 URL 支持 CORS
      // 对于大多数普通网站,直接请求它们的 HTML 会因为 CORS 策略而失败
      // 这里使用一个支持 CORS 的公共 API 作为演示
      const targetUrl = 'https://jsonplaceholder.typicode.com/posts/1';
      const sourceCodeElement = document.getElementById('source-code');
      const fetchBtn = document.getElementById('fetch-btn');
      fetchBtn.disabled = true;
      sourceCodeElement.value = '正在获取...';
      fetch(targetUrl)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
          }
          return response.text();
        })
        .then(htmlSource => {
          console.log('获取成功!');
          sourceCodeElement.value = htmlSource;
        })
        .catch(error => {
          console.error('获取失败:', error);
          sourceCodeElement.value = `获取失败: ${error.message}\n\n请检查目标 URL 是否支持 CORS (跨域资源共享),`;
        })
        .finally(() => {
          fetchBtn.disabled = false;
        });
    });
  </script>
</body>
</html>

重要提示:CORS 限制 如果你尝试将上面的 targetUrl 换成一个普通的网站,'https://www.baidu.com',请求很可能会失败,并在控制台看到类似这样的错误: Access to fetch at 'https://www.baidu.com' from origin 'null' has been blocked by CORS policy.

这是因为百度服务器没有为你的前端页面提供跨域访问的许可,要解决这个问题,通常需要后端服务来代理请求。


Node.js 环境 (后端 JavaScript)

在 Node.js 环境中,没有浏览器的同源策略限制,可以自由地向任何网站发起请求,这是爬虫或数据抓取任务最常用的环境。

方法 1: 使用内置的 https 模块

Node.js 自带了 httpshttp 模块,可以根据 URL 的协议自动选择使用哪个。

核心代码:

const https = require('https');
const targetUrl = 'https://www.javascript.com';
https.get(targetUrl, (res) => {
  let data = '';
  // 当接收到数据块时,将其追加到 data 变量中
  res.on('data', (chunk) => {
    data += chunk;
  });
  // 当所有数据接收完毕
  res.on('end', () => {
    console.log('获取到的源代码:', data);
    // 在这里可以对 data (源代码) 进行处理
  });
}).on('error', (err) => {
  console.error('请求出错:', err);
});

如何运行:

  1. 确保你已经安装了 Node.js
  2. 将上面的代码保存为一个文件,fetch.js
  3. 在终端中运行命令:node fetch.js

方法 2: 使用第三方库 axios (更简洁)

axios 是一个非常流行的、基于 Promise 的 HTTP 客户端,语法更接近 fetch,使用起来更方便。

首先安装 axios: 在终端中运行:

npm install axios

使用 axios 获取源代码:

const axios = require('axios');
const targetUrl = 'https://www.javascript.com';
axios.get(targetUrl)
  .then(response => {
    // response.data 包含了网页的源代码
    console.log('获取到的源代码:', response.data);
  })
  .catch(error => {
    if (error.response) {
      // 请求已发出,但服务器返回的状态码不在 2xx 范围内
      console.error('服务器响应错误:', error.response.status);
    } else if (error.request) {
      // 请求已发出,但没有收到响应
      console.error('无响应:', error.request);
    } else {
      // 在设置请求时发生了错误
      console.error('请求配置错误:', error.message);
    }
  });

总结与对比

特性 浏览器 (fetch) Node.js (https) Node.js (axios)
运行环境 前端浏览器 后端服务器 后端服务器
CORS 限制 ,只能请求支持 CORS 的服务器
易用性 高,基于 Promise,语法简洁 较低,使用事件监听器 高,基于 Promise,API 友好
依赖 无需安装 (现代浏览器内置) Node.js 内置,无需额外安装 需要通过 npm 安装
推荐场景 获取自己或允许跨域访问的 API 数据 简单脚本,不想安装额外依赖 复杂应用、爬虫、项目开发

实际应用场景建议

  • 如果你只是想在网页上显示另一个 API 的数据:使用浏览器端的 fetch API,并确保 API 支持 CORS。
  • 如果你想做一个爬虫,抓取任意网站的公开数据:使用 Node.js 环境,axios 是首选,因为它代码更清晰,功能也更强大(如自动处理 gzip 压缩、设置请求头等)。
  • 如果你在做一个后端服务,需要代理前端的请求以绕过 CORS:使用 Node.js 的 httpsaxios 在后端获取目标数据,然后再返回给你的前端应用。