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

如何用Selenium访问嵌套IFRAME结构中的指定文本框

Selenium 访问嵌套Frames结构内文本框的问题

页面Frames结构

页面的Frameset结构如下:

<frameset border="0" framespacing="0" frameborder="0" rows="120,*"> 
<frame name="start_main" scrolling="no" noresize target="contents" src="start_main"> 
<frameset cols="139,*"> 
<frame name="start_sub" scrolling="no" target="main" src="start_sub"> 
<frame name="start_body" src="start_body"> 
</frameset> 
<noframes> 
<body> 
<p>This page uses frames, but your browser doesn't support them.</p> 
</body> 
</noframes> 
</frameset>  

目标文本框

需要操作的文本框位于start_body frame内,元素代码:

<input type="integer" name="part_num" size="14" style="font-size: 8pt" value=""> 

已尝试的代码

driver.switch_to.frame('start_body')
sleeptime = random.uniform(time_min, time_max)
time.sleep(sleeptime)
# enter the part number
part_num = "394914008"
# switch to the frame containing the input fields
driver.switch_to.frame('start_body')
ascen_field = driver.find_element(By.XPATH,"/html/body/div/center/form/table/tbody/tr[1]/td[2]/font/small/input")      
ascen_field.send_keys(inst_value);

问题分析与解决

  1. 重复切换frame错误:代码连续两次调用driver.switch_to.frame('start_body'),第一次切换后已处于该frame上下文,第二次切换会因当前上下文内无同名frame抛出异常,需删除重复切换的代码。
  2. 定位器稳定性差:绝对XPATH易受页面结构变动影响,建议改用元素的name属性定位,更简洁可靠。
  3. 等待方式不合理:time.sleep()属于固定等待,改用Selenium显式等待,可精准等待frame加载完成、元素可交互,避免页面加载慢导致的元素找不到问题。

修正后的代码示例

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待start_body frame加载完成并切换至该上下文
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it('start_body'))

# 等待目标文本框可交互后输入内容
part_num = "394914008"
ascen_field = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.NAME, "part_num"))
)
ascen_field.send_keys(part_num)

# 操作完成后若需回到主文档,执行以下代码
# driver.switch_to.default_content()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:52:24