解决Selenium在chrome中播放视频报错:play() failed because the user didn't interact with the document first.

selenium在chrome浏览器中自动化播放html5中的视频时,遇到如下报错:

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/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

Python代码如下: 

#在selenium的实现中options会被转为KEY="goog:chromeOptions"的capability

browser=webdriver.Chrome(executable_path=chrome_driver_path,options=options,

desired_capabilities=caps)


#请求html5视频测试页面

browser.get(html5_url)

time.sleep(3)


#定位视频播放控件

video=browser.find_element_by_xpath("/html/body/video")



#播放视频

video_play=browser.execute_script("returnarguments[0].play()",video)

print(f'video_play:{video_play}')

time.sleep(5)

从网上得知:

Chrome的autoplay政策在2018年4月做了更改,在页面没有产生用户交互时时不能进行自动播放的

所以解决方案是:

先执行用户点击行为再进行播放

 

改进后的代码如下:

#在selenium的实现中options会被转为KEY="goog:chromeOptions"的capability

browser=webdriver.Chrome(executable_path=chrome_driver_path,options=options,


#请求html5视频测试页面

browser.get(html5_url)

time.sleep(3)


#定位视频播放控件

video=browser.find_element_by_xpath("/html/body/video")


#获得视频的URL

video_url=browser.execute_script("returnarguments[0].currentSrc",video)

print(f'video_url:{video_url}')


#只是获取一下视频控件的属性,不算互动

p_width=video.get_property('width')

print(p_width)

#需要click一下才行,也可以其它的动作,可以自行实验

video.click()

#播放视频并停留一段时间

video_play=browser.execute_script("returnarguments[0].play()",video)

print(f'video_play:{video_play}')

time.sleep(5)


#暂停视频

#video.click()

video_pause=browser.execute_script("returnarguments[0].pause()",video)

print(f'video_pause:{video_pause}')
time.sleep(3)

 

本文参考了:https://www.cnblogs.com/lcidy/p/10039592.html

你可能感兴趣的:(技术)