selenium 处理HTML5视频

selenium 处理HTML5视频

1、代码实现

  • 代码一
import time
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://videojs.com/")
driver.implicitly_wait(30)

element_video = driver.find_element_by_id("preview-player_html5_api")
url = driver.execute_script("return arguments[0].currentSrc",element_video)
print(url)

# 播放视频
driver.execute_script("return arguments[0].play()",element_video)
# 持续播放五秒
time.sleep(5)

# 暂停视频
driver.execute_script("return arguments[0].pause()",element_video)
time.sleep(3)

# 重新载入视频
driver.execute_script("return arguments[0].load()",element_video)
time.sleep(3)

# 播放视频
driver.execute_script("return arguments[0].play()",element_video)
# 持续播放五秒
time.sleep(5)

driver.quit()

该代码会报错:selenium.common.exceptions.JavascriptException: Message: NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
尝试解决方法:模拟用户点击操作-即可进行播放

  • 代码2
import time
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://videojs.com/")
driver.implicitly_wait(30)

element_video = driver.find_element_by_id("preview-player_html5_api")
url = driver.execute_script("return arguments[0].currentSrc",element_video)
print(url)

# 模拟用户点击播放按钮
element_video.click()
time.sleep(5)

# 暂停视频
print("暂停视频")
driver.execute_script("return arguments[0].pause()",element_video)
time.sleep(3)

# 重新载入视频
print("载入视频")
driver.execute_script("return arguments[0].load()",element_video)
time.sleep(3)

# 播放视频
print("播放视频")
driver.execute_script("return arguments[0].play()",element_video)
# 持续播放五秒
time.sleep(5)

driver.quit()

代码报错:selenium.common.exceptions.ElementClickInterceptedException: Message: Element

obscures it
尝试解决方法:既然不能点击该元素,那么我们是否可以直接不依赖该元素被点击的属性,操作使用鼠标操作点击,真实模拟用户

  • 代码3-最终实现效果
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()
driver.get("http://videojs.com/")
driver.implicitly_wait(30)

element_video = driver.find_element_by_id("preview-player_html5_api")
url = driver.execute_script("return arguments[0].currentSrc", element_video)
print(url)

# 使用鼠标事件,进行点击,播放5秒
ActionChains(driver).click(element_video).perform()
time.sleep(5)

# 暂停视频
print("暂停视频")
driver.execute_script("return arguments[0].pause()", element_video)
time.sleep(3)

# 重新载入视频
print("载入视频")
driver.execute_script("return arguments[0].load()", element_video)
time.sleep(3)

# 播放视频
print("播放视频")
driver.execute_script("return arguments[0].play()", element_video)
# 持续播放五秒
time.sleep(5)
driver.quit()

2、获取视频的时长

# 获取视频文件的时长
print("获取视频文件的时长")
print(driver.execute_script("return arguments[0].duration", element_video))
time.sleep(3)

你可能感兴趣的:(selenium)