前面介紹了元素定位的八大方法,今天在來介紹一種元素定位方法find_element方法
find_element
find_element屬於定位元素中的另一種方法,包含了常用的定位方法,使用的時候可能和其他的使用方法不一樣,先看源碼
源碼:
def find_element(self, by=By.ID, value=None): """ 根據策略和定位器找到給定的元素。 :使用方法: element = driver.find_element(By.ID, 'foo') :rtype: WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value']
源碼中包含了我們的使用方法,但是我們正常去使用的時候會報錯,因為找不到By模塊,所以我們首先要導入By模塊。
# 導入By模塊 from selenium.webdriver.common.by import By
使用方法:
# driver.find_element(By.定位方法,‘元素信息’) driver.find_element(By.ID, 'foo')
使用中的定位方法和普通的定位方法是一致的。
# coding:utf-8 from selenium import webdriver from selenium.webdriver.common.by import By # 選擇瀏覽器 driver = webdriver.Chrome() # 進入百度網站 driver.get('https://www.baidu.com') # 通過find_element定位輸入框 driver.find_element(By.ID,'kw').send_keys('python')
效果動態圖:
PS:最近安靜剛換了工作,更新博客可能偶爾更新了,但是學習也要每天2小時~