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

如何获取URL的HTML内容并根据内容或状态码执行对应操作

几种判断Steam社区个人主页是否存在的可行方案

首先得提一句,你原来的代码存在异步逻辑的问题——fetch是异步操作,不能直接用if包裹它来判断结果,得用async/await或者正确的Promise链式调用才能处理好。下面给你整理几种可靠的实现方案:

方案1:HTTP状态码判断(优化版)

这是你已经想到的思路,我们可以用async/await让代码更易读,同时直接检查响应状态:

async function checkSteamProfile(profileId) {
  const url = `https://steamcommunity.com/id/${profileId}`;
  try {
    const res = await fetch(url);
    // 404状态码表示页面不存在,即ID未被占用
    if (res.status === 404) {
      await message.channel.lastMessage.edit(`URL "${profileId}" is not taken.`);
    } else {
      // 页面存在时的逻辑可以在这里补充
      return;
    }
  } catch (err) {
    console.error('请求出错:', err);
  }
}

// 调用函数
checkSteamProfile(message.channel.lastMessage);

如果想进一步提升效率,还可以用HEAD请求——只获取响应头不下载整个HTML内容,能减少带宽消耗:

async function checkSteamProfile(profileId) {
  const url = `https://steamcommunity.com/id/${profileId}`;
  try {
    const res = await fetch(url, { method: 'HEAD' });
    if (res.status === 404) {
      await message.channel.lastMessage.edit(`URL "${profileId}" is not taken.`);
    }
  } catch (err) {
    console.error('请求出错:', err);
  }
}

方案2:Steam Web API查询(最可靠的官方方式)

直接调用Steam官方提供的API来查询 vanity URL 是否存在,这比解析HTML或判断状态码更准确,因为是官方接口,稳定性有保障。你需要先在Steam开发者平台申请一个API密钥,然后使用ISteamUser/ResolveVanityURL接口:

async function checkSteamVanityUrl(profileId, apiKey) {
  const url = `https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=${apiKey}&vanityurl=${profileId}`;
  try {
    const res = await fetch(url);
    const data = await res.json();
    // response.success为42表示vanity URL不存在,为1表示已被占用
    if (data.response.success === 42) {
      await message.channel.lastMessage.edit(`URL "${profileId}" is not taken.`);
    } else {
      // 存在时可以获取到对应的SteamID
      console.log('该ID已被占用,SteamID:', data.response.steamid);
    }
  } catch (err) {
    console.error('API请求出错:', err);
  }
}

// 调用时传入你的API密钥和要检查的ID
checkSteamVanityUrl(message.channel.lastMessage, '你的Steam API密钥');

这个方案的优势很明显:官方接口不会因为页面文本修改而失效,返回结果明确,能避免HTML解析或状态码判断可能出现的异常情况。

方案3:解析HTML内容判断(你的初始思路,修正版)

如果还是想用解析HTML的方式,需要修正异步逻辑,确保在拿到HTML内容后再进行判断:

async function checkSteamProfileHtml(profileId) {
  const url = `https://steamcommunity.com/id/${profileId}`;
  try {
    const res = await fetch(url);
    const body = await res.text();
    // 检查页面是否包含指定提示文本
    if (body.search('The specified profile could not be found.') !== -1) {
      await message.channel.lastMessage.edit(`URL "${profileId}" is not taken.`);
    }
  } catch (err) {
    console.error('请求出错:', err);
  }
}

checkSteamProfileHtml(message.channel.lastMessage);

不过这个方案有个潜在风险:如果Steam修改了页面的提示文本,你的判断逻辑就会失效,所以不如前两种方案可靠。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:32:35