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")#節點
driver.find_element_by_xpath("/html/body/div") #絕對路徑,從根節點開始,一旦頁面改變必須重新定位,不推薦
driver.find_elements_by_xpath("//div//a") #相對路徑,從當前節點開始而不考慮它們的位置:選取div下面的a元素
driver.find_element_by_xpath("//input/..") #選擇 input 元素的父節點
driver.find_element_by_xpath("//*") #選擇所有節點
#謂語:謂語是用來查找某個特定的節點或者包含某個指定的值的節點,謂語被嵌在方括號[]中。#索引
driver.find_element_by_xpath("//a[1]") #索引,選擇第一個 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 元素#運算符、函數
driver.find_element_by_xpath("//*[@name='pwd' and @class='s-wd']") #邏輯運算 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的最后一個 input
driver.find_element_by_xpath("//div/input[last()-1]") #屬于div的倒數第二個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標簽的所有文本
#軸#子元素 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::*")#當前節點之后的所有節點 following
driver.find_element_by_xpath("//input[@id='pwd']/following::*")#當前節點之前的所有節點 preceding
driver.find_element_by_xpath("//input[@id='pwd']/preceding::*")#attribute 選取當前節點的所有屬性。
"//input[@id='pwd']/attribute::*"
#哥哥姐姐(當前節點之前的同級節點)preceding-sibling
driver.find_element_by_xpath("//input[@id='pwd']/preceding-sibling::*")
time.sleep(1)
driver.quit()
總結
以上是生活随笔為你收集整理的python css和xpath_Selenium系列教程(四)css、xpath定位(基于 Python)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: chrome 代理插件_Chrome浏览
- 下一篇: python输出国际象棋棋盘_pytho