You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium定位非按钮视频全屏元素失败,求正确XPath写法

解决Selenium定位非按钮全屏元素失败的问题

1. 修复代码语法错误

原代码中find_element方法返回单个匹配元素,不能使用[0]索引(只有find_elements返回列表时才需要索引),这会直接导致报错,先修正这一点。

2. 优化全屏元素的XPath定位

针对非按钮类型的全屏元素,可根据以下几种特征调整定位策略:

  • 基于精确class匹配:如果lh-solid是该元素唯一或核心class,用normalize-space处理空格问题:
    //span[normalize-space(@class)='lh-solid']
    
  • 多class组合定位:如果元素有多个class,同时匹配提高准确性:
    //span[contains(@class, 'lh-solid') and contains(@class, 'icon-fullscreen')]
    
  • 结合图标元素定位:如果全屏按钮包含图标(如SVG、Font Awesome),通过子元素特征定位:
    //span[contains(@class, 'lh-solid') and .//svg[@aria-label='全屏']]
    
  • 基于视频容器关联定位:找视频父容器下的目标元素,缩小查找范围:
    //div[contains(@class, 'video-player')]//span[contains(@class, 'lh-solid')]
    

3. 用显式等待替代固定sleep

固定time.sleep()不稳定,改用显式等待确保元素可点击后再操作,提升代码健壮性:

完整修正代码

import time 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions() 
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option("useAutomationExtension", False)

driver = webdriver.Chrome(options=options, executable_path='./driver/chromedriver')
DejeroControlVideo1 = "https://control.dejero.com/return_video/9I_HsFn7NYHiKvtJbHa3WQ"  
driver.get(DejeroControlVideo1)

# 等待预览开关可点击并点击
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='ON']"))).click()
print("preview")

# 等待全屏元素可点击并点击,替换成你测试有效的XPath
fullscreen_xpath = "//span[normalize-space(@class)='lh-solid']"
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, fullscreen_xpath))).click()
print("full screen")

time.sleep(5)
driver.quit()

额外提示

如果以上XPath仍无法定位,可通过浏览器开发者工具:

  1. 右键全屏元素选择「检查」
  2. 查看元素的title、data-*等自定义属性,或父/子元素的特征,进一步优化定位表达式
  3. 用开发者工具的「复制XPath」功能生成基础表达式,再调整为更健壮的写法

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:25:18