Skip to main content
 首页 » 编程设计

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

2025年02月15日13落叶无声

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

这是 tr 的样子(返回三个结果后):

enter image description here

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

enter image description here

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

这里用户定义了顺序(第一个或最后一个(tr))和搜索值,它将搜索带有该文本的 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")  

请您参考如下方法:

你真的应该尝试使用 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")