switch_to.parent_frame()和switch_to_default_content()的帧数有所不同。它们在下面列出-
switch_to_parent_frame()
该方法用于出现在当前框架之外,然后我们可以访问该框架外部而不是该框架内部的元素。这样就切换了控制;外部可以是网页的其他框架或一部分。这样我们就可以脱离当前框架。
语法-
driver.switch_to.parent_frame();
switch_to_default_content()
此方法用于从所有帧中移出并在页面上切换焦点。一旦我们搬出,它将无法访问页面中框架内的元素。
语法-
driver.switch_to_default_content();
使用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()
使用switch_to_parent_frame()方法的代码实现。
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 parent frame name driver.switch_to.frame("frame-top") # to switch to frame with frame inside parent frame with name driver.switch_to.frame("frame-left") # to get the text inside the frame and print on console print(driver.find_element_by_xpath ("//*[text()='LEFT']").text) # to move out the current frame to the parent frame driver. switch_to_parent_frame() #to close the browser driver.quit()