首页 > 解决方案 > 我应该如何在 openpyxl 中循环大文件?iter_rows 给出错误

问题描述

在过去的两个月里,作为我工作的一部分,我一直在 python/selenium/openpyxl 中构建一个网络爬虫。考虑到这是我第一次做这样的事情,它已经相对成功,它已经产生了结果。但是我一直无法弄清楚如何正确执行的一件事是,我应该如何遍历 .xlsx 文档?

我正在处理超过 500k 行的文件。不过,我已将它们分成 100k,这样大小就不会成为问题。

所以我的问题是,当我以这种方式遍历文档时:

wb = load_workbook(filePath, read_only=True)
ws = wb.active

while (currentRow <= docLength):
    adress = ws.cell(row=currentRow, column=1)
    car = ws.cell(row=currentRow, column=2)
        
    #Scrape info and append into other document
    currentRow += 1

它最终消耗了太多的内存,并且在 100 行之后脚本已经变得非常慢......

但是如果我这样做,我每次都会在几百行之后得到 ParseError !这非常令人沮丧,因为我认为这是正确的做法。

wb = load_workbook(filePath, read_only=True)
ws = wb.active

try:
    for row in ws.iter_rows(min_row=1, max_col=10, max_row=docLength, values_only=True):
        for x, cell in enumerate(row):
            if x == 0:
                adress = cell
            if x == 1:
                car = cell

        #Scrape info and append into other document
        currentRow += 1

except xml.etree.ElementTree.ParseError:
    ???

完整的异常错误:

Traceback (most recent call last):
  File "C:\python\scrape.py", line 263, in <module>
    for row in ws.iter_rows(min_row=1, max_col=10, max_row=docLength, values_only=True):
  File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl-3.0.3-py3.8.egg\openpyxl\worksheet\_read_only.py", line 78, in _cells_by_row
  File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl-3.0.3-py3.8.egg\openpyxl\worksheet\_reader.py", line 142, in parse
  File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 1227, in iterator
    yield from pullparser.read_events()
  File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 1302, in read_events
    raise event
  File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 1274, in feed
    self._parser.feed(data)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 769027

为什么会这样?:( 为什么它说这么高的列数,是因为 xml 格式吗?

标签: pythonexcelseleniumopenpyxl

解决方案


推荐阅读