微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

访问页面的 HTML

如何解决访问页面的 HTML

是否可以获取链接并通过该链接访问其 HTML 代码?例如,我想从亚马逊获取一个链接并将其放入我自己的 HTML 代码中,使用 JavaScript getElementsByClassName 从该链接获取价格并将其显示回我的 HTML 代码中。

解决方法

这是可能的。您可以向 Amazon 页面发出 GET 请求,该请求将从那里为您提供响应中的 html,现在您需要对其进行格式化,上次我使用节点模块 jsdom 来执行此操作。>

更详细:

HTTP 是我们用来从服务器请求数据的协议,我写了一个解释性的节点 js 脚本:

const https = require('https');
const JSD = require('jsdom');
const { JSDOM } = JSD;
const zlib = require('zlib');

// The http get request
https.get('https://www.amazon.com',(response) => {
  html = '';

  // we need this because amazon is tricky and encodes the response so it is smaller hence it is faster to send
  let gunzip = zlib.createGunzip();
  response.pipe(gunzip);

  // we need this to get the full html page since it is too big to send in one amazon divides it to chunks
  gunzip.on('data',(chunk) => {
    html += chunk.toString();
  });

  // when the transmittion finished we can do wathever we want with it
  gunzip.on('end',() => {
    let amazon = new JSDOM(html);
    console.log(amazon.window.document.querySelector('html').innerHTML);
  });
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。