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

Python爬虫:WebDriver TypeError(NoneType不可下标)问题求助

问题排查与解决方案

错误原因分析

你遇到的TypeError: 'NoneType' object is not subscriptable错误,本质是ChromeDriver启动会话时返回的response为None,导致无法获取sessionId。核心原因通常是ChromeDriver与浏览器版本不兼容、启动参数冲突或路径配置错误,同时新浪财经的反爬机制也可能导致网站无法正常加载。

分步解决方案

1. 匹配ChromeDriver与Chrome浏览器版本

这是最常见的触发原因:

  • 查看本地Chrome浏览器版本(设置→关于Chrome)
  • 下载对应版本的ChromeDriver,替换当前的chromedriver.exe
  • 确保两者版本号完全一致(比如Chrome是118.x,ChromeDriver也必须是118.x)

2. 调整Chrome启动参数

移除或修改冲突的参数:

  • 注释掉--remote-debugging-port=9230:该参数在无头模式下非必需,若端口被占用会导致会话启动失败
  • 升级无头模式参数:将--headless改为--headless=new,适配新版Chrome的无头模式规范
  • 添加模拟浏览器的User-Agent,规避基础反爬检测

3. 修正ChromeDriver路径

确保chromedriver.exe的路径正确:

  • 若chromedriver在脚本同目录,确认路径./chromedriver.exe无误;否则使用绝对路径(如C:\\tools\\chromedriver.exe)
  • 可将chromedriver放入Python的Scripts目录,直接调用webdriver.Chrome(options=options)无需指定路径

4. 优化页面等待逻辑

原代码的等待逻辑不够严谨,容易出现元素未加载完成就执行操作的情况:

  • 替换implicitly_wait为显式等待(WebDriverWait),针对目标元素设置等待条件

修改后的代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-notification")
options.add_argument("--disable-infobars")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
# 注释掉可能冲突的远程调试端口参数
# options.add_argument("--remote-debugging-port=9230")
# 使用新版无头模式参数
options.add_argument("--headless=new")
# 添加User-Agent模拟正常浏览器
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")

url = 'http://vip.stock.finance.sina.com.cn/mkt/#hs_z'
# 确保chromedriver路径正确,此处假设在同目录
driver = webdriver.Chrome('./chromedriver.exe', options=options)
driver.get(url)

# 使用显式等待,等待搜索框加载完成
wait = WebDriverWait(driver, 15)
search_box = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="inputSuggest"]')))
search_box.clear()
search_box.send_keys('22粤科02')

# 等待搜索按钮并点击
search_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="SSForm"]/input[3]')))
search_btn.click()

额外注意事项

  • 若仍无法打开网站,可尝试关闭无头模式(注释掉--headless=new),查看浏览器窗口中是否有验证码或反爬提示
  • 频繁爬取可能触发新浪财经的反爬限制,建议添加请求间隔(time.sleep(2)),避免被封禁IP

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:25:23