如何在 Selenium 中使用 Python 中的正則表示式?


藉助正則表示式,我們可以透過部分匹配其屬性來識別元素。在 xpath 中,有多種方法可以實現此目的。它們如下所列 −

  • 使用 contains() 方法。這意味著字串包含我們給定的文字。

語法

driver.find_element_by_xpath("//input[contains(@name,'sel')]")

它將搜尋包含包含 'sel' 文字的 'name' 屬性的 input 標籤。

  • 使用 starts-with() 方法。這意味著字串以我們給定的文字開頭。

語法

driver.find_element_by_xpath("//input[starts-with (@name,'Tut')]")

它將搜尋包含以 'Tut' 文字開頭的 'name' 屬性的 input 標籤。

  • 使用 ends-with() 方法。這意味著字串以我們給定的文字結束。

語法

driver.find_element_by_xpath("//input[ends-with (@name,'nium')]")

它將搜尋包含以 'nium' 文字結尾的 'name' 屬性的 input 標籤。

示例

使用 contains() 的程式碼實現

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 contains() in xpath
driver.find_element_by_xpath("//input[contains(@id,'sc-i')]").
send_keys("Selenium")
#to close the browser
driver.close()

使用 starts-with() 的程式碼實現

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 starts-with() in xpath
driver.find_element_by_xpath("//input[starts-with(@id,'gsc')]").
send_keys("Selenium")
#to close the browser
driver.close()

使用 ends-with() 的程式碼實現

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 ends-with() in xpath
driver.find_element_by_xpath("//input[ends-with(@id,'id1')]").
send_keys("Selenium")
#to close the browser
driver.close()

更新日期:2020-07-29

7 千次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告