You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Selenium和Python阻止或设置HTML5视频自动播放?

控制HTML5视频自动播放的脚本方案

完全可以通过脚本来控制HTML5视频的自动播放状态,不管是全局禁用还是针对特定元素,都有可行的方法,我给你分场景整理一下:

一、全局控制所有HTML5视频的自动播放

如果你想一次性处理页面上所有(包括后续动态加载的)视频,可以用下面的脚本:

// 1. 处理已存在的视频元素
document.querySelectorAll('video').forEach(video => {
  // 移除autoplay属性
  video.removeAttribute('autoplay');
  // 暂停正在播放的视频
  if (!video.paused) video.pause();
  // 阻止后续自动播放尝试
  video.addEventListener('play', (e) => {
    e.preventDefault();
    video.pause();
  }, true);
});

// 2. 监听动态新增的视频元素(比如懒加载、AJAX加载的)
const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    mutation.addedNodes.forEach(node => {
      if (node.tagName === 'VIDEO') {
        node.removeAttribute('autoplay');
        node.addEventListener('play', (e) => {
          e.preventDefault();
          node.pause();
        }, true);
      } else if (node.querySelectorAll) {
        node.querySelectorAll('video').forEach(video => {
          video.removeAttribute('autoplay');
          video.addEventListener('play', (e) => {
            e.preventDefault();
            video.pause();
          }, true);
        });
      }
    });
  });
});

observer.observe(document.body, { childList: true, subtree: true });

二、针对特定ID的视频进行控制

针对你提到的still_video_object_html5_api这个ID,直接定位元素操作更高效:

const targetVideo = document.getElementById('still_video_object_html5_api');
if (targetVideo) {
  // 移除自动播放属性
  targetVideo.removeAttribute('autoplay');
  // 立即暂停(如果正在播放)
  if (!targetVideo.paused) targetVideo.pause();
  // 锁死播放事件,防止后续触发自动播放
  targetVideo.addEventListener('play', (e) => {
    e.stopImmediatePropagation();
    targetVideo.pause();
  }, true);
}

三、针对特定类名的视频进行控制

如果要处理所有带.vjs-tech类的视频,用类选择器即可:

document.querySelectorAll('.vjs-tech').forEach(video => {
  video.removeAttribute('autoplay');
  if (!video.paused) video.pause();
  video.addEventListener('play', (e) => {
    e.preventDefault();
    video.pause();
  }, true);
});

临时禁用的小技巧

如果你只是想临时阻止某一次自动播放,而不是永久禁用,可以直接在浏览器控制台执行简化版代码:

  • 针对特定ID:document.getElementById('still_video_object_html5_api')?.pause();
  • 全局暂停:document.querySelectorAll('video').forEach(v=>v.pause());

这些脚本可以直接在浏览器控制台运行,或者放到用户脚本管理器(比如Tampermonkey)里自动执行,完美解决网站自动播放视频的问题~

内容的提问来源于stack exchange,提问作者Otaku Wiz

火山引擎 最新活动