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)
    
  • 相关阅读:
    列表与数组 Perl入门第三章
    北京地区-医类汇总
    via/route blockage/size blockage/wire/pin guide/pin blockage/partition
    dbGet(三)
    dbGet(二.一)hinst
    微服务是什么?
    Docker入门 四 Swarms集群
    Docker入门 三 用服务来扩展和负载均衡你的应用
    Linux2.2路径、删除目录及文件
    Linux2.1系统目录结构、ls、文件类型、alias
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/13041074.html
Copyright © 2011-2022 走看看