python-selenium:execute_script 与execute_async

rob*_*ing 2 python selenium

我不太清楚硒execute_scriptexecute_async_script硒之间的区别。

将 python-selenium 中的示例放入 pytest 函数中:

driver.get(url)

js = '''
var video = document.getElementById("myVideo");

video.onplaying=function() {
  return "play";
};
'''

video_play = driver.execute_script(js)
assert video_play == "play"
Run Code Online (Sandbox Code Playgroud)

结果是:

E       AssertionError: assert None == 'play'
Run Code Online (Sandbox Code Playgroud)

我缺少什么?我应该在js中使用execute_async和async/await函数吗?你能给我举一些例子吗?

Tar*_*ani 5

您需要为此使用异步脚本。

driver.get(url)

js = '''
var callback = arguments[arguments.length - 1];
var video = document.getElementById("myVideo");

video.onplaying=function() {
  callback ("play");
};

setTimeout(function(){
  callback("notplayed");
}, 2000);
'''

video_play = driver.execute_async_script(js)
assert video_play == "play"
Run Code Online (Sandbox Code Playgroud)

上面的作用是,它最多等待 2 秒才能播放,如果没有播放则notplayed返回。

请记住,在脚本完成之前调用不会返回。因此,不要认为您可以在异步脚本之后执行其他代码。直到回调或者异步超时,代码都会卡在execute_async_script