有時候,我們在用firepath(不會的請點這里)查看元素的XPath信息,發現沒有可以用來定位的id信息,這個時候我們就需要考慮用其他的可用的來定位元素。本文介紹如何通過元素節點中class name的值來定位頁面元素。還是以百度首頁,搜索輸入框定位舉例:
XPath截圖
相關腳本代碼如下:
# coding=utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(6)
driver.get("https://www.baidu.com")
try:
driver.find_element_by_class_name("s_ipt")
print ('test pass: element found by class name')
except Exception as e:
print ("Exception found", format(e))
driver.quit()
意見:很多情況下,class利用要比id多,如果class中出現了太長的字符,和可變化的數字,那么請回到用XPath定位方法。