首页 > 解决方案 > 尊重 robots.txt 文件的 Puppeteer 代码

问题描述

这在 Scrapy Scrapy 和尊重 robots.txt中似乎是可能的,但是在 Puppeteer 中是否有一种简单的方法可以做到这一点?

我还没有找到一种简单的方法来将“尊重机器人”构建到 Puppeteer 命令中。

标签: javascriptpuppeteer

解决方案


我不相信 puppeteer 内置任何东西,但您可以使用 puppeteer 进行访问robots.txt,然后使用许多npm模块中的任何一个进行解析robots.txt,以查看是否允许您获取任何特定的 URL。例如,以下是您可以使用robots-txt-parser 的方式

const robotsParser = require('robots-txt-parser')
const robots = robotsParser()

// Now inside an async function
// (or not if using a version of Node.js that supports top-level await)

await robots.useRobotsFor('https://example.com/')
if (await robots.canCrawl(urlToVisit)) {
  // Do stuff with puppeteer here to visit the URL
} else {
  // Inform the user that sadly crawling that URL is forbidden
}

推荐阅读