使用openpyxl实现Python Selenium脚本每次运行向Excel写入新行
解决方法
核心逻辑是每次写入前通过openpyxl自带的max_row属性获取当前工作表已使用的最大行号,动态计算本次写入的目标行号即可,适配首次及后续所有运行场景。
修改后的完整代码如下:
import time from openpyxl import load_workbook # 这里请补全你原有的Selenium driver初始化逻辑,否则driver变量会报错 # 示例:from selenium import webdriver; driver = webdriver.Chrome() path = r"C:\MyFolder\Filename.xlsx" TodaysDate = time.strftime("%b%d") sheet_name = TodaysDate.upper() wb = load_workbook(path) sheet = wb[sheet_name] # 新增:计算本次要写入的行号,max_row是当前已有内容的最后一行,+1就是下一个空行 next_row = sheet.max_row + 1 Date = time.strftime(("%b%d")) sheet.cell(row=next_row, column=1).value = Date Time = time.strftime("%I%M") sheet.cell(row=next_row, column=2).value = Time PCTCLOSE = driver.find_element_by_xpath("//option[contains(text(),'Percentage Close')]").text sheet.cell(row=next_row, column=3).value = PCTCLOSE ValidResponse = driver.find_element_by_xpath("//option[contains(text(),'Valid Response')]").text sheet.cell(row=next_row, column=4).value = ValidResponse wb.save(path) # 运行结束后关闭资源,避免文件占用报错 driver.quit() wb.close()
注意事项
- 请确保对应日期工作表的第1行已经提前写好表头,若为新建的空工作表,
max_row会返回0,首次写入会直接写到第1行,不符合你的需求 - 30分钟定时运行建议用系统自带的定时任务工具实现:Windows用任务计划程序,Linux/macOS用crontab,比在Python中写死循环更稳定
内容的提问来源于stack exchange,提问作者Bobby
相关产品推荐
相关产品推荐

