You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium结合for循环时出现报错问题求助

Selenium循环中InvalidSessionIdException报错解决方法

问题分析

你的代码存在两个核心问题:

  1. 会话失效:循环内部调用driver.close()会关闭当前浏览器会话,第二次循环执行driver.get(url)时,原WebDriver会话已不存在,因此抛出InvalidSessionIdException。
  2. API弃用警告:新版本Selenium不再支持executable_path参数初始化WebDriver,需改用Service类。

修正后的代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
import csv

with open('smlxl.csv', 'r') as myFile:
    myReader = csv.reader(myFile)
    myList = list(myReader)

# 使用Service类指定ChromeDriver路径,解决弃用警告
service = Service('C:\Program Files (x86)\chromedriver.exe')
driver = webdriver.Chrome(service=service)

for n in range(1, 1000, 4):
    barcode = myList[n][24]
    url = f"https://www.google.com/search?q={barcode}"
    driver.get(url)
    print(n)
    time.sleep(3)

# 循环结束后再关闭浏览器
driver.close()

修改说明

  • 新增from selenium.webdriver.chrome.service import Service导入,用Service类替代executable_path参数,消除弃用警告。
  • 将driver.close()移至循环外部,确保整个循环过程复用同一个WebDriver会话,避免会话失效报错。
  • 移除循环内的n = (n+4),因为range(1,1000,4)已自动按步长4递增,手动修改会破坏循环逻辑。
  • 改用f-string拼接URL,代码更简洁易读。

内容的提问来源于stack exchange,提问作者unifari56

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:15:41