zoukankan      html  css  js  c++  java
  • webdriver19-witchto方法

    element = driver.switch_to.active_element
    alert = driver.switch_to.alert
    driver.switch_to.default_content()

      切到frame中之后,我们便不能继续操作主文档的元素,这时如果想操作主文档内容,则需切回主文档。

    
    
      driver.switch_to.default_content()# 跳出frame

    driver.switch_to.frame('frame_name')
    driver.switch_to.frame(1)

     #根据标签为frame找到多个frame,然后取第一个

    driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])

      怎么切到frame中(switch_to.frame())

      selenium提供了switch_to.frame()方法来切换frame

      switch_to.frame(reference)

      不得不提到switch_to_frame(),很多人在这样写的时候会发现,这句话被划上了删除线,原因是这个方法已经out了,之后很有可能会不支持,建议的写法是switch_to.frame()

      reference是传入的参数,用来定位frame,可以传入id、name、index以及selenium的WebElement对象,假设有如下HTML代码 index.html:

      <html lang="en">
      <head>
          <title>FrameTest</title>
      </head>
      <body>
      <iframe src="a.html" id="frame1" name="myframe"></iframe>
      </body>
      </html>

      想要定位其中的iframe并切进去,可以通过如下代码:

      from selenium import webdriver
      driver = webdriver.Firefox()
      driver.switch_to.frame(0)  # 1.用frame的index来定位,第一个是0
      # driver.switch_to.frame("frame1")  # 2.用id来定位
      # driver.switch_to.frame("myframe")  # 3.用name来定位
      # driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))  # 4.用WebElement对象来定位
    # 4.用WebElement对象来定位

    通常采用id和name就能够解决绝大多数问题。但有时候frame并无这两项属性,则可以用index和WebElement来定位:

    • index从0开始,传入整型参数即判定为用index定位,传入str参数则判定为用id/name定位
    • WebElement对象,即用find_element系列方法所取得的对象,我们可以用tag_name、xpath等来定位frame对象

    举个栗子:

    <iframe src="myframetest.html" />

    用xpath定位,传入WebElement对象:

    driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'myframe')]")

    driver.switch_to.parent_frame()

      有时候我们会遇到嵌套的frame,如下:

      <html>
          <iframe id="frame1">
              <iframe id="frame2" / >
          </iframe>
      </html>

      1.从主文档切到frame2,一层层切进去

      driver.switch_to.frame("frame1")
      driver.switch_to.frame("frame2")

      2.从frame2再切回frame1,这里selenium给我们提供了一个方法能够从子frame切回到父frame,而不用我们切回主文档再切进来。

      driver.switch_to.parent_frame()  # 如果当前已是主文档,则无效果

      有了parent_frame()这个相当于后退的方法,我们可以随意切换不同的frame,随意的跳来跳去了。

      所以只要善用以下三个方法,遇到frame分分钟搞定:

      driver.switch_to.frame(reference)
      driver.switch_to.parent_frame()
      driver.switch_to.default_content()

     driver.switch_to.window('main')

  • 相关阅读:
    Pymongo
    asp.net mvc4 使用java异步提交form表单时出现[object object] has no method ajaxSubmit
    C# Activator.CreateInstance()
    GridView中某一列值的总和(web)
    02.[WPF]如何固定窗口的大小
    01.WPF中制作无边框窗体
    C#.net时间戳转换
    org.springframework.beans.factory.BeanCreationException: 求教育!
    log4Net配置详解
    SQL语句-创建索引
  • 原文地址:https://www.cnblogs.com/ayichengxuyuan8899/p/10426895.html
Copyright © 2011-2022 走看看