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

如何用JavaScript解析URL网页并获取ZenQuotes随机名言转为JSON?

如何用JavaScript获取ZenQuotes随机名言并解析网页

一、获取ZenQuotes随机名言并转为JSON

你找到的XMLHttpRequest代码可以优化,而且目标URL应该用随机名言专属接口https://zenquotes.io/api/random/,而非批量名言接口。具体处理步骤如下:

  1. 完善XMLHttpRequest请求逻辑
    必须判断请求的就绪状态和响应状态码,确保请求成功后再处理数据:

    const Http = new XMLHttpRequest();
    const url = 'https://zenquotes.io/api/random/';
    Http.open("GET", url);
    Http.send();
    
    Http.onreadystatechange = () => {
      // 就绪状态为4(请求完成)且状态码为200(请求成功)时处理数据
      if (Http.readyState === 4 && Http.status === 200) {
        // 将响应文本转换为JSON对象
        const quoteData = JSON.parse(Http.responseText);
        console.log(quoteData);
        // 提取名言文本和作者信息
        const quoteText = quoteData[0].q;
        const quoteAuthor = quoteData[0].a;
        console.log(`名言:${quoteText} —— ${quoteAuthor}`);
      }
    };
    
  2. 更简洁的方案:使用fetch API
    现代浏览器推荐用fetch,语法更直观,还能直接处理JSON转换:

    fetch('https://zenquotes.io/api/random/')
      .then(response => {
        if (!response.ok) {
          throw new Error('请求失败');
        }
        return response.json(); // 自动将响应转为JSON对象
      })
      .then(data => {
        console.log(data);
        console.log(`名言:${data[0].q} —— ${data[0].a}`);
      })
      .catch(error => console.error(error));
    

二、用JavaScript从URL解析网页

直接在前端解析外部网页要注意浏览器跨域限制:同源策略会阻止直接请求不同域名的网页,除非目标服务器开启了跨域资源共享(CORS)。如果目标网页没开CORS,前端直接请求会报错。

可行处理方式:

  • 通过服务器代理:搭建一个后端服务,由后端请求目标网页,再把内容返回给前端,绕过浏览器的跨域限制。
  • 解析已获取的HTML文本:如果已经通过代理或其他方式拿到网页的HTML文本,可以用DOMParser解析:
    // 假设htmlText是已获取到的网页HTML内容
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlText, 'text/html');
    
    // 获取页面标题
    const pageTitle = doc.querySelector('title').textContent;
    console.log(pageTitle);
    
    // 获取所有段落文本
    const paragraphs = doc.querySelectorAll('p');
    paragraphs.forEach(p => console.log(p.textContent));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:25:19