Appium – 利用 find_element_by_xpath 找 element

我們很常使用 name 來找 element,但在使用 Appium 測試時,有的時候會發現單純透過 name 沒辦法找到所有想指定的 element,這時候就會覺得 find_element_by_xpath 也是個蠻好用的找尋 element 的方法。

xpath 其實是指畫面上 xml 的路徑,xpath 的使用就是利用這些 node 的階層關係,以及每個 node 的特性來找 element。

看下面一些範例應該會比較清楚如何使用 xpath。

範例一:在 iOS 上,用 xpath 找到 name 為 “testing" 的 UIAButton。(算是最基本的使用)

driver.find_elements_by_xpath('''//UIAButton[@name='testing']''')

 

範例二:在 iOS 上,用 xpath 找到在 UIATableGroup 底下的一個 UIAButton 元件,且 name 有包含 “testing"。

driver.find_elements_by_xpath('''//UIATableGroup/UIAButton[contains(@name, 'testing')]''')

 

範例三:在 iOS 上,用 xpath 找到 name 開頭是 “testing" 的 UIAButton。

driver.find_elements_by_xpath('''//UIAButton[start-with(@name, 'testing')]''')

以上三個範例是平常使用 xpath 找 element 的方法。

還有一種是當想抓到一個 element 但他沒有其他特徵,所以就可以透過此 element 的 sibling 和利用「..」這個 xpath 的 syntax,也就是透過其他 element 跟階層來找到這個沒有特徵的 element。

範例四:在 iOS 上,用 xpath 找到 name 為 “testing" 的 UIAButton 的同一階層的 UIAStaticText。

driver.find_elements_by_xpath('''//UIAButton[@name='testing']/../UIAStaticText''')

這些範例都是用 name 這個屬性來找特定的 element,當然也可以使用其他屬性(ex: value、label …etc)來找。多加變化,可以更準確的找到 element!

參考文章:
XPath Tutorial

對「Appium – 利用 find_element_by_xpath 找 element」的一則回應

  1. 嗨~你好…
    想請教個問題, 我想帶一段字串進入xpath抓取進而定位
    ex:
    result = ‘content’
    event = self.driver.find_element_by_xpath(“//*[@text = result]/..")

    這種情況可以透過xpath去實現嗎? 謝謝

發表留言