XPATH定位
XPATH和CSS選擇器最重要的區別是XPATH可以向前和向后查詢DOM結構的元素,而CSS選擇器只能向前查詢,這意味著XPATH可以通過子元素來定位父元素!
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id ='app'>我是div
<form id="loginForm" name="f"> 我是form
<input id="name" name="username" class="'s_ipt" autocomplete="off"> 我是input_1
<input name="contiune" type="button">我是input_2
<input type="submit" id="su" value="搜索" class="bg s_btn">我是input_2
</form>
</div>
</body>
</html>
選取節點
1)選取此節點下的所有子節點
nodename = "html"
element = driver.find_element_by_xpath("html").find_element_by_xpath('body')
選取html-body節點下的所有子節點
2) / 從根節點選取,代表絕對路徑
element = driver.find_element_by_xpath('/html/body/div')
選取html-body-div節點下的所有子節點
3)// 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置
element = driver.find_element_by_xpath('//div')
選取div節點下的所有子節點
4). . 選取當前節點的父節點;@選取屬性
element = driver.find_element_by_xpath('//*[@id="name"]').find_element_by_xpath('..')
選取input_1的父節點form
5). 選取當前節點
選取未知節點
1)* 匹配任何元素節點
element = driver.find_element_by_xpath('//[@id="name"]')
//[@id="name"]:選取文檔中所有符合id屬性值為name的節點
2)@* 匹配任何屬性節點
element = driver.find_element_by_xpath('//input[@*]')
選取文檔中所有帶有屬性input的元素
3)node() 匹配任何類型的節點
選取若干路徑
1) | 選取若干路徑
element = driver.find_element_by_xpath('//input| //div')
選取文檔中所有input和div元素
關鍵字
element = driver.find_element_by_xpath("http://input[starts-with(@id,'na')]")
選取id值以na開頭的input節點
element = driver.find_element_by_xpath("http://input[contains(@id,'na')]")
選取id值包含na的input節點
element = driver.find_element_by_xpath("http://input[contains(@id,'na') and contains(@id,'me')]")
選取id值包含na和me的input節點
element = driver.find_element_by_xpath("http://title[contains(text(),'itle')]")
選取節點文本包含itle的title節點
xpath軸
element = driver.find_element_by_xpath("http://form/descendant::input[@id='name']")
在form元素的所有子元素中,選擇input標簽且id為name的元素
element = driver.find_element_by_xpath("http://form/ancestor::div[@id='app']")
在form元素的所有先輩中,選擇div標簽且id為app的元素
XPATH使用方法:
1、通過絕對路徑定位(不推薦)
2、通過相對路徑定位
3、通過索引定位
element = driver.find_element_by_xpath("http://input[1]")
4、使用XPATH及屬性值定位
element = driver.find_element_by_xpath('//*[@id="name"]')
5、使用XPATH及屬性名稱定位
driver.find_element_by_xpath("http://input[@id='name']")
6、部分屬性值匹配
element = driver.find_element_by_xpath("http://input[starts-with(@id,'na')]")
7、使用任意值來匹配屬性及元素
8、使用XPATH軸來定位
element = driver.find_element_by_xpath("http://form/ancestor::div[@id='app']")