python - 我应该如何在 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 格式吗?
解决方案
推荐阅读
- dpkg - apt upgrade dpkg error wile processing (Segmentation fault)..?
- python - Python Crash Course,Alien Invasion,第 12 章,“类‘Sprite’的未解析属性引用‘draw_bullet’”
- html - 一个 flexbox 项目与边距不对齐
- accessibility - GNOME:修复屏幕放大镜的扩展;但是,如何?
- android - React-Native 包 androidx.multidex 不存在
- python - libclntsh.so:无法打开共享对象文件:没有这样的文件或目录 Centos 8 和 python
- python-3.x - 我需要改变什么来摆脱这种似乎从一行跳到另一行的语法错误?
- typescript - Vue & webpack & typescript“初始化前无法访问'__WEBPACK_DEFAULT_EXPORT__'”
- javascript - 使用 Python 在 HTML 网页中输入值
- javascript - NPM MysqlDump 和 Mysql-Import,如何添加删除表选项(如果存在),Node.js