Skip to main content
 首页 » 编程设计

Python Selenium Webdriver之查找嵌套框架

2025年01月19日27dflying

我正在使用嵌套框架的 Intranet 工作,无法访问子框架。

HTML 源代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
	<head> 
		<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> 
		<title>VIS</title> 
		<link rel="shortcut icon" href="https://bbbbb/ma1/imagenes/iconos/favicon.ico"> 
	</head> 
	<frameset rows="51,*" frameborder="no" scrolling="no" border="0"> 
		<frame id="cabecera" name="cabecera" src="./blablabla.html" scrolling="no" border="3"> 
			<frameset id="frame2" name="frame2" cols="180,*,0" frameborder="no" border="1"> 
				<frame id="menu" name="menu" src="./blablabla_files/Menu.html" marginwidth="5" scrolling="auto" frameborder="3"> 
					<a href="/ma1/jsp/orD/queda.jsp" target="contenido">Buscar</a> 
				<frame id="contenido" name="contenido" src="./blablabla_files/saved_resource.html" marginwidth="5" marginheight="5"> 
					<html> 
						<head> 
							<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> 
							<title>BUSCAr</title> 
						</head> 
						<frameset name="principal" rows="220,*" frameborder="NO"> 
							 <frame name="Formulario" src="./BusquedaSimple.html" scrolling="AUTO" noresize="noresize"> 
								<input id="year" name="year" size="4" maxlength="4" value="" onchange="javascript:Orden();" onfocus="this.value='2018';this.select();" type="text"> 
							 <frame name="Busqueda" src="./saved_resource(2).html" scrolling="AUTO"> 
						</frameset> 
						<noframes> 
							&lt;body&gt; 
							&lt;p&gt;soporte a tramas.&lt;/p&gt; 
							&lt;/body&gt; 
						</noframes> 
					</html> 
				<frame name="frameblank" marginwidth="0" scrolling="no" src="./blablabla_files/saved_resource(1).html"> 
			</frameset> 
			<noframes> 
			  &lt;P&gt;Para ver esta página.&lt;/P&gt; 
			</noframes> 
	</frameset> 
</html>

我在框架“菜单”中找到按钮“Buscar”:

driver.switch_to_default_content() 
driver.switch_to_frame(driver.find_element_by_css_selector("html frameset frameset#frame2 frame#menu")) 
btn_buscar = driver.find_element_by_css_selector("#div_menu > table:nth-child(10) > tbody > tr > td:nth-child(2) > span > a") 
btn_buscar.click()

我试过这段代码来定位 frame="Formulario"中的输入 id="year":

driver.switch_to_default_content() 
try:       driver.switch_to_frame(driver.switch_to_frame(driver.find_element_by_css_selector("html frameset frameset#frame2 frame#contenido frameset#principal frame#Formulario"))) 
    print("Ok cabecera -> contenido") 
except: 
    print("cabecera not found")

或

driver.switch_to_frame(driver.switch_to_xpath("//*[@id='year"]"))

但它们不起作用。

你能帮帮我吗?

谢谢!

请您参考如下方法:

为了能够处理所需的 iframe 您需要随后切换到所有 祖先框架:

driver.switch_to.frame("cabecera") 
driver.switch_to.frame("menu") 
btn_buscar = driver.find_element_by_link_text("Buscar") 
btn_buscar.click() 

另请注意,Webdriver 实例没有 switch_to_xpath() 和 switch_to_frame() 等方法,switch_to_default_content() 方法已弃用,因此您最好使用switch_to.frame(), switch_to.default_content()