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

解决Selenium在Chrome浏览器中自动化播放HTML5视频时的autoplay政策限制问题,通过先执行用户点击行为再播放视频的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值