You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript将URL转换为HTML文档?

JavaScript获取指定URL的HTML文档实现方法

在JavaScript中,根据运行环境(浏览器/Node.js)的不同,实现获取指定URL HTML的方式有所区别,以下是具体方案:

一、浏览器端实现

浏览器环境下可以使用现代的fetch API(替代旧版的XMLHttpRequest)来发起请求,获取页面HTML:

async function getHtmlFromUrl(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    const html = await response.text();
    console.log(html);
    return html;
  } catch (error) {
    console.error('获取HTML出错:', error);
  }
}

// 调用示例(注意:需符合浏览器同源策略,或目标服务器允许CORS)
getHtmlFromUrl('https://www.example.com');

注意:浏览器存在同源策略限制,如果目标URL和当前页面域名、协议、端口不一致,需要目标服务器配置CORS(跨域资源共享)允许当前域的请求,否则会触发跨域错误。

二、Node.js端实现

Node.js环境下有两种常见方式:使用内置的http/https模块,或者使用原生fetch(Node.js 18及以上版本支持)。

方式1:使用内置https模块

const https = require('https');

function getHtmlFromUrl(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (response) => {
      let html = '';
      response.on('data', (chunk) => {
        html += chunk;
      });
      response.on('end', () => {
        resolve(html);
      });
    }).on('error', (error) => {
      reject(`请求出错:${error.message}`);
    });
  });
}

// 调用示例
getHtmlFromUrl('https://www.example.com')
  .then(html => console.log(html))
  .catch(err => console.error(err));

方式2:使用原生fetch(Node.js 18+)

async function getHtmlFromUrl(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    const html = await response.text();
    console.log(html);
    return html;
  } catch (error) {
    console.error('获取HTML出错:', error);
  }
}

// 调用示例
getHtmlFromUrl('https://www.example.com');

和Java IOUtils.toString的对应关系

Java中IOUtils.toString是将输入流转换为字符串,JavaScript中的实现逻辑类似:都是发起请求获取响应流,然后将流内容转换为字符串格式,本质都是读取并转换响应内容为文本。

内容的提问来源于stack exchange,提问作者Srushti Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:01:40