writer.writerow()在for循环中无法写入多条数据的问题求助
解决writer.writerow()无法写入多条数据到CSV的问题
看起来你的脚本核心逻辑是通的,但几个细节问题导致数据没法正常写入文件。我来帮你逐一排查修复:
1. 修复异常处理中的变量未定义问题
你的try-except块里,如果元素查找失败(比如页面加载慢、元素定位错),address、name这些变量就不会被定义,后续执行writer.writerow()时会悄悄抛出NameError(虽然你用了pass跳过异常,但程序其实在这里卡壳了)。要给这些变量设置默认值:
try: address = driver.find_element_by_xpath('//*[@id="maincontent"]/div[2]/div[1]/div[3]/div').text name = driver.find_element_by_class_name('owner-name').text mailing_address = driver.find_element_by_xpath( '//*[@id="maincontent"]/div[3]/div[1]/div[2]/div[2]/div').text phone = driver.find_element_by_xpath( '//*[@id="maincontent"]/div[3]/div[2]/div[2]/div[2]/div[1]/strong').text except Exception as e: # 捕获异常时给变量设默认值,避免未定义错误,同时打印错误方便调试 print(f"处理地址时出错: {str(e)}") address = "" name = "" mailing_address = "" phone = ""
2. 修复地址输入的格式错误
你把地址按逗号分割成列表后直接存入address_array,但send_keys()需要传入字符串,而不是列表。这样会导致搜索框输入类似['123 Main St', 'New York']的内容,肯定搜不到正确结果。要把列表转回完整字符串:
# 原代码:address_array.append(address) address_array.append(','.join(address)) # 把分割后的列表转回完整地址字符串
3. 强制刷新文件缓冲区
用追加模式(a)打开文件时,Python会缓冲写入内容,可能数据还留在内存里没写到磁盘。可以在每次写入后手动刷新缓冲区:
writer.writerow({"Address": address, "Name": name, "Mailing Address": mailing_address, "Ph": phone}) f.flush() # 强制把内存中的数据写入磁盘
或者打开文件时直接启用行缓冲,这样每写一行就自动刷盘:
with open('save_data.csv', 'a', buffering=1) as f:
4. 确保表头正确写入(可选)
如果是第一次运行脚本,save_data.csv是空文件,需要先写入表头。可以在初始化writer后添加判断:
import os # 在打开save_data.csv的with块内 if os.path.getsize('save_data.csv') == 0: # 文件为空时写入表头 writer.writeheader()
优化建议:复用浏览器实例
你现在每次循环都新建一个Chrome实例,这不仅慢,还会消耗大量系统资源。可以把driver初始化移到循环外面:
# 移到循环前初始化浏览器 driver = webdriver.Chrome() driver.set_window_size(1920, 1080) for j in range(initRow, len(address_array)): driver.get('somesite') sleep(7) # ... 后续搜索、数据提取操作 ... # 所有地址处理完后再关闭浏览器 driver.quit()
完整修复后的核心代码片段
import csv from time import sleep import pandas as pd from selenium import webdriver import os initRow = 0 with open('Search.csv', 'r') as csv_file: with open('save_data.csv', 'a', buffering=1) as f: fieldnames = ["Address", "Name", "Mailing Address", "Ph"] writer = csv.DictWriter(f, fieldnames=fieldnames) # 写入表头(仅当文件为空时) if os.path.getsize('save_data.csv') == 0: writer.writeheader() csv_reader = csv.DictReader(csv_file) address_array = [] for row in csv_reader: address = row['Address'].split(',') address_array.append(','.join(address)) # 修复地址格式 print(address_array) # 复用浏览器实例 driver = webdriver.Chrome() driver.set_window_size(1920, 1080) for j in range(initRow, len(address_array)): driver.get('somesite') sleep(7) driver.find_element_by_xpath('//*[@id="search-address"]').send_keys(address_array[j]) driver.find_element_by_xpath( '//*[@id="maincontent"]/div[2]/div[1]/div[2]/div[1]/div[2]/form[1]/input[3]').click() sleep(10) try: address = driver.find_element_by_xpath('//*[@id="maincontent"]/div[2]/div[1]/div[3]/div').text name = driver.find_element_by_class_name('owner-name').text mailing_address = driver.find_element_by_xpath( '//*[@id="maincontent"]/div[3]/div[1]/div[2]/div[2]/div').text phone = driver.find_element_by_xpath( '//*[@id="maincontent"]/div[3]/div[2]/div[2]/div[2]/div[1]/strong').text except Exception as e: print(f"处理地址 {address_array[j]} 时出错: {str(e)}") address = "" name = "" mailing_address = "" phone = "" writer.writerow({"Address": address, "Name": name, "Mailing Address": mailing_address, "Ph": phone}) print(address, name, mailing_address, phone) print('---------------------------') driver.quit()
这些修改应该能解决你无法写入多条数据的问题,主要修复了变量未定义、地址格式错误、文件缓冲这几个核心问题,同时优化了浏览器实例的使用,提升脚本运行效率。
内容的提问来源于stack exchange,提问作者junaid iqbal
相关产品推荐
相关产品推荐

