selenium python自動化元素定位

2022-01-10 22:30:52 字數 2731 閱讀 7089

最近學習自動化測試,終於初步學習完成,需要進行部落格日誌總結,加深鞏固自己的知識。

元素的八種定位方式

我們在python輸入的元素定位語法:bs.find_element_by_id('kw').send_keys('selenium  (必須包含id屬性)

元素定位語法:(必須包含name屬性的)

元素定位語法:(必須包含class屬性)

元素定位語法:(必須是具有唯一標籤才能定位)

語法同link_text相同,區別在於partial_link_text可以進行模糊定位

這裡為什麼不輸入「新」字呢?,因為定位不是唯一的

7.xpath

這是需要重點學習的地方,因為xpath功能強大,基本能定位所有的元素,如果不行那就多重邏輯加上多關係路徑結合,少有失手。

xpath提供兩種定位方式

一.絕對路徑  :   bs.find_element_by_xpath("/html/body/form/span/input"

絕對路徑因正常情況下使用起來比較繁瑣,所以一般使用下面的相對路徑

二.相對路徑   : bs.find_element_by_xpath("//form/span/input")     相對路徑單一使用只能定位多個相似的元素,必須結合屬性或者層級以及邏輯關係才能定位唯一的元素。

1.相對路徑加屬性: bs.find_element_by_xpath("//*[@id='kw']")  、bs.find_element_by_xpath("//*[@name='wd']")  、bs.find_element_by_xpath("//input[@class='s_ipt']")

2.相對路徑加屬性加層級關係 : 1)父子關係定位: bs.find_element_by_xpath("//span[@class='soutu-btn']/input")   、2)兄弟關係定位 :bs.find_element_by_xpath("//form[@id='form']/../span/input")

3.相對路徑加屬性加邏輯關係 : bs.find_element_by_xpath("//input[@id='kw' and @name='wd']")(並不侷限與id、name、class等,其他屬性也能利用,並且可以邏輯關係巢狀父子關係或者兄弟關係的邏輯關係)bs.find_element_by_xpath("//input[@id='wd' and @target='_black']/../[@id='wd' and @target='_sipt']/div")

8.css

同上面的xpath一樣也是重點和使用最多的方法,因其定位元素速度比xpath快,方法多,所有元素皆可定位,並且上面的定位工具也支援css定位和檢查,所以建議大家盡量使用css。

css定位語法:

1.id  :  bs.find_element_by_css_selector("#kw")

2.class   :  bs.find_element_by_css_selector(".s_ipt")

3.屬性(必須唯一屬性)  :   bs.find_element_by_css_selector("[name=wd]") 、  bs.find_element_by_css_selector("[type=submit

]")4. 層級   : bs.find_element_by_css_selector("html > body > form > span > input") 

5. 屬性加層級  : bs.find_element_by_css_selector("span.soutu-btn> input#kw")  、bs.find_element_by_css_selector("form#form > span > input")

注意:firebug和firepath在新的火狐瀏覽器已經被拋棄了,具體原因不是很清楚,但其功能強大,定位精準,可惜只能安裝低版本的火狐瀏覽器使用。

selenium python環境搭建

安裝python 2.7.版本,其他版本目前支援不好 嘗試cmd下輸入python,若無法呼叫python,需要將python的安裝路徑 python.exe的儲存位置 新增到path系統變數中 3 安裝pycharm整合開發環境 晚上比較多資料,需要破解。4 配置pycharm 開啟pycharm...

selenium python 安裝使用

selenium官網 selenium簡單教程 selenium完整教程 python基礎教程 注意 上去中如果沒有勾選add python to 安執行命令列,會報 pip 不是內部或外部命令 需要手動進行環境配置即可 執行命令視窗 cmd 輸入以下命令安裝selenium pip install...

selenium python環境搭建

一 初始準備 準備工具如下 因為版本都在更新的,python選擇2.7.xx,setuptoosl選擇平台對應的版本。二 安裝 1.安裝python,安裝目錄c python27 2.setuptools 的安裝也非常簡單,同樣是exe檔案,缺省會找到python的安裝路徑,將安裝到c python...