在web应用中,前台网页的设计一般会用到iframe或者frame表单来潜逃页面的应用,例如在我们qq邮箱的登录页面。selenium webdriver只能定位当前页面中的元素,而一个页面通常会嵌套多个html文件,frame相当于独立的页面,因此在定位时对于不同的表单中的iframe或者frame是无法直接定位的。此时我们就需要用switch_to.frame()方法来切换frame来进行切换。
这里我们以qq邮箱来举例,首先用webdriver通过火狐浏览器打开qq邮箱页面,操作如下:
driver = webdriver.Firefox()
driver.get('https://mail.qq.com')
一、如果网页中源代码iframe有id或者name 属性时,
![8dd9204b971a6f517ab30757fec74ebd.png](https://i-blog.csdnimg.cn/blog_migrate/68885505a4de61b309faad2616d5b2e1.png)
![040eff2bac8f7e4a37ec93b20e398f37.png](https://i-blog.csdnimg.cn/blog_migrate/665951a800535343e7adfc3fffd38497.png)
![897c2bb02b3ba7f5342f839a5b3f2657.png](https://i-blog.csdnimg.cn/blog_migrate/83c0a2190d4570b8e74ae5110c88c2a4.png)
这是我们可以直接通过id或者name的属性值且属性值不带时间戳即不会发生变化时,可以先进入id为login_frame的frame,然后再执行driver.find_element_by_name("u"),driver.find_element_by_name("p")就可以登录进去改页面,然后再通过driver.switch_to.default_content()就可以切回主文档,代码实现如下:
![88103442ea7a4864213edc5f6448ca71.png](https://i-blog.csdnimg.cn/blog_migrate/2dbb501a5f8df6aa2145f982785150ef.png)
- 如果网页中没有id或name 属性时,则需要先用路径by_xpath去定位iframe,然后再切换到iframe中去。路径方法用代码实现如下:
![5b69a81325910b3a4b83f5cfb507631c.png](https://i-blog.csdnimg.cn/blog_migrate/07d3e1cee1d01df4b1d462f4958066f8.png)
注意如果源代码中有多个iframe时,则需要通过driver.switch_to.frame()一层一层的切入。