UI自動化的核心在於定位
目錄
1、8種基礎定位方法
2、xpath定位
3、css定位
4、多組元素
1、8種基礎定位方法
driver.find_element_by_id() #id定位 driver.find_element_by_name() #name定位 driver.find_element_by_class_name() #class定位 driver.find_element_by_tag_name() #標簽名定位,一般用於iframe;標簽較少的也可以使用,用取下標的方式 driver.find_element_by_xpath() #xpath定位,可以用firepath來獲得這個定位 driver.find_element_by_css_selector() #css定位 driver.find_element_by_link_text() #a標簽的文本定位 driver.find_element_by_partial_link_text() #a標簽的局部文本定位
2、xpath定位
//:相對定位
*匹配任意標簽
第一種:id\class\name\其他屬性
driver.find_element_by_xpath("//*[@id='']") #id和值 driver.find_element_by_xpath("//*[@class='']") #class和值 driver.find_element_by_xpath("//*[@name='']") #name和值,如:find_element_by_xpath("//*[name='']") driver.find_element_by_xpath("//*[@shuxingming='']") #屬性名和值,如:find_element_by_xpath("//*[align='left']")
第二種:模糊匹配\層級\索引\邏輯運算
模糊匹配:
driver.find_element_by_xpath("//*[contains(text(),'測試')]") #包含某些字符 driver.find_element_by_xpath("//*[starts-with(text(),'測試')]") #以某些字符開頭 driver.find_element_by_xpath("//*[ends-with(text(),'測試')]") #以某些字符結尾 driver.find_element_by_xpath("//*[matchs(text(),'測試')]") #正則匹配
層級:
driver.find_element_by_xpath("//*[@id='']/p")
索引:
driver.find_element_by_xpath("//*[@id='']/option[0]")
邏輯運算:
driver.find_element_by_xpath("//*[@class=''and @name='']")
第三種:
絕對定位,使用firepath:
html/body/heard/div/div/div/div/ul/li[2]/a
3、css定位
第一種:id\class\標簽名
driver.find_element_by_css_selector("#username") #id為username driver.find_element_by_css_selector(".username") #class為username driver.find_element_by_css_selector("iframe") #標簽名為iframe
第二種:
索引: driver.find_element_by_css_selector("selet#nr>option:nth-child(1)") #標簽名:nth-child(1)來定位子元素 層級: driver.find_element_by_css_selector("selet#nr>option") #標簽名:nth-child(1)來定位子元素 邏輯運算: driver.find_element_by_css_selector("input#nr[id=''][class='']") #不用and連接,寫在一起即可
4、多組元素
一組元素是find_element,多組就是find_elements,其他定位方法一樣。只不過要通過下標索引的方式取得想要的值
m=driver.find_elements_by_name("qq") print m[1]