Python Selenium爬虫运行报错ValueError: I/O operation on closed file问题咨询
报错原因
你触发该报错的核心是Python with 上下文管理器的特性导致的:
with open(...) as xxx语法会自动管理文件句柄的生命周期,当代码执行跳出with对应的缩进块后,关联的文件会被自动关闭- 你原代码的结构存在缩进错误:
with open('inputLinks1.csv', 'rt') as cp_csv: cp_url = csv.reader(cp_csv) # 此处已经跳出with块,cp_csv文件已经被自动关闭 for row in cp_url: ...
csv.reader对象cp_url依赖打开的cp_csv文件句柄运行,文件关闭后再遍历cp_url就会触发I/O operation on closed file报错。
修复方案
只需要把遍历cp_url的代码全部缩进,放到with open('inputLinks1.csv', 'rt') as cp_csv:的缩进块内即可,修改后的代码片段如下:
with open('inputLinks1.csv', 'rt') as cp_csv: cp_url = csv.reader(cp_csv) # 遍历逻辑移到with块内部,保证读取期间文件始终处于打开状态 for row in cp_url: links = row[0] contents.append(links) driver.get(links) with open('xpathtags.csv', 'rt') as cp2_csv: cp_url2 = csv.reader(cp2_csv) for row1 in cp_url2: print(row[0]) (xtype, xpathtext) = row1[0].split(';') print(xtype, xpathtext) contents.append(xtype) contents.append(xpathtext) elems = driver.find_elements_by_xpath(xpathtext) for elem in elems: f = open('output1.csv', 'a', encoding='utf-8') f.write( links + ", "+ xtype + "," + str(elem.get_attribute('type')) + ', ' + str(elem.get_attribute('id')) + ', ' + str(elem.get_attribute('class')) + ', ' + str(elem.get_attribute('for')) + ', ' + str(elem.get_attribute('href')) + ', ' + str(elem.get_attribute('alt')) + ', ' + str(elem.get_attribute('type')) + ', ' + str(elem.get_attribute('src')) + ', ' + str(elem.get_attribute('name')) + ', ' + str(elem.get_attribute('width')) + ', ' + str(elem.get_attribute('height')) + ', ' + str(elem.get_attribute('data-src')) + ', ' + str(elem.get_attribute('innerText').strip()) + ', ' + str(elem.get_attribute('action')) + ', ' + str(elem.get_attribute('value')) + ', ' + '\n') f.close()
可选优化建议:
- 你也可以在with块内先把所有链接一次性读取到列表里,之后再遍历列表也可以避免该问题
- 输出文件
output1.csv的写入操作也建议用with上下文管理器管理,避免频繁打开关闭文件影响性能
内容的提问来源于stack exchange,提问作者aurnindo
相关产品推荐
相关产品推荐

