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

为何使用Python的Selenium无法找到播放按钮元素?

问题原因与解决方法

你的问题核心在于播放按钮位于iframe内部,而Selenium默认只会在主页面的DOM中查找元素,无法直接访问iframe内的元素。

解决步骤

  1. 定位并切换到包含播放按钮的iframe上下文
  2. 再查找并操作目标播放按钮

修改后的代码示例

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

browser = webdriver.Chrome()
browser.get("https://www.bbc.co.uk/sounds/play/live:bbc_radio_fourfm")

# 等待目标iframe加载完成并切换到该iframe
# 若页面存在多个iframe,可通过src属性等更精准的方式定位
iframe = WebDriverWait(browser, 30).until(
    EC.presence_of_element_located((By.TAG_NAME, "iframe"))
)
browser.switch_to.frame(iframe)

# 现在可以正常定位到播放按钮
playButton = WebDriverWait(browser, 30).until(
    EC.visibility_of_element_located((By.ID, "p_audioui_playpause"))
)
playButton.click()

# 若后续需要操作主页面元素,需切回默认上下文
# browser.switch_to.default_content()

# 延时查看效果后关闭浏览器
time.sleep(10)
browser.close()

补充说明

  • 若页面存在多个iframe,建议通过src属性、class名等唯一标识定位目标iframe,避免切换错误的上下文
  • 切换到iframe后,所有元素查找操作都会在该iframe的DOM中执行,完成操作后可通过switch_to.default_content()切回主页面上下文

内容的提问来源于stack exchange,提问作者Drew S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:24:58