使用 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()输出
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP