Selenium python根据给定的参数从表行中选择表数据

时间:2016-12-06 15:13:38

标签: python selenium

我有一个函数,其中order和searchValue是必需的参数,action和buttonName是可选的。我在运行搜索后使用此功能。此功能允许用户根据参数执行不同的操作。例如,单击复选框(可以在行中的任何位置),单击打开按钮(行中的任何位置)等。

这里是tr看起来(返回三个结果后):

enter image description here

这里是tr里面的td(td可以是复选框,按钮等)

enter image description here

这是我写的一段代码,它工作正常,但想知道我是否可以用更好的方式编写它,或者我不必多次定义xpath路径。

这里用户定义顺序(First或Last(tr))和searchValue,它将使用该文本搜索td并在同一tr中执行操作(取决于顺序)。

def listView(self, order, searchValue, action=False, buttonName=False):
        if order = 'First':
            #self.find_element("//*[starts-with(@id,'table_')]/tbody/tr")
            self.find_element('//*[starts-with(@id,"table_")]/tbody/tr[1]/td[text()= "'+ searchValue +'"]')
            if action == "Link":
                self.click(10, "//*[starts-with(@id,'table_')]/tbody/tr[1]")
            elif action == "Checkbox":
                self.click(10, '//*[starts-with(@id,"table_")]/tbody/tr[1]/td/input[@type="checkbox"]')
            elif action == "Button" and buttonName:
                self.click(10, '//*[starts-with(@id,"table_")]/tbody/tr[1]/td/input[@type="Button"]/@value["'+ buttonName +'"]')
            else:
                raise Exception("Invalid value for action parameter")

        elif order = 'Last':
            self.find_element('//*[starts-with(@id,"table_")]/tbody/tr[last()]/td[text()= "'+ searchValue +'"]')
            if action == "Link":
                self.click(10, "//*[starts-with(@id,'table_')]/tbody/tr[last()]")
            elif action == "Checkbox":
                self.click(10, '//*[starts-with(@id,"table_")]/tbody/tr[last()]/td/input[@type="checkbox"]')
            elif action == "Button" and buttonName:
                self.click(10, '//*[starts-with(@id,"table_")]/tbody/tr[last()]/td/input[@type="Button"]/@value["'+ buttonName +'"]')
            else:
                raise Exception("Invalid value for action parameter")

        else:
            raise Exception("Invalid value for order parameter") 

1 个答案:

答案 0 :(得分:1)

您应该尝试使用Page Object pattern - 将页面,页面部分定义为页面对象,从而抽象出在页面上定位元素和可用操作的方式。

例如,在您的情况下,您可能将表行定义为单独的对象:

INDEX_MAP = {
    'First': '1',
    'Last': 'last()'
}

class RowElement(object):
    def __init__(self, driver, index):
        if index not in INDEX_MAP:
            raise ValueError("Invalid index %s" % index)

        self.driver = driver
        self.row = self.driver.find_element_by_xpath("//*[starts-with(@id,'table_')]/tbody/tr[%s]" % INDEX_MAP[index])

    def click_checkbox(self):
        self.row.find_element_by_xpath('./td/input[@type="checkbox"]').click()

    def click_button(self, name):
        self.row.find_element_by_xpath('./td/input[@type="Button" and @value = "%s"]' % name).click()

然后,您可以这样使用此RowElement类:

row = RowElement(driver, 'First')
row.click_checkbox()
row.click_button("Apply")

row = RowElement(driver, 'Last')
row.click_checkbox()
row.click_button("Apply")