html - 抓取:由于结构变化,网页抓取停止
问题描述
在抓取网页时,网页的结构不断变化,我的意思是它的动态导致我的爬虫停止工作的情况。是否有机制在运行完整爬虫之前识别网页结构变化,从而识别结构是否发生变化。
解决方案
您当然可以使用“快照”来比较同一页面的 2 个版本。我已经实现了类似于 java String hashCode 的东西来实现这一点。
javascript中的代码:
/*
returns a dom element snapshot as innerText hash code
starting point is java String hashCode: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
keep everything fast: only work with a 32 bit hash, remove exponentiation
custom implementation: s[0]*31 + s[1]*31 + ... + s[n-1]*31
*/
function getSnapshot() {
const snapshotSelector = 'body';
const nodeToBeHashed = document.querySelector(snapshotSelector);
if (!nodeToBeHashed) return 0;
const { innerText } = nodeToBeHashed;
let hash = 0;
if (innerText.length === 0) {
return hash;
}
for (let i = 0; i < innerText.length; i += 1) {
// an integer between 0 and 65535 representing the UTF-16 code unit
const charCode = innerText.charCodeAt(i);
// multiply by 31 and add current charCode
hash = ((hash << 5) - hash) + charCode;
// convert to 32 bits as bitwise operators treat their operands as a sequence of 32 bits
hash |= 0;
}
return hash;
}
如果您无法在页面中运行 javascript 代码,您可以使用整个 html 响应作为内容以您喜欢的语言进行哈希处理。
推荐阅读
- r - 基于 sys.call 在符号 `T` 上使用 `isTRUE()`
- javascript - 返回空数组的函数
- mongodb - 每当我尝试查找最小值和最大值时,我都会得到重复的结果
- reactjs - onClick 返回 SyntheticBaseEvent
- flutter - 继续下载会弄乱文件
- reactjs - 如何在使用上下文 API 和 useReducer 的反应应用程序中测试组件
- autodesk-forge - Autodesk forge 查看器
- sql - 根据行中存在的 NULL 值的数量删除重复的行
- rest - 领域驱动设计中跨微服务实体的继承
- c# - 如何使用 SQL Server - 带有 EntityFramework Core 的时态表