如何使用 Python 在 Selenium 中處理框架?


我們可以使用 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(name)

    此方法用於使用框架名稱識別框架,然後將焦點切換到該特定框架。

語法 -

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()

更新於: 2020-07-29

9K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告