import time from selenium import webdriver from selenium.webdriver import ChromeOptions from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as when class TestDemo: def test_01(self): service = Service(executable_path='chromedriver') with webdriver.Chrome(service=service) as browser: browser.implicitly_wait(5) browser.get("http://www.baidu.com") input_el = browser.find_element(By.XPATH, '//input[@id="kw"]') input_el.send_keys('柠檬班') # 点击百度一下 search_btn = browser.find_element(By.ID, 'su') search_btn.click() # 显性等待 # 1,等待器,设置倒计时 # 2,等待条件,出现 # 3,在超时前,如果等待条件出现了; 如果等待条件没出现,会报超时的错误 wait = WebDriverWait(browser, timeout=5) condition = when.element_to_be_clickable( (By.LINK_TEXT, 'lemon.ke.qq.com/') ) lemon_link = wait.until(condition) # lemon_link = browser.find_element(By.LINK_TEXT, 'lemon.ke.qq.com') # #WebDriverWait(browser, timeout=10).until(when.element_to_be_clickable((By.LINK_TEXT, 'lemon.ke.qq.com/'))) # 获取当前窗口 print(browser.current_window_handle) # lemon_link = browser.find_element(By.LINK_TEXT, 'lemon.ke.qq.com/') lemon_link.click() # 打印所有的窗口名称 ['窗口1', '窗口2'] print(browser.window_handles) # 有一个新页面生成 # 切换到新页面 browser.switch_to.window(browser.window_handles[-1]) print(browser.current_window_handle) # browser.find_element(By.CSS_SELECTOR, '.agency-content')
上面是普通的窗口切换,下面是iframe切换
写个简单的有iframe的页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>py44</title> </head> <body> <h2 id="hello">hello</h2> <iframe id="i" name="f" src="http://www.testingpai.com" width="800px" height="600px"></iframe> </body> </html>
切换到iframe
import time from selenium import webdriver from selenium.webdriver import ChromeOptions from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as when class TestDemo: def test_01(self): service = Service(executable_path='chromedriver_95.exe') with webdriver.Chrome(service=service) as browser: browser.implicitly_wait(5) browser.get("file:///D:/vip%E7%8F%AD%E7%BA%A7/py44/day36_%E7%AD%89%E5%BE%85%E5%92%8C%E5%88%87%E6%8D%A2/iframe_web.html") browser.find_element(By.ID, 'hello') # 必须要切换到iframe当中 iframe = browser.find_element(By.ID, 'i') browser.switch_to.frame(iframe) # iframe browser.find_element(By.XPATH, '//span[contains(text(), "排行榜")]')