【问题标题】:Lua: "error": "attempt to call method 'mouse_click' (a nil value)",Lua: "error": "attempt to call method 'mouse_click' (a nil value)",
【发布时间】:2022-01-25 06:46:16
【问题描述】:

我是 Lua 的新手,并尝试使用“for”循环遍历“items”中的所有链接,并使用 mouse_click() 函数单击所有链接。但它会抛出 "error": "attempt to call method 'mouse_click' (a nil value)" 我该怎么做?我自己尝试了下面提到的代码,但可能缺少一些东西。从文档中,我发现 Lua 有两种类型的 for 循环。数字和通用。但是要遍历链接,然后单击它我必须使用什么?

再一次,我对 Lua 很陌生。只是想熟悉它,所以我正在寻求所有专家的指导。

function main(splash, args)
  
  splash:set_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
  splash.private_mode_enabled = false
  assert(splash:go(args.url))
  assert(splash:wait(3))
  
  items = assert(splash:select("div.item-list-content a"))
  
  for item in pairs(items) do
    item:mouse_click()
    assert(splash:wait(5))
  end
  
  splash:set_viewport_full()
  return {
    html = splash:html(),
    png = splash:png(),
    har = splash:har(),
  }
end

输出

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

【问题讨论】:

  • 哪里说有个函数叫mouse_click
  • @JosephSible-ReinstateMonica 抱歉输入错误。这是一种方法
  • 你有网站的链接吗?使用它检查您的代码并找到改进更容易。

标签: lua scrapy lua-table scrapy-splash


【解决方案1】:

Select 仅返回 one 元素,因此使用 pairs 迭代它没有意义(因为您将迭代该元素的字段,这可能不是您想要的想)。您可能想使用select_all,然后使用 ipairs 来遍历与选择器匹配的元素。有关详细信息和示例,请参阅 select 文档。

[更新以解决您的评论]如果您查看我引用的示例,您会发现它看起来像这样:

    local imgs = splash:select_all('img')
    local srcs = {}

    for _, img in ipairs(imgs) do
      srcs[#srcs+1] = img.node.attributes.src
    end

由于ipairs 返回两个值(索引及其值),您必须使用for _, item in ipairs(items) 而不是for item in ipairs(items)(因为在后一种情况下item 将获得索引值而不是项目)。

【讨论】:

  • 我按照你的建议使用了 select_all 和 ipairs 但现在它显示 { "error": 400, "type": "ScriptError", "description": "Error occurred while execution Lua script", "info ": { "source": "[string \"function main(splash, args)\r...\"]", "line_number": 11, "error": "attempt to index local 'item' (一个数字value)", "type": "LUA_ERROR", "message": "Lua 错误: [string \"function main(splash, args)\r...\"]:11: 尝试索引本地 'item' (一个数值)" } }
  • @RaisulIslam 你不能索引数字值。 items 是一个数字列表。所以在你的循环项目中是一个数值,因此你不能做 item:mouse_click()。这是非常基本的 Lua。如果您无法理解这样的错误消息,请阅读手册并做一个初学者教程。你有一个行号、一个变量名、它的类型和一个失败的操作。你还能希望什么?你只需要考虑一下。你期望什么价值?它是什么?你需要改变什么来解决它?
猜你喜欢
  • 2018-05-25
  • 2022-12-27
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
相关资源
最近更新 更多