solidSpoon / TodayIFound

TodayIFound 是一个记录好玩、有趣和有用信息的项目,旨在分享日常生活中的发现和灵感。包括各种主题,欢迎加入分享。
7 stars 0 forks source link

【工具推荐】一个灵活的 nodejs 爬虫库 —— x-crawl #15

Open coder-hxl opened 1 year ago

coder-hxl commented 1 year ago

x-crawl · npm GitHub license

x-crawl 是一个灵活的 Node.js 多功能爬虫库。灵活的使用方式和众多的功能可以帮助您快速、安全、稳定地爬取页面、接口以及文件。

如果你也喜欢 x-crawl ,可以给 x-crawl 存储库 点个 star 支持一下,感谢大家的支持!

GitHub:https://github.com/coder-hxl/x-crawl

特征

示例

以每天自动获取世界各地的经历和房间的一些照片为例:

// 1.导入模块 ES/CJS
import xCrawl from 'x-crawl'

// 2.创建一个爬虫实例
const myXCrawl = xCrawl({ maxRetry: 3, intervalTime: { max: 3000, min: 2000 } })

// 3.设置爬取任务
// 调用 startPolling API 开始轮询功能,每隔一天会调用回调函数
myXCrawl.startPolling({ d: 1 }, async (count, stopPolling) => {
  // 调用 crawlPage API 来爬取页面
  const res = await myXCrawl.crawlPage({
    targets: [
      'https://www.airbnb.cn/s/experiences',
      'https://www.airbnb.cn/s/plus_homes'
    ],
    viewport: { width: 1920, height: 1080 }
  })

  // 存放图片 URL 到 targets
  const targets = []
  const elSelectorMap = ['._fig15y', '._aov0j6']
  for (const item of res) {
    const { id } = item
    const { page } = item.data

    // 等待页面加载完成
    await new Promise((r) => setTimeout(r, 300))

    // 获取页面图片的 URL
    const urls = await page!.$$eval(
      `${elSelectorMap[id - 1]} img`,
      (imgEls) => {
        return imgEls.map((item) => item.src)
      }
    )
    targets.push(...urls)

    // 关闭页面
    page.close()
  }

  // 调用 crawlFile API 爬取图片
  await myXCrawl.crawlFile({ targets, storeDir: './upload' })
})

运行效果:

注意: 请勿随意爬取,爬取前可查看 robots.txt 协议。这里只是为了演示如何使用 x-crawl 。

更多

更多内容可查看:https://github.com/coder-hxl/x-crawl