Python+Selenium 自动化实现实例-定位frame中的元素

场景

处理frame需要用到2个方法,分别是switch_to_frame(name_or_id_or_frame_element)和switch_to_default_content()

如何理解这个switch_to_frame(name_or_id_or_frame_element)方法呢?可以简单记忆一下,如果这个frame有name和id属性那么就用这两个属性就好,如果没有的话可以先用find_element_by_xxx方法找到这个frame元素,然后把这个元素传进去,这也是可行的。

switch_to_frame方法把当前定位的主体切换了frame里。怎么理解这句话呢?我们可以从frame的实质去理解。frame中实际上是嵌入了另一个页面,而webdriver每次只能在一个页面识别,因此才需要用switch_to_frame方法去获取frame中嵌入的页面,对那个页面里的元素进行定位。

switch_to_default_content方法的话则是从frame中嵌入的页面里跳出,跳回到最外面的原始页面中。

如果页面上只有1个frame的话那么这一切都是很好理解的,但如果页面上有多个frame,情况有稍微有点复杂了。

 

# -*- coding: utf-8 -*- 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
import os
import selenium.webdriver.support.ui as ui
if 'HTTP_PROXY'in os.environ: del os.environ['HTTP_PROXY']

dr = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('frame.html')

dr.get(file_path)

# 先到f1再到f2
dr.switch_to_frame('f1')
dr.switch_to_frame('f2')

# 往f2中的百度关键字文本框中输入内容
dr.find_element_by_id('kw').send_keys('watir-webdriver')

# 直接跳出所有frame
dr.switch_to_default_content()

# 再到f1
dr.switch_to_frame('f1')
dr.find_element_by_link_text('click').click()

sleep(2)
dr.quit()

 

posted @ 2017-04-05 10:57  ForcePush  阅读(6619)  评论(0编辑  收藏  举报