含Web Scraper的Node.js网站部署及定时运行求助
如何部署带定时任务的Node.js爬虫并实现前端数据访问?
我学习JavaScript已有40天,做了一个Web爬虫,用Puppeteer抓取美元及指数相关数据,保存为JSON文件;前端读取这些JSON文件做计算后展示。
现在需要让爬虫脚本index.js每天早上8点自动运行,但我之前只部署过静态网站,完全不知道怎么处理带Node.js和定时任务的项目。
本地测试时,我必须把项目放在XAMPP的localhost目录下,否则前端读取JSON会触发CORS错误;测试时手动在终端执行node index.js,刷新浏览器就能看到更新后的数据。
我的爬虫代码(index.js)
const puppeteer = require('puppeteer'); const fs = require('fs'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://br.advfn.com/investimentos/futuros/di-depositos-interfinanceiros/cotacoes',{ waitUntill: 'load', timeout: 0 }); const textNode = await page.evaluate(()=>{ const nodeText = document.querySelector(".even.first").innerText; const text = [nodeText]; return text }); fs.writeFile('arreglo2.json', JSON.stringify(textNode), err =>{ if (err) throw new Error ('algo deu errado') console.log('deu certo') }) })(); //**********************pegar o DX**************************************************/ (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://br.tradingview.com/symbols/TVC-DXY/',{ waitUntill: 'load', timeout: 0 }); const textNode = await page.evaluate(()=>{ const nodeText = document.querySelector(".js-quote-ticker.tv-site-table__row.tv-widget-watch-list__row:nth-child(2)").children[1].children[1].children[0].innerHTML; const text = [nodeText]; return text }); fs.writeFile('arreglo.json', JSON.stringify(textNode), err =>{ if (err) throw new Error ('algo deu errado') console.log('deu certo') }) })(); /**********vai pegar a cotação do fechamento do colar */ (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://br.advfn.com/bolsa-de-valores/fx/USDBRL/cotacao',{ waitUntill: 'load', timeout: 0 }); const textNode = await page.evaluate(()=>{ const nodeText = document.querySelector(".qs-current-price").innerText; const text = [nodeText]; return text }); fs.writeFile('cotacaoFechamento.json', JSON.stringify(textNode), err =>{ if (err) throw new Error ('algo deu errado') console.log('deu certo') }) })();
希望得到以下帮助:
- 如何部署这个包含Node.js脚本的项目,让
index.js每天自动运行? - 部署后如何确保前端能正常访问生成的JSON文件,避免CORS问题?
内容的提问来源于stack exchange,提问作者vinicius souza
相关产品推荐
相关产品推荐

