PythonSelenium为定位器类使用一个通用xpath字典?

2024-10-01 11:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python字典可以为多个xpath获取一个“通用xpath”吗? 在locators类中,我想定位公式中的所有元素,以便自动输入数据(用于自动化测试)。 在XPATH中,每个字段的所有更改只需每次输入“number+1”。 所以我用python创建了这个字典:

class CreateLabLocators(object):
formulaDictionary = {"labname":12,
                     "city":13,
                     "state":14,
                     "zipcode":15,
                     "street":16,
                     "number":17,
                     "country":18,
                     "website":19,
                     "phone":20,
                     "fax":21,
                     }

是否可以使用字典的键和值为每个字段设置一个定位器? 所以不是这样:

^{pr2}$

吃点更一般的东西。我该如何实现这一点? 所以如果我想在类外调用定位器,我应该可以用类似于。。。在

find_element(*CreateLabLocators.city).send_keys("abc")
find_element(*CreateLabLocators.zipcode).send_keys("123")

等等。 另外,我使用的是python2.7。在


Tags: 定位send元素numbercity字典elementkeys
2条回答

你可以这样做-

def xpath_builder(which_one):
     first_half = r"//input[@id='__input"
     second_half = r"-inner']"
     return (first_half + formulaDictionary[which_one] + second_half)

your_element = driver.find_element_by_xpath(xpath_builder(city))

在您的具体情况下,您可以简单地执行以下操作:

for index in range(12, 22):
    locator = (By.XPATH, "//input[@id='__input%s-inner']" % index)
    #  do something with locator

或者如果要使用字典中的值:

^{pr2}$

相关问题 更多 >