首页 > 解决方案 > 访问页面的 HTML

问题描述

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

标签: javascripthtmlgetelementbyidgetelementsbyclassname

解决方案


有可能的。您可以向 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);
  });
});

推荐阅读