• 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()
  • 相关阅读:
    别人的代码
    ZOJ 1914 Arctic Network
    今日所得 2.22
    poj 2031 Building a Space Station
    POJ 1251 Jungle Roads
    优秀的开发者 vs. 糟糕的开发者
    有关读书求知的一些想法
    开发者拒绝写技术博客的常见理由
    写代码如坐禅:你是哪一类程序员?
    [C++] c++ new() 与new[]的区别
  • 原文地址:https://www.cnblogs.com/chenlimei/p/12781389.html
Copyright © 2020-2023  润新知