Python+Selenium 自動化實現實例-定位frame中的元素


場景

處理frame需要用到2個方法,分別是switch_to_frame(name_or_id_or_frame_element)和switch_to_default_content()

如何理解這個switch_to_frame(name_or_id_or_frame_element)方法呢?可以簡單記憶一下,如果這個frame有name和id屬性那么就用這兩個屬性就好,如果沒有的話可以先用find_element_by_xxx方法找到這個frame元素,然后把這個元素傳進去,這也是可行的。

switch_to_frame方法把當前定位的主體切換了frame里。怎么理解這句話呢?我們可以從frame的實質去理解。frame中實際上是嵌入了另一個頁面,而webdriver每次只能在一個頁面識別,因此才需要用switch_to_frame方法去獲取frame中嵌入的頁面,對那個頁面里的元素進行定位。

switch_to_default_content方法的話則是從frame中嵌入的頁面里跳出,跳回到最外面的原始頁面中。

如果頁面上只有1個frame的話那么這一切都是很好理解的,但如果頁面上有多個frame,情況有稍微有點復雜了。

 

# -*- coding: utf-8 -*- 
from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep import os import selenium.webdriver.support.ui as ui if 'HTTP_PROXY'in os.environ: del os.environ['HTTP_PROXY'] dr = webdriver.Chrome() file_path = 'file:///' + os.path.abspath('frame.html') dr.get(file_path) # 先到f1再到f2
dr.switch_to_frame('f1') dr.switch_to_frame('f2') # 往f2中的百度關鍵字文本框中輸入內容
dr.find_element_by_id('kw').send_keys('watir-webdriver') # 直接跳出所有frame
dr.switch_to_default_content() # 再到f1
dr.switch_to_frame('f1') dr.find_element_by_link_text('click').click() sleep(2) dr.quit()

 


免責聲明!

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



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