python-selenium -- iframe、滾動條、窗口切換定位方法詳解


一、frame框架里面的元素定位

  1.1 iframe定位 -- 先切換到iframe框架-定位-釋放iframe

 

 

 

定位到iframe 3種的方法

"""
Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
driver.switch_to.frame('frame_name')   #通過名字
driver.switch_to.frame(1)   #通過下標
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])   #通過WebElement對象來定位


""" 

 1 #切換到iframe
 2 driver.switch_to.frame("login_frame_qq")  3 
 4 #點擊賬號密碼登錄
 5 driver.find_element_by_xpath('//a[@id="switcher_plogin"]').click()  6 time.sleep(2)  7 #輸入賬號密碼
 8 
 9 #釋放iframe 回到主頁面
10 driver.switch_to.default_content()

 

二、頁面滾動條之后的元素定位及窗口切換

  2.1 元素拖動到可見區域-定位

  四個常見方法:  

   1)移動到元素element對象的“底端”與當前窗口的“底部”對齊:
       driver.execute_script("arguments[0].scrollIntoView(false);",element)

  2)移動到元素element對象的“頂端”與當前窗口的“頂部”對齊  :
       driver.execute_script("arguments[0].scrollIntoView();",element)

  3)移動到頁面底部:
        driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")

  4)移動到頁面頂部:
       driver.execute_script("window.scrollTo(document.body.scrollHeight,
     0)") 

如:
 1 from selenium import webdriver  2 import time  3 from selenium.webdriver.support.wait import WebDriverWait  4 from selenium.webdriver.support import expected_conditions as EC  5 from selenium.webdriver.common.by import By  6 
 7 driver = webdriver.Chrome()  8 driver.get("https://www.baidu.com/")  9 driver.maximize_window() 10 time.sleep(3) 11 
12 #定位百度搜索框
13 driver.find_element_by_id("kw").send_keys("python") 14 time.sleep(3) 15 driver.find_element_by_id("su").click() 16 time.sleep(5) 17 #找到這個元素
18 ele = driver.find_element_by_xpath('//a[text()="_百度百科"]') 19 #拖動元素到可見區域--scrollIntoView() 拉到頂部顯示,有可能會被導航欄遮擋,定位不到而報錯;scrollIntoView(false)可視區域底部對齊
20 driver.execute_script("arguments[0].scrollIntoView(false);",ele) 21 time.sleep(5)


  2.2 窗口切換   
  1)windows = driver.window_handles #獲取當前所有的窗口
  2)driver.switch_to.window(windows[-1]) #切換到最新打開的一個窗口
  3)driver.switch_to.window(windows[0]) #切換到第一個窗口
  4)driver.current_window_handle() #獲取當前窗口句柄

 1 #窗口切換
 2 #獲取當前所有句柄 --返回的是個列表
 3 windows = driver.window_handles  4 ele.click()  5 time.sleep(10)  6 
 7 #等待新窗口打開
 8 WebDriverWait(driver,10,0.5).until(EC.new_window_is_opened(windows))  9 #獲取當前所有句柄
10 windows = driver.window_handles 11 #切換到最后一個句柄 -- 根據返回的列表下標取值
12 driver.switch_to.window(windows[-1]) 13 #滑動到頁面最底部
14 driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") 15 driver.current_window_handle() 16 
17 time.sleep(5) 18 driver.quit()

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM