selenium中Xpath定位元素

370 阅读1分钟

基本语法:

element=wd.find_element(By.XPATH,'/html')

绝对路径选择:

elements = driver.find_elements(By.XPATH, "/html/body/div")

相对路径选择:

所有的 div 元素里面的 所有的 p 元素

elements = driver.find_elements(By.XPATH, "//div//p")

通配符 *

选择所有div节点的所有直接子节点

elements = driver.find_elements(By.XPATH, "//div/*")

根据属性选择

选择属性为class='single_choice'的所有select元素

//select[@class='single_choice']

属性值包含字符串

//*[contains(@style,'color')]

属性值以字符串开头

//*[starts-with(@style,'color')]

属性值以字符串结尾

//*[ends-with(@style,'color')]`

按次序选择

选择 p类型第2个的子元素

//p[2]

p类型倒数第1个子元素

//p[last()]

范围选择

选取option类型第1到2个子元素

//option[position()<=2]

组选择,父节点,兄弟节点

组选择

选所有的option元素 和所有的 h4 元素

//option | //h4

父节点

某个元素的父节点用 /.. 表示

要选择 id 为 china 的节点的父节点

//*[@id='china']/..

兄弟节点

后续兄弟节点

following-sibling::

选择 class 为 single_choice 的元素的所有后续兄弟节点

//*[@class='single_choice']/following-sibling::*

前驱兄弟节点

preceding-sibling::

class 为 single_choice 的元素的所有前面的兄弟节点

//*[@class='single_choice']/preceding-sibling::*

注意事项

某个元素内部使用xpath选择元素, 需要在xpath表达式最前面加个点