使用Python的Selenium中,XPath和CSS選擇器之間有什麼區別?
XPath和CSS選擇器是Selenium中最常用的定位器之一。儘管還有其他定位器,如id、name、classname、tagname和link text等等,但在沒有唯一屬性可用於識別元素時,XPath和CSS選擇器就派上用場了。
XPath和CSS選擇器之間存在一些差異,列舉如下:
XPath允許雙向遍歷,這意味著可以從父節點到子節點,也可以從子節點到父節點進行遍歷。CSS只允許單向遍歷,這意味著只能從父節點到子節點進行遍歷。
XPath在效能和速度方面較慢。CSS的效能和速度優於XPath。
XPath可以透過text()函式利用螢幕上可見的文字進行識別。CSS沒有此功能。
可以使用id和class屬性直接建立自定義CSS。對於id,CSS表示式由#後跟id表示[#<
>]。對於class,CSS表示式由.後跟class表示[.< >]。XPath沒有這樣的功能。 XPath表示式表示為[//tagname[@attribute = 'value']]。CSS表示式表示為[tagname[attribute = 'value']]。
XPath有兩種型別:絕對路徑和相對路徑。但是CSS沒有這種型別。
示例
使用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 css driver. find_element_by_css_selector("input[class='gsc-input']"). send_keys("Selenium") #to close the browser driver.close()
使用XPath的程式碼實現
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 xpath driver. find_element_by_xpath("//input[@class='gsc-input']"). send_keys("Selenium") #to close the browser driver.close()
廣告