Selenium运行报selenium.common.exceptions.TimeoutException异常如何解决
问题原因及解决方案
1. 无头模式参数配置错误
你当前写的__headless是无效参数,Chrome浏览器正确的无头模式参数为--headless=new(Chrome 112及以上版本推荐),旧版本可使用--headless=chrome,参数前缀是两个横杠不是下划线,参数错误会导致无头模式未生效,甚至影响页面正常加载。
2. 定位逻辑依赖动态哈希类名
你XPATH里写的完整类名panelProduct panelLayout_panelLayout__BDQ6_ view_product__3AOqY中,panelLayout__BDQ6_、view_product__3AOqY这类带随机后缀的类名是前端构建工具自动生成的哈希类,站点更新后随时会变化,直接全量匹配很容易找不到元素。
3. 缺少反爬规避配置
目标站点有基础反爬机制,默认的无头模式Selenium请求会被识别为爬虫,导致商品列表不会正常渲染,自然找不到目标元素触发超时。
4. 可选:消除GPU报错
你日志里的GPU相关报错可以通过添加--disable-gpu参数消除,不影响核心功能但会让日志更干净。
修复后可运行代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options from shutil import which from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import time chrome_options = Options() # 修正无头模式参数 chrome_options.add_argument('--headless=new') # 禁用GPU,消除相关报错 chrome_options.add_argument('--disable-gpu') # 规避Selenium检测 chrome_options.add_argument('--disable-blink-features=AutomationControlled') chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36') chrome_path = which('chromedriver') driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options) driver.set_window_size(1920, 1080) driver.get('https://www.galaxus.ch/search?q=5010533606001') # 修改XPATH为部分匹配类名,不依赖动态哈希后缀 product_tab = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//article[contains(@class, 'panelProduct')]/a"))).click() time.sleep(5) print(driver.current_url) # 可验证是否成功跳转到商品详情页 driver.close()
额外注意点
- 如果还是出现超时,可以适当延长WebDriverWait的等待时长到20秒,部分地区访问境外站点加载速度较慢
- 确保你的Chrome浏览器和chromedriver版本完全匹配,版本差超过2个小版本也可能出现未知加载问题
内容的提问来源于stack exchange,提问作者Raisul Islam
相关产品推荐
相关产品推荐

