UI自動化之元素定位(xpath、css)


  很早之前就已經寫過自動化了,不過點着功能久了就會容易忘記元素定位,尤其是xpath和css定位,所以就花點時間做下總結收集。

xpath有兩種定位:

一.絕對路徑(不推薦使用,除非已經使用了所有方式仍然無法定位)
方法:根據實際目錄,逐層輸寫。
例子: find_element_by_xpath("/html/body/div[1]/span/input/a")  # div[1]指第1個元素
二.相對路徑(推薦使用)

方法:找到元素有”精准元素“即唯一能標識的屬性;

# 1、通過id定位(以百度首頁為例)
driver.find_element_by_xpath("//*[@id='kw']").send_keys("test")
time.sleep(1)

# 2、通過class定位
driver.find_element_by_xpath("//*[@class='s_ipt']").send_keys("test")

# 3、通過name定位
driver.find_element_by_xpath("//input[@name='wd']").send_keys("test")

# 4、通過其它屬性定位
driver.find_element_by_xpath("//*[@autocomplete='off']").send_keys("test")

# 5、多個屬性組合定位(邏輯運算符and、or等)
driver.find_element_by_xpath("//*[@autocomplete='off' and @class='s_ipt']").send_keys("test")

# 6、通過文本屬性定位
driver.find_element_by_xpath("//*[text()='新聞']")

# 7、通過父元素定位子元素(層級關系)
driver.find_element_by_xpath("//*[@id='u1']/a[2]")  # 通過上一級的id對下一級a標簽進行定位(索引從1開始)

# 8、通過子元素找父元素
driver.find_element_by_xpath("//*[@id='kw']/..")  # //*[@id='kw']/../.. 這個是找爺爺

# 9、模糊匹配
driver.find_element_by_xpath("//a[contains(text(),'hao')]")     # 文本模糊匹配
driver.find_element_by_xpath("//input[contains(@class,'s_btn')]")   # class屬性模糊匹配,其它類似

 

CSS語法定位

 

# 1、通過id定位
driver.find_element_by_css_selector("#kw").send_keys("test")

# 2、通過class定位(多個class屬性有空格的話,將空格換成.)
driver.find_element_by_css_selector(".s_ipt").send_keys("test")

# 3、通過tag定位
driver.find_element_by_css_selector("input") # 定位所有input標簽

# 4、通過其它屬性定位
driver.find_element_by_css_selector("[name='wd']").send_keys("test")

# 5、通過父元素找子元素(組合定位)
driver.find_element_by_css_selector("#qrcode .qrcode-img")     # 通過id為qrcode上一級或上上級找尋下級class為qrcode-img的元素
driver.find_element_by_css_selector("qrcode .qrcode-img:nth-child(1)")     # 找剛剛上面結果的第一組元素,索引從1開始
driver.find_element_by_css_selector("#qrcode div.qrcode-img:nth-child(1)")    # 組合定位,div標簽下class為qrcode-img的元素

css更多操作請看下方

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM