定位元素時常常會出現定位不到元素,這時候咱們須要觀察標籤的上下文,通常狀況下這些定位不到的元素存放在了frame或者放到窗口了,只要咱們切入進去就能夠很容易定位到元素。web
處理frame時主要使用到switch_to.frame()(切入frame也能夠些寫成switch_to_frame,不過這個已經用的不多了)和switch_to_default_content()兩個方法,一個主要是切入到iframe裏面,一個是切換到主文檔中,通常狀況這兩個要配合着用,切進去之後操做完成元素之後,就要在切回到主文檔,避免一些其餘的錯誤。測試
#-*- coding:utf-8 -*- '''126郵箱登錄''' import time import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class WANGYI(unittest.TestCase): def setUp(self): print('開始測試') self.username = 'yuhuan2006_2548' # 定義帳號 self.password = 'xxxxx' #定義密碼 self.driver = webdriver.Chrome() self.driver.maximize_window() self.base_url = "http://mail.126.com/" self.driver.get(self.base_url) def test_login(self): '''測試登錄126郵箱''' WebDriverWait(self.driver,10).until( EC.presence_of_element_located((By.ID, "x-URS-iframe"))) self.driver.switch_to.frame("x-URS-iframe") #切換進入frame 在這裏也能夠寫self.driver.switch_to.frame(self.driver.find_element_by_xpath('//*[@id="x-URS-iframe"]')),先定位元素 self.driver.find_element_by_name("email").send_keys(self.username) self.driver.find_element_by_name("password").send_keys(self.password) self.driver.find_element_by_id("dologin").click() WebDriverWait(self.driver,10).until( EC.presence_of_element_located((By.ID, "spnUid"))) #增長等待時間,判斷驗證信息元素是否顯示 verifyLoginSucceed = self.driver.find_element_by_xpath('//*[@id="spnUid"]').text self.assertIn(self.username,verifyLoginSucceed) #驗證是否登錄成功 def tearDown(self): self.driver.implicitly_wait(30) self.driver.quit() print('測試結束') if __name__ == '__main__': unittest.main()
正好有人問我126郵箱如何輸入帳號和密碼,開始他覺得是因爲Input標籤的屬性致使沒有辦法輸入帳號,後來正好有時間了,看了一下126郵箱的你過來,發現這裏正是用到了iframe切換,因此在這裏總結了一下frame,而且以126郵箱爲例子寫了一下。ui