如何使用 Splash 和 Scrapy 在 Lua 脚本和 Javascript 之间传递变量?

我正在使用 scrapy 和 splash 进行爬取项目。我是 Lua 和 Javascript 的新手。我现在遇到了这样一种情况,需要将一个变量从 Lua 传递给 Javascript,但是我不知道如何传递。

以下是我的 Lua 脚本

 script = """
    function main(splash, args)
        assert(splash:go(args.url))
        pn = tonumber(args.pn)
        assert(splash:wait(10))
        assert(splash:runjs('document.querySelector("#profile-listing-uploads > div:nth-child(2) > ul > li:nth-child("+ pn +") > a").click()'))
        assert(splash:wait(10))
        return {
        html = splash:html()
        }
    end
    """

我遇到的错误是

Bad request to Splash: {'info': {'line_number': 7, 'source': '[string "..."]', 'type': 'LUA_ERROR', 'message': 'Lua error: [string "..."]:7: JS error: "ReferenceError: Can\'t find variable: pn"', 'error': 'JS error: "ReferenceError: Can\'t find variable: pn"'}, 'description': 'Error happened while executing Lua script', 'type': 'ScriptError', 'error': 400}

看起来这是一个 Javascript 错误,无法找到在 Lua 脚本中存在的变量 pn。我该如何将 pn 的值传递给 javascript?

点赞
用户8794009
用户8794009

尝试使用以下方式访问您的参数:

pn = tonumber(splash.args.pn)
2019-08-24 03:32:11
用户9383219
用户9383219

根据我的计算,Lua 脚本的第 7 行是 assert(splash:wait(10)),但在那里并没有使用 pn

如果编号偏移了一个,也许错误实际上是在第 6 行, assert(splash:runjs('document.querySelector("#profile-listing-uploads > div:nth-child(2) > ul > li:nth-child("+ pn +") > a").click()'))。我不知道是否有一些 Lua 函数可以在 JavaScript 运行时定义变量,但是你应该能够将变量 pn 的值连接到 JavaScript 中,像这样:

assert(splash:runjs('document.querySelector("#profile-listing-uploads > div:nth-child(2) > ul > li:nth-child(' .. pn .. ') > a").click()'))

(如果 pnnil,如果 args.pnpn = tonumber(args.pn) 中不是一个有效的数字文字,则会崩溃。)

2019-08-25 00:44:57