使用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.com/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.com/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()
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP