我们可以处理Selenium中的帧。框架是一个HTML元素,用于将文档保留在页面中的另一个文档中。HTML具有<frame>或<iframe>标记,用于将框架嵌入文档中。
Selenium中有多个API可用于框架。它们在下面列出-
switch_to_frame(id)
此方法用于在帧ID的帮助下识别帧,然后将焦点切换到该特定帧。
语法-
driver.switch_to_frame("frameid"), where frameid is the id attribute present under the frame/iframe tag in HTML.switch_to_frame(名称)
此方法用于在帧名称的帮助下识别帧,然后将焦点切换到该特定帧。
语法-
driver.switch_to_frame("framename"), where framename is the name attribute present under the frame/iframe tag in HTML.switch_to_frame(webelement)
此方法用于借助框架Web元素识别框架,然后将焦点切换到该特定框架。
语法-
driver.switch_to_frame("frameclassname"), where frameclassname is the name of class attribute present under the frame/iframe tag in HTML.switch_to_parent_frame()
该方法用于出现在当前框架之外,然后我们可以访问该框架之外而不是该框架内部的元素。
switch_to_default_content()
此方法用于从所有框架中移出并在页面上切换焦点。一旦我们搬出,它将无法访问页面中框架内的元素。
带框架的代码实现。
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# to switch to frame with frame name
driver.switch_to.frame("frame-bottom")
# to get the text inside the frame and print on console
print(driver.find_element_by_xpath ("//*[text()='BOTTOM']").text)
# to move out the current frame to the page level
driver.switch_to.default_content()
#to close the browser
driver.quit()