使用 Python 和 Selenium 選擇 iframe


我們可以使用 Selenium webdriver 來選擇 iframe。iframe 在 html 文件中以 <iframe> 標記標識。iframe 是一個包含元素的 html 文件,該元素駐留在另一個 html 文件中。

讓我們一起看一個框架的 html 文件。

以下方法有助於在 iframe 之間切換:

  • switch_to.frame(args) - 將幀索引作為方法的引數。iframe 的起始索引為 0。

    語法:

    driver.switch_to.frame(0),切換到第一個 iframe。

  • switch_to.frame(args) - 將幀名稱或 ID 作為方法的引數。

    語法:

    driver.switch_to.frame("nm"),切換到具有名稱 nm 的 iframe。

  • switch_to.frame(args) - 將幀 webelement 作為方法的引數。

    語法:

    driver.switch_to.frame(f),切換到具有 webelement f 的 iframe。

  • switch_to.default_content() – 從 iframe 切換到父頁面。

    語法:

    driver.switch_to.default_content()

示例

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.get("https://the-internet.herokuapp.com")
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# switch to frame with name
driver.switch_to.frame("frame-bottom")
# identify element and get text method
s = driver.find_element_by_xpath("//body").text
print ("Test inside frame: " + s)
# move out of frame to parent page
driver.switch_to.default_content()
driver.quit()

輸出

更新時間:2020 年 9 月 18 日

5000+ 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告