首页 > 解决方案 > 抓取:由于结构变化,网页抓取停止

问题描述

在抓取网页时,网页的结构不断变化,我的意思是它的动态导致我的爬虫停止工作的情况。是否有机制在运行完整爬虫之前识别网页结构变化,从而识别结构是否发生变化。

标签: htmlweb-scrapingweb-crawler

解决方案


您当然可以使用“快照”来比较同一页面的 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 响应作为内容以您喜欢的语言进行哈希处理。


推荐阅读