python css和xpath_Selenium系列教程(四)css、xpath定位(基于 Python)
#!/usr/bin/env python
importtimefrom selenium importwebdriver
driver=webdriver.Chrome()
driver.get("http://localhost:63342/webtest/demo.html")#節(jié)點(diǎn)
driver.find_element_by_xpath("/html/body/div") #絕對路徑,從根節(jié)點(diǎn)開始,一旦頁面改變必須重新定位,不推薦
driver.find_elements_by_xpath("//div//a") #相對路徑,從當(dāng)前節(jié)點(diǎn)開始而不考慮它們的位置:選取div下面的a元素
driver.find_element_by_xpath("//input/..") #選擇 input 元素的父節(jié)點(diǎn)
driver.find_element_by_xpath("//*") #選擇所有節(jié)點(diǎn)
#謂語:謂語是用來查找某個(gè)特定的節(jié)點(diǎn)或者包含某個(gè)指定的值的節(jié)點(diǎn),謂語被嵌在方括號[]中。#索引
driver.find_element_by_xpath("//a[1]") #索引,選擇第一個(gè) a 元素#屬性選擇器 @
driver.find_element_by_xpath("//span[@class='name']/input") #選擇 class=name 的span元素下的input元素
driver.find_element_by_xpath("//input[@type]") #選取所有含有 type 屬性的 input 元素
driver.find_element_by_xpath("//input[@*]") #選取所有帶有屬性的 input 元素#運(yùn)算符、函數(shù)
driver.find_element_by_xpath("//*[@name='pwd' and @class='s-wd']") #邏輯運(yùn)算 and、or、not
driver.find_element_by_xpath("//book/title | //book/price") #book下的title 和book 下的price
driver.find_element_by_xpath("//div/input[last()]") #屬于div的最后一個(gè) input
driver.find_element_by_xpath("//div/input[last()-1]") #屬于div的倒數(shù)第二個(gè)input
driver.find_element_by_xpath("//div/input[position()<2]") #選擇屬于div的最前面的input元素
driver.find_element_by_xpath("//book[price>30]") #price>30的book元素
#模糊匹配
ele = driver.find_element_by_xpath("//*[contains(@class, 'wd')]")print(ele.get_attribute("id"))
driver.find_element_by_xpath("//*[starts-with(@id, 'p')]")#文本定位
driver.find_element_by_xpath("//a[text()='百度']")"//a/text()" #獲取a標(biāo)簽的所有文本
#軸#子元素 child
driver.find_element_by_xpath("//div[contains(@class,'account')]//child::*") #class包含account的div下的所有子元素(不知道為什么也查出了后代元素???)
driver.find_element_by_xpath("//div[contains(@class,'account')]//child::input[@id='kw']")#先輩 ancestor
driver.find_element_by_xpath("//input[@id='test']//ancestor::div")#先輩和自己 ancestor-or-self
driver.find_element_by_xpath("//input[@id='test']//ancestor-or-self::*")#parent:父輩
driver.find_element_by_xpath("//input[@id='test']//parent::*")#descendant 后代子孫
driver.find_element_by_xpath("//div[contains(@class,'account')]//descendant::*")#descendant-or-self 后代及自己
driver.find_element_by_xpath("//div[contains(@class,'account')]//descendant-or-self::*")#當(dāng)前節(jié)點(diǎn)之后的所有節(jié)點(diǎn) following
driver.find_element_by_xpath("//input[@id='pwd']/following::*")#當(dāng)前節(jié)點(diǎn)之前的所有節(jié)點(diǎn) preceding
driver.find_element_by_xpath("//input[@id='pwd']/preceding::*")#attribute 選取當(dāng)前節(jié)點(diǎn)的所有屬性。
"//input[@id='pwd']/attribute::*"
#哥哥姐姐(當(dāng)前節(jié)點(diǎn)之前的同級節(jié)點(diǎn))preceding-sibling
driver.find_element_by_xpath("//input[@id='pwd']/preceding-sibling::*")
time.sleep(1)
driver.quit()
總結(jié)
以上是生活随笔為你收集整理的python css和xpath_Selenium系列教程(四)css、xpath定位(基于 Python)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: chrome 代理插件_Chrome浏览
- 下一篇: python输出国际象棋棋盘_pytho