如何透過 Selenium 中的特定屬性在網頁元素中使用相對 xpath 定位其位置?
我們可以使用相對 xpath 透過特定屬性值來定位網頁元素。相對 xpath 從要定位的元素開始,而不是從根元素開始。
它以 // 符號開頭。它的優點是即使一個元素在 DOM 中被刪除或新增,特定元素的相對 xpath 也不會受到影響。要透過屬性獲取相對路徑,xpath 表示式為 //tagname[@attribute='value']。
讓我們藉助 alt 屬性識別一下頁面上下方框中的元素。
語法
l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")
示例
from selenium import webdriver #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://tutorialspoint.tw/about/about_careers.htm") #identify element with an attribute using xpath l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']") #get src attribute s = l.get_attribute('src') print('Src attribute value is: ') print(s) #browser quit driver.quit()
輸出
廣告