在進行UI自動化測驗程序中,需要獲取元素的屬性時可以使用Selenium中提供的get_attribute()方法,
例如:獲取元素的文本內容:get_attribute(‘textContent’)
一、 使用方法
get_attribute()方法中指定不同的引數,可以獲取到相應的元素屬性,
例如:
- 獲取元素的文本內容:get_attribute(‘textContent’)
- 獲取元素的內部HTML:get_attribute('innerHTML')
- 獲取元素的外部HTML:get_attribute('outerHTML')
- 獲取元素的id:get_attribute('id')
- 獲取元素的鏈接:get_attribute('href')
我們以百度首頁為例,分別獲取不同的屬性來查看效果:

from selenium import webdriver
# 初始化瀏覽器
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.maximize_window()
# 百度首頁左上角導航欄
ele_1 = driver.find_element_by_id("s-top-left")
# 百度首頁左上角導航欄新聞
ele_2 = driver.find_element_by_xpath("//div[@id='s-top-left']/a[1]")
# 百度首頁左上角導航欄地圖
nele_3 = driver.find_element_by_xpath("//div[@id='s-top-left']/a[3]")
print('元素的內部HTML:', ele_1.get_attribute('innerHTML'))
print('元素的外部HTML:', ele_1.get_attribute('outerHTML'))
print('元素的文本內容:', ele_2.get_attribute('textContent'))
print('元素的id屬性:', ele_1.get_attribute('id'))
print('元素的鏈接:', nele_3.get_attribute('href'))
執行結果:
元素的內部HTML: 新聞
元素的外部HTML: <a href="http://news.baidu.com" target="_blank" >新聞</a>
元素的文本內容: 新聞
元素的id屬性: s-top-left
元素的鏈接: http://map.baidu.com/
二、實際應用

在進行UI自動化測驗時,需要獲取輸入框的默認文本,如上圖所示,但是輸入框元素不顯示默認文本資訊,使用element.text也不能獲取到,這里默認姓名是作為一個‘value’屬性隱藏起來了,所以需要使用get_attribute('value')去獲取,
driver.find_element_by_xpath("//input[@placeholder='請輸入入住人姓名']").get_attribute("value")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299333.html
標籤:其他
