【发布时间】: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