问题
I would like in interval to track video play progress in a HTML video.
Based on the tutorial, the HTML video DOM timeupdate
event can be achieved by something like below:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
chrome_options = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path=r"\Browsers\chromedriver.exe",
options=chrome_options)
browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")
WebDriverWait(browser, 70).until(EC.element_to_be_clickable(
(By.XPATH, "//button[@aria-label='Play']"))).click()
javascript_to_execute = ' return document.getElementById("ytplayer").currentTime();'
for x in range(0, 2):
time_current = browser.execute_script(javascript_to_execute)
print(time_current)
time.sleep(1)
However, I got the following error
Message: javascript error: Cannot read property 'currentTime' of null
May I know where did I do wrong. Appreciate for any hint or help. Thanks in advance
回答1:
The following code should work thanks to the suggestion made from OP1. To obtain the currentTime of a HTML video using JS, the following can be considered.
The JS code, to extract the video current time is
"return document.getElementsByTagName('video')[0].currentTime;"
The above JS can be executed using the method execute_script
time_video = browser.execute_script("return document.getElementsByTagName('video')[0].currentTime;")
To investigate whether the above implementation is able to obtain the video timing, say, in the middle of the video. We first jump to a position, say 180 sec from the starting point using the code below.
player_status = browser.execute_script("document.getElementsByTagName('video')[0].currentTime += 180;")
The full code are as below;
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
chrome_options = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path = r"some_path\Browsers\chromedriver.exe",
options = chrome_options)
browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")
WebDriverWait(browser, 70).until(EC.element_to_be_clickable(
(By.XPATH, "//button[@aria-label='Play']"))).click()
print('Fast forward')
player_status = browser.execute_script("document.getElementsByTagName('video')[0].currentTime += 80;")
print('Get Current time')
time_video = browser.execute_script("return document.getElementsByTagName('video')[0].currentTime;")
来源:https://stackoverflow.com/questions/61519327/getting-error-javascript-error-cannot-read-property-when-tracking-html-vide