【问题标题】:Using Nightmare web-scraping with React (create-react-app)在 React 中使用 Nightmare 网络抓取 (create-react-app)
【发布时间】:2019-09-05 21:56:01
【问题描述】:

我正在设置一个 create-react-app 以从 API 中提取,在页面上显示结果,然后当您单击其中一个结果时,我想从从传递的 URL 中抓取一些数据API。我已经单独测试了网络爬虫,并且我已经单独测试了应用程序。分开它们效果很好,但是当我尝试同时使用它们时会出现错误:

(编辑):这是错误前 node_modules/nightmare/node_modules/electron/ 的第 1-4 行

   1 | var fs = require('fs')
   2 | var path = require('path')
   3 |
   4 | var pathFile = path.join(__dirname, 'path.txt')
TypeError: Cannot read property 'existsSync' of undefined
(anonymous function)
node_modules/nightmare/node_modules/electron/index.js:7
   4 | 
   5 | var pathFile = path.join(__dirname, 'path.txt');
   6 | 
>  7 | if (fs.existsSync(pathFile)) {
   8 |   module.exports = path.join(__dirname, fs.readFileSync(pathFile, 'utf-8'));
   9 | } else {
  10 |   throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again');

我在网上搜索并尝试实施一些解决方案,但没有任何效果。我尝试将requires 更改为window.require,并且我还删除了我的node_modules 文件夹以尝试查看是否会导致问题。在我的 node_modules 文件夹中,我检查了 node_modules 文件夹并找到了 nightmare 和 electron 模块,但它们里面也有 node_modules,不确定这是否正常。我可以使用你们可能有的任何帮助或建议!

const Nightmare = require('nightmare');
const nightmare = Nightmare({ show: false });
// have this set to false for performance but can set to true if you'd like to see what it's scraping

export const webScraper = (link) => {
  nightmare
    .goto(link)
    .wait('.desc_text')
    .evaluate(() => {
      let thing = document.querySelector('.class_of_thing_grabbed');
      return thing.innerHTML
    })
    .end()
    .then((result) => {
      return result
    })
    .catch((error) => {
      console.error('Search failed:', error);
    });
}

当自己运行噩梦应用程序时,它会返回我想要的链接的内部 HTML,但是当我尝试在我的 React 应用程序中使用它时,整个应用程序崩溃并且我收到了该错误。

【问题讨论】:

  • 你需要fs:const fs = require("fs")
  • 谢谢,@pguardiaro,但在 node_modules 内的电子模块的第 1 行已经需要它。你是说我应该在其他地方需要它吗?
  • 显然你这样做是因为它没有在那里定义。 Electron 有 2 个运行时,一个后端和一个浏览器,您需要 fs 和 nightmarejs 在后端并在浏览器中做出反应。

标签: reactjs web-scraping electron nightmare


【解决方案1】:

这可能是因为您在 Electron 窗口内运行 Nightmare,结果是在 renderer process 内运行。默认情况下,渲染器进程无法访问像 fs 这样的 Node.js API。您可以通过在创建BrowserWindow 时将webPreferences.nodeIntegration 设置为true 来更改此设置,如下所示:

new BrowserWindow({
  webPreferences: { nodeIntegration: true }
})

请注意,不建议这样做:如果有人设法将恶意脚本注入您的 BrowserWindow,他们将有权访问所有 Node.js API,并可能危及用户的系统.

更安全的解决方案是使用 Electron 的 inter-process communication (IPC) 功能。以下是它的工作原理:

  • 运行 React 的渲染器进程(nodeIntegration关闭)向主进程发送一条消息,告诉它抓取某个 URL。

  • 默认情况下可以访问所有 Node.js API 的主进程运行爬虫并将结果作为消息发送回渲染器进程。

  • 渲染器进程收到此消息并显示结果。

这允许您使用可能有危险的 Node.js API,而不会将它们暴露给渲染器进程。

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2022-01-23
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多