Selenium Python可以按字母顺序对Web元素列表进行排序

时间:2016-02-15 10:53:41

标签: python-2.7 selenium selenium-webdriver

我有一个网络元素列表。我想按字母顺序排序。 Web元素的数据类型没有排序功能 当我尝试排序时出现以下错误:

Traceback (most recent call last):
  File "C:\Webdriver\ClearCore Regression Test\ClearCore - Regression Test\TestCases\DataPreviewsPage_TestCase.py", line 375, in test_a2_sort_data_preview
    print data_previews_page.compare_lists_2()
  File "C:\Webdriver\ClearCore 501 Regression Test\ClearCore - Regression Test\Pages\data_previews.py", line 610, in compare_lists_2
    sortedTable = DataPreviewsPage.column1_list_before_sort.sort() # This table holds the data previews name in sorted order of what it should be
AttributeError: 'NoneType' object has no attribute 'sort'

我的代码段是:

class DataPreviewsPage(BasePage):
            column1_list_before_sort = None # This list will hold the data from col1 before ClearCore has done the sort.  This list will then be sorted into ABC order.  We can then use it to compare with the list after ClearCore has done the sort

def compare_lists_2(self):
        sortedTable = DataPreviewsPage.column1_list_before_sort.sort() # This table holds the data previews name in sorted order of what it should be
        sortedList = DataPreviewsPage.list_after_ClearCore_has_sorted # This compares the sort with the expected sort (expected sort = sortedTable)
        for item in sortedTable:
            print sortedTable[item]
            print sortedList[item]

返回web元素列表的方法是:

def get_table_column_1_values_into_a_list_before_ClearCore_has_done_the_sort(self):
        try:
            WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.ID, 'data_configuration_data_previews_ct_fields_body')))
            table_id = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.ID, 'data_configuration_data_previews_ct_fields_body')))
            rows = table_id.find_elements(By.TAG_NAME, "tr")
            return [row.find_elements(By.TAG_NAME, "td")[1].text for row in rows] # returns the data preview name from col1 for each row
        except NoSuchElementException, e:
            print e
            return False

如何按字母顺序对网页元素列表进行排序? web元素变量是“column1_list_before_sort”,我想对此进行排序。

谢谢, 里亚兹

1 个答案:

答案 0 :(得分:0)

您可以创建cutom比较器,以自定义方式对对象列表进行排序,例如

AttributeError: 'NoneType' object has no attribute 'sort'

但是,我认为问题是column1_list_before_sort的值。由于错误为column1_list_before_sort,它在{{1}}内没有任何意义。