我正在开发一个由 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?
最佳答案
据我所知,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()'))
(如果 pn
为 nil
,如果 args.pn
不是 pn = 中的有效数字文字,则会崩溃tonumber(args.pn)
.)
关于javascript - 如何使用splash和scrapy将变量从Lua脚本传递到Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632845/