selenium之By.cssSelector与By.xpath的区别

阅读更多
1、搜索路径中间的某个节点所在层级有多个该dom节点时,xpath和cssSelector会在多个节点中均搜索后续的节点,如测试1.
2、搜索路径最后一个节点下仍包含该类型的dom节点时,cssSelector会将包含的同名节点也搜索出来,xpath则不会继续向下搜索,只打印搜索路径中的最后一个dom节点,如测试2.
3、查找第几个子节点
   xpath:div[2],查找到父节点下的所有div节点后,取第二个div返回
   cssSelector:div:nth-child(2),查找父节点下的第2个节点,如果该节点是div,则返回否则找不到元素
                div:first-child,div是父节点下的第一个节点,则返回该div元素
                div:last-child,div是父节点下的最后一个节点,则返回该div元素
详见测试3.

测试1:
dom节点:

xpath测试代码:
List eless = driver.findElements(By.xpath("//div[@class='detail-time-picker']/div/span"));
for(int i=0;i 
 
结果:
the list classvalue:sfi sfi-chevron-up
the list tagname:span
the list classvalue:sfi sfi-chevron-down
the list tagname:span

cssSelector测试代码:
List eless = driver.findElements(By.cssSelector("div.detail-time-picker div span"));
for(int i=0;i 
 
结果:
the list classvalue:sfi sfi-chevron-up
the list tagname:span
the list classvalue:sfi sfi-chevron-down
the list tagname:span

测试2:
dom节点:

xpath测试代码:
List eless = driver.findElements(By.xpath("//div[@class='detail-date-picker']/div"));
for(int i=0;i 
 
结果:
the list classvalue:datepicker datepicker-inline
the list tagname:div

cssSelector测试代码:
List eless = driver.findElements(By.cssSelector("div.detail-date-picker div"));
for(int i=0;i 
 
测试结果:
the list classvalue:datepicker datepicker-inline
the list tagname:div
the list classvalue:datepicker-days
the list tagname:div
the list classvalue:datepicker-months
the list tagname:div
the list classvalue:datepicker-years
the list tagname:div


测试3:
dom节点:

this is a test text.

hello,this is h5

pppppppp

this is a test text.

hello,this is h5
second div

xpath测试代码:
List ele = driver.findElements(By.xpath("//div[@id='test']/div/dl[1]"));
System.out.println("number is:"+ele.size());
for(int i=0;i 
 
结果:
number is:2
第0个元素的class值为firstdl
第1个元素的class值为dl1

cssSelector测试代码:
List ele = driver.findElements(By.cssSelector("div#test div dl:nth-child(3)"));
System.out.println("number is:"+ele.size());
for(int i=0;i 
 
结果:
number is:2
第0个元素的class值为firstdl
第1个元素的class值为dl2

你可能感兴趣的:(xpath,cssSelector)