使用Lua脚本在Splash中访问google.com的DOM

我正在尝试在Splash中运行Lua脚本执行Google搜索,并获取搜索结果的截屏。当我尝试使用xpath或css选择器选择Google搜索框时,我的Lua脚本会发生如下错误:

{
    "error": 400,
    "type": "ScriptError",
    "description": "在执行Lua脚本时发生错误",
    "info": {
        "message": "[string \"function main(splash, args)\r...\"]:9: 不能选择指定的元素 {'type': 'JS_ERROR', 'js_error_type': '语法错误', 'js_error_message': 'SyntaxError: DOM Exception 12', 'js_error': '错误:SyntaxError: DOM Exception 12', 'message': \"JS error: 'Error: SyntaxError: DOM Exception 12'\"}",
        "type": "SPLASH_LUA_ERROR",
        "splash_method": "select",
        "source": "[string \"function main(splash, args)\r...\"]",
        "line_number": 9,
        "error": "不能选择指定的元素 {'type': 'JS_ERROR', 'js_error_type': 'SyntaxError', 'js_error_message': 'SyntaxError: DOM Exception 12', 'js_error': 'Error: SyntaxError: DOM Exception 12', 'message': \"JS error: 'Error: SyntaxError: DOM Exception 12'\"}"
    }
}

这是我的Lua脚本:

function main(splash, args)

  splash.private_mode_enabled = false
  splash:set_user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0")

  assert(splash:go(args.url))
  assert(splash:wait(1.0))

  search_box = assert(splash:select("//div[@class='a4bIc']/input"))
  search_box:focus()
  search_box:send_text('my user agent')
  search_box:send_keys('<Enter>')
  assert(splash:wait(2.0))

  return splash:png()
end

我尝试设置自定义标头,以隐私模式运行脚本,但什么都没用。 然而,当使用duckduckgo.com时,相同的脚本可以正常运行并得出正确的输出。当目标URL是google.com时,问题就出现了。 我认为Google检测到浏览器正在被一个机器人(脚本)控制,因此禁止访问DOM树。 有什么办法可以解决这个问题吗?

点赞
用户3342050
用户3342050

你的选择器有问题。

"//div[@class='a4bIc']/input"

打开网页,点击F12键,使用检查器确定要针对该输入字段进行定位的div类。也可能是它们的类名是动态生成的,以混淆它们。

2020-10-21 10:14:52
用户3342050
用户3342050

也许页面还没有完全下载/渲染

function main(splash, args)
    splash.private_mode_enabled = false
    splash:set_user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0")

    local ok, reason = assert( splash:go(args.url) )

    if ok then
        local wait, increment, maxwait = 0, 0.1, 10
        while wait < maxwait and not splash:select("//div[@class='a4bIc']/input") do
            splash:wait(increment)  --  等待直到它存在,或者超时
            wait = wait +increment
        end
        if wait >= maxwait then
            print('超时')
        else
            search_box = splash:select("//div[@class='a4bIc']/input")
            search_box:focus()
            search_box:send_text('my user agent')
            search_box:send_keys('<Enter>')
            splash:wait(2.0)
            return splash:png()
        end
    else
        print( reason )  --  查看是否有告诉你为什么
    end
end
2020-10-22 19:33:32