首页 > 解决方案 > I'm trying to switch frames in Selenium using Xpath, but haven't had any success so far

问题描述

I'm trying to switch frames in Selenium using an Xpath instead of using the name of the frame. The frame doesn't have a name so I figured I could just use the Xpath, but I'm not sure Selenium supports using an Xpath instead of a name.

This is the normal way to switch frames:

driver.switch_to.frame("WhateverFrame")

This is what I have tried:

driver.switch_to.frame(By.XPath("//*[@id='ui-id-1']/iframe"))

driver.find_frame_by_xpath("//*[@id='ui-id-43']/iframe")

Any suggestions as to how I should alter my code to get this to work?

标签: pythonselenium

解决方案


您可以使用不同的选项切换到框架。

driver.switch_to.frame('frame_name')
driver.switch_to.frame(frame_index)
driver.switch_to.frame(element)

因此,在您的情况下,您可以发送元素,如下所示。

driver.switch_to.frame(driver.find_element_by_xpath("//*[@id='ui-id-43']/iframe"))

如果您想转到第一个 iframe,您也可以执行以下操作。

driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])

推荐阅读