frame标签有frameset、frame、iframe三种,frameset里的元素定位跟其他普通标签没有区别,而frame与iframe需要通过切换到frame里才能定位到里面的元素
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Chrome()
url = 'https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python'
browser.get(url)
# 通过id定位并切换到iframe中
browser.switch_to.frame('iframeResult')
# 其他方式
# driver.switch_to.frame(0) # 使用index来定位
# driver.switch_to.frame("myframe") # 使用name来定位
# driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) # 使用用WebElement对象来定位
try:
logo = browser.find_element_by_class_name('logo')
except NoSuchElementException:
print('NO LOGO')
# 从frame中切回主文档, 一步到位
browser.switch_to.default_content()
logo = browser.find_element_by_class_name('logo')
print(logo)
driver.switch_to.frame("myframe")
# 从子frame切回到父frame,如果当前已是主文档,则无效果
browser.switch_to.parent_frame()