您將如何使用 Python 中的 xpath 在 Selenium 中從子節點導航到父節點?


利用 xpath,我們可以在 DOM 中從其子節點識別父節點。在某些情況下,html 中的父節點具有動態屬性,而子節點具有一些可用於識別的唯一靜態屬性。

透過聯合使用相對 xpath 和父 xpath 軸。方法可達成此目的。

語法 

driver. find_element_by_xpath("//input[@id='job']/parent::div")

示例

子節點到父節點遍歷的程式碼實現。

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.tw/tutor_connect/index.php")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of xpath parent
atb=driver.find_element_by_xpath ("//input[@id='txtSearchText']/parent::div")
#prints the class attribute value in console
val = atb.get_attribute("class")
print(val)
driver.close()

更新時間: 2020-07-29

11K+ 次閱讀

開啟您的 職業生涯

完成課程認證

入門
廣告