【问题标题】:Selenium Python the rows of the table from a column is not being stored in my list variableSelenium Python 列中的表行未存储在我的列表变量中
【发布时间】:2016-02-13 19:35:18
【问题描述】:

我有一个包含一些列和行的表格的页面。我正在尝试将每行的第 1 列中的数据存储到列表变量中。当我浏览我的代码时,列表变量中没有存储任何内容。 我的循环遍历表很好,因为我可以为每一行打印出第 1 列的值。 我已经在类级别声明了 List 变量。

我的代码 sn-p 是:

def get_table_column_1_values_into_a_list(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")
        for row in rows:
            # Get the columns
            col_name = row.find_elements(By.TAG_NAME, "td")[1]  # This is the Configuration Name column
            col_type = row.find_elements(By.TAG_NAME, "td")[3]  # This is the Type column
            col_rows = row.find_elements(By.TAG_NAME, "td")[4]  # This is the Rows column
            print "col_name.text = "
            print col_name.text
            print col_type.text
            print col_rows.text
            # store the value of col 1 into a  list
            DataPreviewsViewPage.col1_list_before_sort[row] = col_name.text
            print DataPreviewsViewPage.col1_list_before_sort[row]
            #    return True
        return DataPreviewsViewPage.col1_list_before_sort
        #return False
    except NoSuchElementException, e:
        print e
        return False

我的 List 变量声明是:

class DataPreviewsPage(BasePage):

    col1_list_before_sort = [] 

在 For 循环中,我如何将 col_name = row.find_elements(By.TAG_NAME, "td")[1] 中的值存储到项目列表中?

谢谢, 里亚兹

【问题讨论】:

  • 不确定您的代码是如何运行的。 row 不是 webElement 和 DataPreviewsViewPage.col1_list_before_sort[row] 不能工作,如果它是一个列表?

标签: python python-2.7 selenium selenium-webdriver


【解决方案1】:

我认为你可以从方法中返回列名列表:

def get_table_column_1_values_into_a_list(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_element(By.TAG_NAME, "td")[1].text for row in rows]
    except NoSuchElementException, e:
        print e
        return False

【讨论】:

  • 我可以将列名列表存储到一个列表、一个数组中吗?然后我想按字母顺序对列表进行排序。我想使用列表数据类型的排序功能。例如。 col1_values_list.sort()
  • @RiazLadhani 我发布的方法已经返回一个列表。
  • 是的,它返回了一个列表。我通过 PyCharm 调试浏览了代码。它的每一行都有来自 col1 的名称。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2019-04-08
  • 2019-12-03
  • 2021-01-15
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多