如何在 CSS 定位器中使用正则表达式?


我们可以在 CSS 定位器中使用正则表达式。我们可以通过使用正则表达式部分匹配它们的属性来识别元素。在 CSS 中,有多种方法可以实现这一点。它们列在下面 -

  • 使用通配符 *。这意味着字符串包含我们给定的文本。

    语法 - driver.find_element_by_css_selector("input[name*='sel']")

    它将搜索包含包含“sel”文本的“name”属性的 input 标签。

  • 使用通配符 ^。这意味着字符串以我们给定的文本开头。

    语法 - driver.find_element_by_css_selector("input[name^='Tut']")

    它将搜索包含以“Tut”文本开头的“name”属性的 input 标签。

  • 使用通配符 $。这意味着字符串以我们给定的文本结尾。

    语法 - driver.find_element_by_css_selector("input[name$='nium']")

    它将搜索包含以“nium”文本结尾的“name”属性的 input 标签。

示例

使用 * 通配符在 css 中实现代码。

from selenium import webdriver
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 * in css selector
driver. find_element_by_css_selector("input[id*='sc-i']").
send_keys("Selenium")
#to close the browser
driver.close()

示例

使用 ^ 通配符在 css 中实现代码。

from selenium import webdriver
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 ^ in css selector
driver. find_element_by_css_selector("input[id^='gsc']").
send_keys("Selenium")
#to close the browser
driver.close()

示例

使用 $ 通配符在 css 中实现代码。

from selenium import webdriver
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 $ in css selector
driver. find_element_by_css_selector("input[id$='id1']").
send_keys("Selenium")
#to close the browser
driver.close()

更新于: 2021-11-19

4K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.