如何使用 Python 中的 Selenium 來透過 xpath 識別第 n 個元素?


構建自定義 xpath 的方法多種多樣。如果我們需要識別第 n 個元素,我們可以透過下面列出的方法來實現。

  • xpath 中的 position() 方法。

    假設一個頁面中有兩個具有相同 xpath 的編輯框,我們想要識別第一個元素,那麼我們需要新增 position()=1。

語法

driver.find_element_by_xpath("//input[@type='text'][position()=1]")
  • 用方括號加上大括號來表示索引。

    假設我們需要訪問表中的第三行,並且該行的自定義 xpath 應用 [3] 表示式表示

語法

driver.find_element_by_xpath("//table/tbody/tr[2]/td[2]")

示例

使用 position() 的程式碼實現

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/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of position()
driver.find_element_by_xpath("//input[@type='text'][position()=1]").
send_keys("Selenium")
#to close the browser
driver.close()

使用索引的程式碼實現

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/plsql/plsql_basic_syntax.htm")
#to refresh the browser
driver.refresh()
# printing the first data in the row 2 of table with index
print(driver.find_element_by_xpath("//table/tbody/tr[2]/td[1]").text)
#to close the browser
driver.close()

上次更新: 2020-07-29

4K+ 次瀏覽

職業生涯起航

完成本課程獲取認證

開始學習
廣告