使用Enum构建硒测试定位器

时间:2017-05-04 13:29:26

标签: python selenium selenium-webdriver

我提出了一个关于硒网测试的问题。由于所有元素都需要自己的xpath或css选择器才能通过selenium webdriver进行操作。 我曾尝试使用python Enum并创建类似

的东西
file: elementEnum.py
from enum import Enum

class PageA(Enum):
    pElementA = '//div[{}]'
    pElementB = '//a[.="{}"]'
    pElementC = '//div[@class={}]'

class PageB(Enum):
    pElementA = '//button[.="{}""]'
    pElementB = '//table/tr[{}]/td[{}]'

但事实证明我需要很多时间来构建python格式的字符串函数,而且它看不到pythonoic。

from elementEnum import *
driver.find_element_by_xpath('//div[@class="aaaaaa"]/{}'.format((PageA.pElementA.value).format(1)))
driver.find_element_by_xpath('{}/{}'.format(PageA.pElementA.value).format(1), PageA.pElementB.value.format(2)))
driver.find_element_by_xpath('{}/{}'.format(PageB.pElementB.value).format(1, 3), PageA.pElementA.value.format(2)))

列出所有对应元素及其定位器的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

你可以使用

EC.visibility_of_element_located以找到元素

http://selenium-python.readthedocs.io/waits.html

示例代码:

class SeleniumBaseClass(object):
    def __init__(self,driver):
        self.driver = driver
    def open(self,URL):
        self.driver.get(URL)
    def driverURLChange(self,URL):  
        print("change URL" + URL)
        self.driver.get(URL)
    def currentUrl(self):
        print("URL   " +  self.driver.current_url)
        return self.driver.current_url
    def switchNewWindow(self):
        self.driver.switch_to_window(self.driver.window_handles[1])
        return self.driver.title
    def locateElement(self, loc):
        try:
            print(loc)
            element = WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc))
            return element
        except:
            print ("cannot find {0} element".format(loc))
        return None

你可以

password_loc =(By.NAME,'password')
webdriver = SeleniumBaseClass(driver)
webdriver.locateElement(password_loc )

这可以通过元组来定位元素