最近在學習selenium webdriver尋找元素時
常需要重複打
find_element_by_id或xpath或name等等....
如是還要加上explicit wait時
就會讓code變得又臭又常
剛好在逛論壇時看到有個網友PO了一個自訂function
======
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from abc import abstractmethod
class LocatorMode:
XPATH = "xpath"
CSS_SELECTOR = "cssSelector"
NAME = "name"
ID = "id"
TAG_NAME = "tagName"
class BasePage(object):
def __init__(self, driver):
self.driver = driver
def wait_for_element_visibility(self, waitTime, locatorMode, Locator):
element = None
if locatorMode == LocatorMode.ID:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.ID, Locator)))
elif locatorMode == LocatorMode.NAME:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.NAME, Locator)))
elif locatorMode == LocatorMode.XPATH:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.XPATH, Locator)))
elif locatorMode == LocatorMode.CSS_SELECTOR:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.CSS_SELECTOR,
Locator)))
else:
raise Exception("Unsupported locator strategy.")
return element
=====
我試了好多次都沒辦法成功呼叫這個function
我現在希望的狀況是
1.用tagname來找element,且假設網頁中element的tagname="tr"
2.EC是在visibility_of_element_located的狀況
3.等待時間是10秒
所以我自己試了一下
element = BasePage.wait_for_element_visibility(10,tagName,"tr")
element.click()
但如果用這樣的input執行的話
系統會返回:
name 'tagName' is not defined
要是換成
element = BasePage.wait_for_element_visibility(10,"tagName","tr")
element.click()
系統會返回:
wait_for_element_visibility() missing 1 required positional argument:
'Locator'
請問我要怎麼輸入括號內的變數,才能成功執行BasePage裡面的function呢?