如何在 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.com/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.com/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.com/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()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP