如何在 Python 中使用 Selenium 中 CSS 中的正則表示式?
藉助正則表示式,我們可以透過部分匹配其屬性來識別元素。在 css 中,有多種方法可實現此目的。它們列在下面 −
使用萬用字元 *。這意味著字串包含我們給定的文字。
語法−
driver.find_element_by_css_selector("input[name*='sel']")它將搜尋包含包含 'sel' 文字的 'name' 屬性的輸入標籤。
使用萬用字元 ^。這意味著字串以我們給定的文字開頭。
語法−
driver.find_element_by_css_selector("input[name^='Tut']")它將搜尋包含以 'Tut' 文字開頭的 'name' 屬性的輸入標籤。
使用萬用字元 $。這意味著字串以我們給定的文字結尾。
語法−
driver.find_element_by_css_selector("input[name$='nium']")它將搜尋包含以 'nium' 文字結尾的 'name' 屬性的輸入標籤。
示例
CSS 中使用 * 萬用字元的程式碼實現。
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 * 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
#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 ^ 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
#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 $ in css selector
driver. find_element_by_css_selector("input[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