selenium切换iframe
2020-07-06 本文已影响0人
Lydia1991
切换的条件:如果你要操作的元素,在iframe当中, 你才需要切换
页面元素(容器)-里面是一个HTML页面
iframe定位方式
driver.switch_to.frame()
index,下标
driver.switch_to.frame(3)
name属性:
driver.switch_to.frame("name属性的值")
webelement对象:
driver.switch_to.frame(driver.find_element_by_xpath('xpath表达式'))
嵌套的iframe
driver.switch_to.frame()
直接返回main页面
driver.switch_to.default_content()
切换到父级iframe
driver.switch_to.parent_frame()
举例说明:以登录腾讯课堂为例:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
# 实例化webdriver中的Chome对象
driver = webdriver.Chrome()
# 访问腾讯课堂
driver.get('https://ke.qq.com/')
# 查找登录按钮,设置等待条件
loc = (By.XPATH, '//div[@id="js-mod-entry-index"]//a[text()="登录"]')
# 找到找到登录的元素在进行下一步操作,查找时间上限为10秒
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
# 找到元素,并点击
driver.find_element(*loc).click()
time.sleep(3)
# 点击QQ登录,等待元素被找到进行下一步
loc = (By.XPATH, '//a[@class="js-btns-enter btns-enter btns-enter-qq"]')
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
driver.find_element_by_xpath('//a[@class="js-btns-enter btns-enter btns-enter-qq"]').click()
time.sleep(1)
# iframe切换方式一:通过下标、name属性、webelement对象进行切换
# 弹出一个iframe登录框,定位iframe框
driver.switch_to.frame('login_frame_qq')
# 使用显性等待
loc = (By.ID, 'switcher_plogin')
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
# 查找用账号密码登录元素
driver.find_element(*loc).click()
time.sleep(0.5)
# 输入账号
driver.find_element_by_id('u').send_keys("xxxx")
# 输入密码
driver.find_element_by_id('p').send_keys('xxxxx')
driver.find_element_by_id('login_button').click()
time.sleep(3)
# 退出
driver.quit()
方法二:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
# 创建一个Chrome对象
driver = webdriver.Chrome()
# 窗口最大化
driver.maximize_window()
# 访问腾讯课堂
driver.get('https://ke.qq.com/')
# 定位登录按钮,并点击操作,利用显示等待
loc = (By.ID, 'js_login')
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
driver.find_element_by_id('js_login').click()
# 定位QQ登录按钮,并点击操作,显示等待
loc = (By.XPATH, '//a[@class="js-btns-enter btns-enter btns-enter-qq"]')
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
driver.find_element(*loc).click()
time.sleep(1)
# iframe切换方式二:下标、name属性、webelement对象、元素定位元组四种
# iframe骚操作,EC条件中,frame_to_be_available_and_switch_to_it这个条件,说明iframe有效并切换到iframe中
# 切换到登录的iframe页面中
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe[@name="login_frame_qq"]')))
driver.find_element_by_id('switcher_plogin').click()
time.sleep(1)
# 定位输入框,输入账户名、密码
driver.find_element_by_id('u').send_keys('xxx')
driver.find_element_by_id('p').send_keys('xxx')
# 点击登录按钮
driver.find_element_by_id('login_button').click()
time.sleep(3)
# 关闭浏览器
driver.quit()