如何修复getPlayerState for Youtube API以返回int值?

2024-09-27 21:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

错误:

selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'getPlayerState' of null

或者

Message: javascript error: getPlayerState is not a function

HTML代码:

<div id="movie_player"></div>

Javascript代码:

<script src="http://www.youtube.com/player_api"></script>

<script>
// create youtube player
var player;
var video_id = 'qCTMq7xvdXU';
let player_vars = {"playsinline": 1, "origin": "https://www.youtube.com"}
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('movie_player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
function cueVideo(url) {
    player.cueVideoByUrl(url);
    }
function VideoReady(id) {
    player.loadVideoById(id);
}

Python代码:

self.driver.execute_script(
                "ytplayer = document.getElementById('player');")
            player_status = self.driver.execute_script(
                "return ytplayer.getPlayerState();")
            print(player_status)

理想情况下,我希望getPlayerState()将播放器的状态返回为-1、0、1、2、3、4、5,这将允许我继续下一步。如果状态码为0(或已完成),则使用加载下一首歌曲selenium.execute\脚本使用从Python脚本加载的videoId。你知道吗

编辑:键入控制台.log(player.getPlayerState())打印出播放器的实际值。所以getPlayerState()是一个函数。你知道吗


Tags: the代码eventidyoutubevarvideoscript

热门问题