如何在Python中使用Selenium选择iframe?

2024-10-04 11:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

使用selenium python,我想选择一个iframe,其中包含以下信息:

<iframe title="Key to fetch simulation results" class="ltiLaunchFrame" name="ltiFrame-1548f8973dbf4d76840c56763e996767" src="/courses/course-v1:EPFL+SimNeuro2+2019_2/xblock/block-v1:EPFL+SimNeuro2+2019_2+type@lti_consumer+block@1548f8973dbf4d76840c56763e996767/handler/lti_launch_handler" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" allow="microphone *; camera *; midi *; geolocation *; encrypted-media *"></iframe>

我试着去做

webdriver.switch_to.frame("ltiFrame-1548f8973dbf4d76840c56763e996767")'

但是它说

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="ltiFrame-1548f8973dbf4d76840c56763e996767"]

但是我用的是正确的名字!我做错了什么


Tags: tokeyname信息truetitleseleniumlti
2条回答
//iframe[contains(@name, 'ltiFrame-') and @class='ltiLaunchFrame']

您可以使用上述xpath来定位iframe

代码:

wait = WebDriverWait(driver, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@name, 'ltiFrame-') and @class='ltiLaunchFrame']")))

导入:

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

此外,如果您想从框架中走出来,请使用以下代码:

driver.switch_to.default_content()

如果title属性值Key to fetch simulation results是唯一的,则应该这样做:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Key to fetch simulation results']")))

为了使用它,您必须导入

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

并初始化wait对象

wait = WebDriverWait(driver, 20)

相关问题 更多 >