Splash API/lua错误:尝试索引本地元素(空值)

我正在编写与scrapy + splash一起使用的lua脚本以用于网站。我想编写一个脚本,输入文本,然后单击按钮。我有以下代码:

function main(splash)
   local url = splash.args.url
   assert(splash:go(url))
   assert(splash:wait(5))

   local element = splash:select('.input_29SQWm')
   assert(element:send_text("华尔街,纽约"))
   assert(splash:send_keys("<Return>"))
   assert(splash:wait(5))

   return {
     html = splash:html(),
   }
end

现在我正在使用splash API测试我的代码是否正常运行。当我单击"Render!"时,我收到以下消息:

{
  "info": {
      "message": "Lua error: [string \"function main(splash)\r...\"]:7: attempt to index local 'element' (a nil value)",
      "type": "LUA_ERROR",
      "error": "attempt to index local 'element' (a nil value)",
      "source": "[string \"function main(splash)\r...\"]",
      "line_number": 7
  },
  "error": 400,
  "type": "ScriptError",
  "description": "Error happened while executing Lua script"
}

所以出现一些原因在我尝试发送"华尔街,纽约"时element仍然为空。我不明白为什么;如果我在chrome控制台中输入以下内容:

$('.input_29SQWm')

我找到了想要的元素!

Q:有人知道我做错了什么吗?

提前感谢!

点赞
用户2858170
用户2858170

如错误信息所示,您尝试对本地的'element'进行索引,但该变量是nil。 错误发生在第7行:assert(element:send_text("Wall Street, New York"))

那么为什么是'nil'呢?在第6行,我们给'element' 赋值:

local element = splash:select('.input_29SQWm')

显然,splash:select('.input_29SQWm') 返回的是nil。

让我们看一下文档:

http://splash.readthedocs.io/en/stable/scripting-ref.html#splash-select

如果无法使用指定的选择器找到元素,则将返回nil。如果您的选择器不是有效的CSS选择器,则会引发错误。

你的错误是没有处理'nil'可能返回的情况。您不能盲目地引用可能是'nil'的值。 此外,当调用可能引发错误的函数时,应使用受保护的调用。

现在,您需要找出为什么'select' 没有找到使用该选择器的元素。

我建议在继续之前阅读一些关于Lua中的错误处理的内容。

2017-01-12 21:23:18