selenium如何处理H5视频
selenium处理H5视频主要使用的是javascript,javascript函数有内置的对象叫arguments,arguments包含了调用的参数组,[0]代表取第一个值。
currentSrc 返回当前音频或视频的URL,如果未设置则返回空字符串。
load() , play() , pause()代表视频的加载,播放,停止。
示例1:
from selenium import webdriver from time import sleep dr = webdriver.Chrome() dr.get('https://www.videojs.com') dr.implicitly_wait(10) video = dr.find_element_by_css_selector("#vjs_video_3_html5_api") url = dr.execute_script("return arguments[0].currentSrc;",video) print(url) print("start") dr.execute_script("return arguments[0].play()",video) sleep(10) print('stop') dr.execute_script("return arguments[0].pause()",video) dr.quit()
运行上面代码报错如下:
blob:https://videojs.com/905716de-68da-493b-b78d-0a56ea256ee2 start Traceback (most recent call last): File "js.py", line 11, in <module> dr.execute_script("return arguments[0].play()",video) File "F:\python3.7\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 635, in execute_script 'args': converted_args})['value'] File "F:\python3.7\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "F:\python3.7\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.JavascriptException: Message: javascript error: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD (Session info: chrome=83.0.4103.61)
解决思路,模拟手动点击播放
from selenium import webdriver from time import sleep dr = webdriver.Chrome() dr.get('https://www.videojs.com') dr.implicitly_wait(10) video = dr.find_element_by_css_selector("#vjs_video_3_html5_api") url = dr.execute_script("return arguments[0].currentSrc;",video) print(url) print("start") js = "document.querySelector('#vjs_video_3 > div.vjs-poster').click()" dr.execute_script(js) sleep(15) print('stop') dr.execute_script("return arguments[0].pause()",video) dr.quit()
结果:
blob:https://videojs.com/3d283b74-9f8e-4573-9820-d805ce938195
start
stop
***Repl Closed***
本文来自博客园,作者:Harry_666,转载请注明原文链接:https://www.cnblogs.com/harry66/p/13467148.html