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)
posted @ 2020-06-04 00:33  静心&得意  阅读(317)  评论(0编辑  收藏  举报