执行 javascript 异步函数和 return 导致 selenium

Execute javascript async function and return result in selenium

我正在尝试在 selenium 中执行以下脚本

    result = driver.execute_script('let result; await axe.run().then((r)=> {result=r}); return result;')

但它正在返回

javascript error: await is only valid in async function

我也试过

    result = @driver.execute_async_script('(async() => {return await axe.run();})();')

但它返回了以下错误

Selenium::WebDriver::Error::ScriptTimeoutError: script timeout: result was not received in 30 seconds

如果你想使用execute_async_script你需要调用传递的回调函数来告诉驱动程序你已经完成了,否则驱动程序不会识别你已经完成并等待直到超时。回调函数是最后一个参数:

script = "
var callback = arguments[arguments.length - 1]; // this is the callback to call when you are done
axe.run().then((r)=> {callback(r)});
"
result = @driver.execute_async_script(script);

供参考see