如何跳过循环中的空 .xls 单元格:XLRD (Python)

How to skip empty .xls cells in loop : XLRD (Python)

我正在读取 .xls 文件并按单元格解析列,并使用 xlrd 根据亚马逊订单上的 Web 元素检查它们。在 .xls 文件包含一个空单元格之前,一切似乎都运行良好。然后解析空单元格,然后 "found" 作为网络元素。

from selenium import webdriver
import xlrd

sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
for i in range(sheet.nrows):
    po = (sheet.cell_value(i, 3))
    tracking = (sheet.cell_value(i, 10))
    if driver.find_elements_by_link_text(po):
        print("FOUND!!!!", po)

xls 文件如下所示:(为简单起见,我只使用了 2 列)

+---+---------------------+--------------------+
|   |        Col3         |        col10       |
+---+---------------=-----+--------------------+
| 1 | 111-6955555-7777777 | 1Z1E199A4209992999 |
| 2 |                     | 775746666666       |
| 3 | 2008999             |                    |
| 4 | 111-5855555-7777777 | 1Z1E199E4207772696 |
+---+---------------------+--------------------+

在这种情况下,亚马逊的订单号以 111- 开头。较小的订单号用于另一个网站,但没关系,因为它不是作为 Web 元素找到的。问题是 col3 中的空白单元格,因为它们已被解析并且 ARE 被发现为 Web 元素。

第 10 列用于查找与作为 Web 元素找到的相应单元格关联的跟踪号。空白单元格在这里很好,因为所有亚马逊订单都会有相应的跟踪号。

@evolve710,嗨。 从 this post 开始,我建议使用 xlrd.XL_CELL_EMPTY 在这里查看。

因此,对工作簿中所有 non-empty 个单元格进行迭代的整个代码片段如下所示:

import xlrd
book = xlrd.open_workbook("sample.xls")
ref3d = book.name_map["moscow"][0].result.value[0]

# Iterate over each sheet
for sheet_num in range(ref3d.shtxlo, ref3d.shtxhi):
    sheet = book.sheet_by_index(sheet_num)
    print sheet.name
    row_lim = min(ref3d.rowxhi, sheet.nrows)
    col_lim = min(ref3d.colxhi, sheet.ncols)

    # Iterate over each column
    for row_num in range(ref3d.rowxlo, row_lim):

        # Iterate over each row
        for col_num in range(ref3d.colxlo, col_lim):
            col_type = sheet.cell_type(row_num, col_num)

            if not col_type == xlrd.XL_CELL_EMPTY:
                cval = sheet.cell_value(row_num, col_num)
                print "\t({0},{1}): {2}".format(
                    row_num, col_num, cval)

希望此方法对您有所帮助。

我终于明白了。代码如下所示:

sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
for i in range(sheet.nrows):
    cell = sheet.cell(i, 3)
    cty = cell.ctype
    if cty == xlrd.XL_CELL_EMPTY:
        continue
    else:
        po = (sheet.cell_value(i, 3))
        tracking = (sheet.cell_value(i, 10))
        if driver.find_elements_by_link_text(po):
            print("FOUND!!!!", po)