zoukankan      html  css  js  c++  java
  • iframe+windows切换

    iframe+windows切换

    iframe切换

    如果一个元素无法定位到,那么最大的可能时定位的元素属性在iframe框架中,iframe对象代表一个HTML的内联框架,在HTML中iframe每出现一次,一个iframe对象就被创建。

    一、iframe切入

    iframe存在id属性

    例:

    #!/usr/bin/python3
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    import time
    
    chrome = webdriver.Chrome()
    chrome.maximize_window()
    chrome.get('https://music.163.com/')
    
    chrome.switch_to_frame('g_iframe') #跳到id='g_iframe'的iframe中
    # chrome.find_element_by_xpath('//*[@id="discover-module"]/div[1]/div/div/div[1]/ul/li[1]/div/a').click()
    chrome.find_element_by_xpath('//*[@id="discover-module"]//*[@title="Uzi退役:江湖路远,我们有缘再见" and @class="msk"]').click()
    time.sleep(10)
    

    iframe不存在id属性

    当iframe不存在id属性时,需要先通过xpath或css等其它手段定位到iframe后,再使用switch_to.frame('定位到的iframe')

    #!/usr/bin/python3
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    import time
    
    chrome = webdriver.Chrome()
    chrome.maximize_window()
    chrome.get('https://music.163.com/')
    
    iframe1 = chrome.find_element_by_xpath('//*[@class="g-iframe" and @scrolling="auto"]') #假设此iframe没有id属性
    chrome.switch_to.frame(iframe1)     #切入iframe
    
    chrome.find_element_by_xpath('//*[@id="discover-module"]//*[@title="Uzi退役:江湖路远,我们有缘再见" and @class="msk"]').click()
    time.sleep(10)
    
    

    二、iframe切出

    切到最外层

    driver.switch_to_default_content()
    

    windows(窗口)切换

    #获取当前窗口句柄
    now_handle = driver.current_window_handle
    
    #窗口切换
    driver.switch_to_window(now_handle)
    
    #获取所有页面的句柄
    handles = driver.window_handles
    
    #handles是个列表可以循环
    for handle in handles:
            driver.switch_to_window(handle)
    
    #!/usr/bin/python3
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    import time
    
    chrome = webdriver.Chrome()
    chrome.maximize_window()
    chrome.get('https://mail.sina.com.cn/')
    now_handle = chrome.current_window_handle
    chrome.find_element_by_link_text('注册').click()
    time.sleep(5)
    handles = chrome.window_handles
    for handle in handles:
            chrome.switch_to_window(handle)
    
    chrome.switch_to_window(now_handle)
    
    time.sleep(5)
    
  • 相关阅读:
    基于51单片机数码管显示经ADC0808转化1K电位器分压5V模拟量为数字量的项目工程
    基于51单片机数码管显示经ADC0808转化1K电位器分压5V模拟量为0V-5V数字量的项目工程
    浅谈移动端过长文本溢出显示省略号的实现方案
    浅谈自动化测试
    Tomcat 优雅关闭之路
    InnoDB 事务加锁分析
    Tomcat 9.0.26 高并发场景下DeadLock问题排查与修复
    Kotlin 协程真的比 Java 线程更高效吗?
    Spark 数据倾斜及其解决方案
    大数据平台架构设计探究
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/13041074.html
Copyright © 2011-2022 走看看