【问题标题】:How to call my web scraper from within an express route?如何从快速路线中调用我的网络爬虫?
【发布时间】:2021-02-10 06:29:39
【问题描述】:

我的 Nodejs 服务器根目录中有一个网络爬虫,运行 express。这是一个使用 needle 对 html 发出 get 请求的文件,它返回一个数据数组。然后我有我的 index.js 和我的快速路线,一个简单的路线,比如 "/api/scrape"

但是,当我转到该 url 时,服务器控制台仍会在刮板中打印出一个 console.log 以表明它正在完成。但是 express 想在等待刮板完成之前继续前进。

如何在将响应发送回 React 之前等待爬虫完成。

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    您可以尝试将调用网络爬虫的函数转换为异步函数,并使用 await 快速调用该函数。这样,express 将等待返回的承诺,而不是继续前进。

    我相信这在 express 中也是可以实现的,将其作为中间件:

    const example_scrape = (req, res, next) => {
    ... do your scraping
    next() //allows express to move onto the next route? not sure the terminology 
    }
    
    
    app.get('/api/scrape_my_site', example_scrape, (req,res) => {
    ...
    }
    

    【讨论】:

      【解决方案2】:

      你可以看看这个项目 - https://github.com/vodolaz095/email-parser-api

      它是一个简单的 Selenium 驱动的 api,它是从 nodejs 应用程序中调用的,暴露了某种 REST API。

      代码很简单

      这里是 expressjs 路由器代码,它实际上调用 scraper 以响应 POST 请求

      https://github.com/vodolaz095/email-parser-api/blob/master/index.js#L21-L53

      这里是爬虫代码

      https://github.com/vodolaz095/email-parser-api/blob/master/lib/parser.js

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-26
        • 2012-01-14
        相关资源
        最近更新 更多