javascript - 访问页面的 HTML
问题描述
是否可以通过该链接获取链接并访问其 HTML 代码?例如,我想从亚马逊获取一个链接并将其放入我自己的 HTML 代码中,使用 JavaScriptgetElementsByClassName
从该链接获取价格并将其显示回我的 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);
});
});
推荐阅读
- python - SparseCategoricalCrossentropy 形状不匹配
- php - 带有递归查询的 SQL - 尝试输出注释树
- python - NotFoundError:无法从 /content/training/ckpt-9 的检查点或 SavedModel 恢复:
- jquery - Uikit 切换器 - 防止在选定项目中切换
- tensorflow - 如何在 Tensorflow 的第一个纪元后保存进度
- html - 屏幕大时显示水平滚动条
- reactjs - redux useSelector:组件对状态更新没有反应
- ssl - Rabbitmq web_stomp ssl - 连接和断开连接(代码:1011,原因:“”)
- android - 将 gradle 更新到 7.0.3 后 buildConfigField 不起作用
- python - 为什么打开文件比加载模块慢?