最近這段時間比較忙好久沒跟朋友們一起分享技術話題了,今天接着上一篇的Robot繼續跟大家分享Robotframework-Appiumlibrary通過索引定位元素。
1.應用場景
做Android自動化測試的朋友肯定遇到過具有相同ID或Class的無從操作的時候,很多人會想到加個索引呀,沒錯索引確實能解決這個問題,但是Robotframework-Appiumlibrary是不支持索引的,這就需要我們進行擴展,比如下面的微信表情,全部是相同的ID。
2.定位代碼
#通常我們用這個方法來操作點擊元素
def click_element(self, locator):
"""Click element identified by `locator`.
Key attributes for arbitrary elements are `index` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Clicking element '%s'." % locator)
self._element_find(locator, True, True).click()
#通過這個方法來定位元素
def _element_find(self, locator, first_only, required, tag=None):
application = self._current_application()
if isstr(locator):
# Normalize any unicode as explained here, http://appium.io/slate/en/master/?javascript#multi-lingual-support
if self._get_platform() == 'ios':
_locator = normalize('NFD', locator)
else:
_locator = locator
elements = self._element_finder.find(application, _locator, tag)
if required and len(elements) == 0:
raise ValueError("Element locator '" + locator + "' did not match any elements.")
if first_only:
if len(elements) == 0: return None
return elements[0]
elif isinstance(locator, WebElement):
elements = locator
# do some other stuff here like deal with list of webelements
# ... or raise locator/element specific error if required
return elements
通過這兩個方法我們可以確定第二個定位元素的方法找到是一個數組elements,這說明這個方法是可以找到相同ID或Class的全部元素的,另外有個參數first_only表示默認取第一個元素,這下我們就清楚了,當我們傳參數first_only爲false的時候即可返回全部元素,然後我們通過數組下標來獲取對應的元素。
3.增加通過索引點擊元素的方法
#新增一個方法,並且增加一個索引參數
def click_elementsByIndex(self, locator,index):
"""Click element identified by `locator` and `index`.
Key attributes for arbitrary elements are `index` and `name`.
See`introduction` for details about locating elements.
Args:
- ``locator`` - find elements by locator
- ``index`` - click the element with index
"""
self._info("Clicking element '%s'." % locator)
self._element_find(locator, False, True)[int(index)].click()
這段代碼即可通過ID或Class+索引來操作元素
4.RIDE檢驗結果
重新安裝之後,F5即可看到添加的最新關鍵字
image.png
5.實際應用
我們再去操作一下微信表情的點
1.分層實現的業務關鍵字
2.分層實現的基礎關鍵字
後續我會陸續退出Robot framework擴展的相關文章,歡迎小夥伴們持續關注,謝謝。