zoukankan      html  css  js  c++  java
  • Python+Selenium--定位iframe中的对象

    场景

          在web 应用中经常会出现frame 嵌套的应用,假设页面上有A、B 两个frame,其中B 在A 内,那么定位B 中的内容则需要先到A,然后再到B。
          switch_to_frame 方法可以把当前定位的主体切换了frame 里。怎么理解这句话呢?我们可以从frame的实质去理解。frame 中实际上是嵌入了另一个页面,而webdriver 每次只能在一个页面识别,因此才需要用switch_to.frame 方法去获取frame 中嵌入的页面,对那个页面里的元素进行定位。
         下面的代码中frame.html 里有个id 为f1 的frame,而f1 中又嵌入了id 为f2 的frame,该frame 加载了百度的首页。

    代码

    iframe.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div >
    <h3>frame</h3>
    <iframe id="f1" src="inner.html" width="900" height="600"></iframe>
    </div>
    </body>
    </html>

     inner.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>inner</h3>
    <iframe id="f2" src="http://www.baidu.com" width="800" height="400">
    </iframe>
    </body>
    </html>

      

    主程序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    #!/usr/bin/env python
    # -*- codinfg:utf-8 -*-
    '''
    @author: Jeff LEE
    @file: iframe.py
    @time: 2020-01-08 17:23
    @desc:
    '''
    from selenium import webdriver
    import time,os
     
    driver = webdriver.Firefox()
     
    file_path ='file:///' + os.path.abspath('iframe.html')
    driver.get(file_path)
     
    driver.implicitly_wait(30)
     
    #先找到到ifrome1(id = f1)
    driver.switch_to_frame("f1")
    #再找到其下面的ifrome2(id =f2)
    driver.switch_to_frame("f2")
     
    driver.find_element_by_id("kw").send_keys("uniquefu")
    driver.find_element_by_id("su").click()
    time.sleep(2)
    driver.quit()
  • 相关阅读:
    php下的jsonp使用实例
    jquery ajax jsonp跨域调用实例代码
    js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)
    jsonp实现跨域访问
    jsonp调用实例
    Jsonp和java操作例子
    JSONP实例
    跨平台移动开发工具:PhoneGap与Titanium全方位比拼
    混合开发模式下主流移动开发平台分析
    企业移动信息化应用开发模式选型指南
  • 原文地址:https://www.cnblogs.com/chenlimei/p/12781389.html
Copyright © 2011-2022 走看看