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

如何用JavaScript通过URL获取单行文本网页内容?

获取指定URL单行文本的JavaScript实现方案

浏览器端实现

浏览器中网络请求是异步操作,因此getTextFromURL需要以异步函数形式实现,使用原生fetch API即可完成需求:

const STARTER = "https://cactus.nci.nih.gov/chemical/structure/";
let chemical = "ethanol";
let type = "formula";

async function getTextFromURL(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    // 直接提取网页返回的纯文本内容
    return await response.text();
  } catch (error) {
    console.error('获取文本出错:', error);
    return null;
  }
}

// 异步调用并输出结果
(async () => {
  const text = await getTextFromURL(STARTER + chemical + '/' + type);
  console.log(text); // 输出: C2H6O
})();

注意:如果目标网站未配置CORS响应头,浏览器会拦截跨域请求,此时可通过后端代理或开发环境专用插件临时绕过(仅用于测试)。

Node.js端实现

Node.js环境无跨域限制,可通过内置模块或第三方库实现:

方式1:使用内置https模块

const https = require('https');
const STARTER = "https://cactus.nci.nih.gov/chemical/structure/";
let chemical = "ethanol";
let type = "formula";

function getTextFromURL(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (response) => {
      let data = '';
      // 拼接响应数据块
      response.on('data', (chunk) => {
        data += chunk;
      });
      // 请求结束后返回处理后的文本
      response.on('end', () => {
        response.statusCode === 200 
          ? resolve(data.trim()) 
          : reject(new Error(`请求失败,状态码:${response.statusCode}`));
      });
    }).on('error', (error) => {
      reject(error);
    });
  });
}

// 异步调用并输出结果
(async () => {
  try {
    const text = await getTextFromURL(STARTER + chemical + '/' + type);
    console.log(text); // 输出: C2H6O
  } catch (error) {
    console.error('获取文本出错:', error);
  }
})();

方式2:使用axios库(需先执行npm install axios安装)

const axios = require('axios');
const STARTER = "https://cactus.nci.nih.gov/chemical/structure/";
let chemical = "ethanol";
let type = "formula";

async function getTextFromURL(url) {
  try {
    const response = await axios.get(url, { responseType: 'text' });
    return response.data.trim();
  } catch (error) {
    console.error('获取文本出错:', error);
    return null;
  }
}

// 异步调用并输出结果
(async () => {
  const text = await getTextFromURL(STARTER + chemical + '/' + type);
  console.log(text); // 输出: C2H6O
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:17:16