• 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)
    
  • 相关阅读:
    汉字机内码的特点
    while(~scanf(..))的用法
    【C语言】八进制转十进制
    【C语言】按字典顺序排序
    【C语言】矩阵相乘
    【C语言】魔方阵
    【C语言】统计候选人的得票数
    【C语言】对输入的字符串中C关键词的查找统计
    20201231《信息安全导论》第十二周学习总结
    20201231《信息安全导论》第十一周学习总结
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/13041074.html
Copyright © 2020-2023  润新知