Selenium之xpath绝对路径表示法

xpath写法:

          绝对路径:以/开始,逐个增加节点用/分割

          特点:不能跨级、类似css中的直接子元素选择器

          相对路径:用两个斜杠  //      如  //div//p//a

通配符:xpath也有通配符 * 

       比如  所有的节点    //div/*    选择div下面所有的直接子元素

根据属性和属性的值的选择  -----------  比如 id  、 class='xxx'等

       比如  //*[@style]    选择所有具有style属性的元素   -----  注意前面必须有个@

       比如  //p[@spec='len2']   选择所有具有spec值len2的元素   -----等价于-------    css中的p[speec='len2']

       比如  根据id选择   //div[@id='food']

       比如  根据class选择   //div[@class='cheese']

模糊的属性值定位元素:

       fn:contains(string1,string2)写法    -------   contains()   包含

              比如   //*[contains(@style, 'margin-top')]

       fn:starts-with(string1,string2)写法    -------- starts-with()    以什么开头

              比如   //*[starts-with(@style, 'margin-top')]

:nth-child(n)写法   -----  选择父元素下第几个子元素

       比如   #food :nth-child(2)  

:nth-of-type(n)写法   -------   选择属于父元素下第几个元素的每个元素

       比如  #food>p:nth-of-type(2)

子元素选择?:

       选择属于其父元素的第n个某个类型的子元素   

              如  //*[@id='food']/p[1]   等价于   #food>p:nth-of-type(1)

       选择属于其父元素的倒数第n个某个类型的子元素

              如  //span[last()-1]

                   //*[@id='food']/span[last()]

        还有像  :nth-last-child(n)

                         nth-last-of-type(n)

子元素选择:

        选择属于其父元素的第n个子元素(基于所有类型元素)

                    如://*[@id='food']/*[position()=2]

        支持其他的  比较操作符

                    如://*[@id='food']/*[position() < 3]

        选择属于其父元素的倒数第n个子元素

                    如://*[@id='food']/*[position()=last()-1]

组元素:

        在xpath中,用  |   来隔开,  如:  //p  |   //button

相邻兄弟选择器:

       比如:   //*[@id='food']/following-sibling::div    找当前元素相邻的元素  往下找

       比如:   //*[@id='food']/preceding-sinling::div    找当前元素相邻的元素怒  网上找

定位到上级元素:

       比如:  //div/..

                   //div//*[id='food']/..

xpath擅长的:

         选择父节点   ..符号

         position函数,  结合比较操作符

注意:如果在写代码时,driver.find_elements_by_xpath('.//p')     相对路径时,前面必须要加上点。

猜你喜欢

转载自www.cnblogs.com/peipei-Study/p/11970702.html
今日推荐