Selenium 中 switch_to_default_content() 方法和 switch_to.parent_frame() 方法之間有什麼區別?
幀中的 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()
廣告