xpath可以以標簽定位,也可以@任意屬性:
如:以input標簽定位:driver.find_element_by_xpath("//input[@id='kw']")
如:@type屬性:driver.find_elements_by_xpath("//input[@type='text']")
一、xpath定位
1、常規屬性
1.通過id定位
driver.find_element_by_xpath("//*[@id='kw']").send_keys("hao")
2.通過tag(標簽)定位
*號匹配任何標簽:driver.find_element_by_xpath("//*[@id='kw']")
也可以指定標簽名稱:driver.find_element_by_xpath("//input[@id='kw']")
3.通過class定位
driver.find_element_by_xpath("//input[@class='s_ipt']").send_keys("hao")
4.通過name定位
driver.find_element_by_xpath("//input[@name='wd']").send_keys("hao")
2、其他屬性
1.其它屬性
driver.find_element_by_xpath("//input[@autocomplete='off']").send_keys("hao")
2.多個屬性組合(邏輯運算)
driver.find_elements_by_xpath("//input[@type='text' and @name='wd']")
3.絕對路徑:/html/body/xxx/xx[@id=‘kw’]
3、層級關系
1.相對路徑:層級關系
driver.find_element_by_xpath("//form[@id='form']/span/input")
如:
/代表絕對路徑
//代表相對路徑
2.索引:如定位搜索選項框
driver.find_element_by_xpath("//*[@id='nr']/option[3]")
3.同一父級多個子元素
如果同一父級下,有多個相同的子元素,下標從1開始:.//*[@id='u1']/a[2]
也可以這樣:.//*[@id='u1']/a[@class="mnav"][1]
4、模糊匹配
1.contains模糊匹配text:contains
如,通過模糊匹配text屬性,找到百度首頁的“糯米”網站超鏈接
driver.find_element_by_xpath("//a[contains(text(),'糯')]").click()
2.模糊匹配某個屬性:contains
xpath("//input[contains(@id,‘xx')]")
driver.find_element_by_xpath("//input[contains(@class,'s_ip')]").send_keys("hao")
3.模糊匹配以xx開頭:starts-with
xpath("//input[starts-with(@id,‘xx') ]")
driver.find_element_by_xpath("//input[starts-with(@class,'s_ip')]").send_keys("hao")
5、文本屬性
對於這種文本屬性,語法:.//*[text()=‘文本內容’]
除了這個文本屬性匹配是.//*[text()=‘文本’]這種格式(無@)
其它的屬性,如id,name,class等都是.//*[@id=‘xxx’] .//*[@name=‘xxx’]這種格式
二、瀏覽器調試xpath
1.Firefox調試:無firePath的情況下,控制台下輸入$x(xpath定位),回車
2.Chrome調試:Console下輸入$x(xpath定位),回車
三、table表格定位
1、定位表格
Table表格固定格式:.//*[@id=‘表格id’]/tbody/tr[行數]/td[列數]/a
.//*[@id='bugList']/tbody/tr[6]/td[4]/a
2、參數化行和列
x = 6
y = 4
table = f".//*[@id='bugList']/tbody/tr[{x}]/td[{y}]/a"
driver.find_element_by_xpath(table).click()
3、根據表格標題定位后面的按鈕
1.先通過bug的標題名稱找到這一行
2.再找到這一行的父節點
3.通過父節點往下搜(編輯按鈕都是固定位置)
text = "上傳多個附件"
t = f'.//*[text()="{text}"]/../../td[@class="text-right"]/a[@title="編輯"]'
driver.find_element_by_xpath(t).click()