python selenium 定位iframe(多層架構)__python

來源:互聯網
上載者:User

在 web 應用中經常會出現 iframe 嵌套的應用,假設頁面上有 A、B 兩個 iframe,其中 B 在 A 內,那麼定位 B 中的內容則需要先到 A,然後再到 B。

iframe 中實際上是嵌入了另一個頁面,而 webdriver 每次只能在一個頁面識別,因此需要用 switch_to.frame 方法去擷取 iframe 中嵌入的頁面,對那個頁面裡的元素進行定位。

如果iframe裡有id或者name,使用switch_to_frame()可以很方便的定位到,如

例1:

# 先找到到 ifrome1(id = f1)

driver.switch_to_frame("f1")

# 再找到其下面的 ifrome2(id =f2)

driver.switch_to_frame("f2")

# 下面就可以正常的操作元素了

driver.find_element_by_id("xx").click()

註:切到frame中之後,我們便不能繼續操作主架構的元素,這時如果想操作主架構內容,則需切回主文件(最上級文檔);若使用後需要再次對iframe定位需要重新從初始化的frame進行定位。

br.switch_to.default_content()

但有時會碰到iframe裡沒有id或者那麼的情況,這就需要其他辦法去定位了,如:

例2:


方法一:從頂層開始定位,相對比較費勁。

text1 = browser.find_element_by_class_name("bodybg")

text2 = text1.find_element_by_xpath("div[@class='Lean_overlay']/div[2]")

# 輸入iframe裡的src內容,確認已經定位到iframe

# text3 = text2.find_element_by_tag_name("iframe").get_attribute("src")

# print text3

text = text2.find_element_by_tag_name("iframe")

browser.switch_to.frame(text)

方法二:定位到上一次,然後再定位到iframe。

#找出所有class_name=qh-login的上一層元素

text1 = browser.find_elements_by_class_name("qh-login")

for text in text1:

if text.get_attribute("id") == "idname":

print text.get_attribute("class")

text2 = text.find_element_by_tag_name("iframe").get_attribute("src")

else:

text2 = str("定位失敗了")

---------------------------------------------------------------------------------------------------------------------------------

有可能嵌套的不是架構,而是視窗,還有針對視窗的方法:switch_to_window 

用法與switch_to_frame 相同: 

driver.switch_to_window("windowName")

有的頁面鑲嵌的是frame:

用法與switch_to_frame相同:

driver.switch_to.frame("id||name")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.