最近在学习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呢?