首页 > 解决方案 > Nightmare.js 和 Github 操作

问题描述

我遇到了 Nightmare.js 和 Github Actions 的问题,我想触发 Github Actions 计划以从网站上抓取数据并更新 mongodb 中的数据。一开始我尝试使用 Pupeeteer.js,效果很好,但不打开浏览器就无法工作,所以我切换到 Nightmare.js。yaml 文件每次都能正常工作,但 Mongodb 中的数据仍未更新。team.js 和 match.js 的每个 JS 文件都是一个从网站抓取数据的函数。这是我的 gh-actions yaml 文件

name: Crawler for MLB static
on:
  schedule:
    - cron: '0 7 * * *'
  workflow_dispatch:
jobs:
  start_scraping:
    name: start_scraping
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@main
    - name: Build
      run: npm install
    - name: Get static
      run: | 
       npm run match
       npm run team

和我的 package.json 文件

{
  "main": "index.js",
  "engines": {
    "node": "14.17.0"
  },
  "scripts": {
    "start": "node ./index.js",
    "match": "node ./match.js",
    "team": "node team.js"
  },
  "dependencies": {
    "express": "^4.17.1",
    "mongodb": "^4.1.1",
    "nightmare": "^3.0.2"
  }
}

匹配.js 文件

const Nightmare = require("nightmare");
const nightmare = Nightmare();

const { MongoClient, ObjectId } = require("mongodb");
const uri = "%%%";
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const matchDBID = "%%%";
const matchesCrawler = async () => {
  const matches = await nightmare
    .goto("https://www.msn.com/zh-tw/sports/mlb/schedule")
    .evaluate(() => {
      let results = [...document.querySelectorAll(".spl-matchrow")];
      return results.map((element) => element.innerText);
    })
    .end(); 
  console.log(matches);
  client.connect(async (err) => {
    if (err) throw err;
    const collection = client.db("mlb").collection("mlbStatic");
    await collection.updateOne(
      { _id: ObjectId(matchDBID) },
      { $set: { data: matches } }
    );
    console.log("success!");
  });
};

matchesCrawler();

我认为这可能是 Nightmare.js 无法使用 gh-actions 运行的问题,希望有人能解决这个问题,提前感谢!

标签: javascriptnode.jsgithubgithub-actionsnightmare

解决方案


推荐阅读