定位元素時經常會出現定位不到元素,這時候我們需要觀察標簽的上下文,一般情況下這些定位不到的元素存放在了frame或者放到窗口了,只要我們切入進去就可以很容易定位到元素。
處理frame時主要使用到switch_to.frame()(切入frame也可以些寫成switch_to_frame,不過這個已經用的很少了)和switch_to_default_content()兩個方法,一個主要是切入到iframe里面,一個是切換到主文檔中,一般情況這兩個要配合着用,切進去以后操作完成元素以后,就要在切回到主文檔,避免一些其他的錯誤。
- switch_to.frame() #如果frame 中有name和id屬性就直接使用id或者name進行定位,如果沒有id和name屬性,可以通過find_element_by_xpath(或者其他定位)方法定位到這個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郵箱為例子寫了一下。
