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

Selenium WebDriver无限挂起、Python脚本卡顿,如何抛异常并处理?

解决Selenium WebDriver无限挂起的异常触发方案

嘿,我来帮你搞定这个Selenium无限挂起的问题!你遇到的这种脚本卡住不动的情况,多半是页面加载时某个资源一直处于pending状态,或者WebDriver本身僵住了。下面给你几个实用的方案,能让脚本在超时后自动触发异常,不会一直死等:

1. 给WebDriver配置关键超时参数

不管你用PhantomJS还是ChromeDriver,先把这些超时参数配上,这是最基础的解决办法:

针对你正在用的PhantomJS(补充优化你的现有代码)

你已经加了resourceTimeout,但还得补上其他几个超时设置,才能全方位覆盖:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

url = "http://collegeofdesign.info/?page_id=9"

# 配置PhantomJS的能力参数
caps = webdriver.DesiredCapabilities.PHANTOMJS
# 资源请求超时(10秒,单位是毫秒)
caps["phantomjs.page.settings.resourceTimeout"] = 10000
# 页面加载策略设为"none",不用等页面完全加载完
caps["pageLoadStrategy"] = "none"
# 页面整体加载超时(10秒)
caps["phantomjs.page.settings.loadTimeout"] = 10000

browser = webdriver.PhantomJS(desired_capabilities=caps)
# 脚本执行超时(15秒,防止JS卡死)
browser.set_script_timeout(15)
# 页面加载超时(15秒)
browser.set_page_load_timeout(15)

try:
    browser.get(url)
    # 这里可以加显式等待,比如等页面里的关键元素出现后再操作,避免提前执行下一步
except TimeoutException as e:
    print("页面加载超时啦,触发异常:", e)
    # 一定要记得清理浏览器进程,避免残留
    browser.quit()

如果你切换回ChromeDriver(更推荐,因为PhantomJS已经停更了)

ChromeDriver的稳定性更好,配合这些设置能大幅减少卡住概率,还能禁用不必要的资源加载:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException

url = "http://collegeofdesign.info/?page_id=9"

chrome_options = Options()
# 禁用图片、CSS(根据你的需求调整,减少加载压力)
chrome_options.add_argument("--blink-settings=imagesEnabled=false")
chrome_options.add_argument("--disable-css")
# 页面加载策略设为none,不等待完全加载
chrome_options.page_load_strategy = "none"

driver = webdriver.Chrome(options=chrome_options)
# 页面加载超时10秒
driver.set_page_load_timeout(10)
# 脚本执行超时10秒
driver.set_script_timeout(10)
# 隐式等待5秒(找不到元素时的等待时间)
driver.implicitly_wait(5)

try:
    driver.get(url)
    # 可以加显式等待,比如等body元素出现再继续
    # from selenium.webdriver.support.ui import WebDriverWait
    # from selenium.webdriver.common.by import By
    # WebDriverWait(driver, 10).until(lambda x: x.find_element(By.TAG_NAME, "body"))
except TimeoutException as e:
    print("触发超时异常:", e)
    driver.quit()

2. 用Python的超时兜底方案(终极手段)

如果WebDriver本身僵住了,连超时参数都不生效,那可以用Python的signal模块给整个请求块设置强制超时,到点直接触发异常:

import signal
from selenium import webdriver
from selenium.common.exceptions import TimeoutException

# 自定义超时异常类
class TimeoutError(Exception):
    pass

def timeout_handler(signum, frame):
    raise TimeoutError("请求超时,强制终止!")

# 设置15秒的超时时间
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(15)

try:
    url = "http://collegeofdesign.info/?page_id=9"
    driver = webdriver.PhantomJS()
    driver.get(url)
    # 你的后续操作
    signal.alarm(0)  # 操作完成后取消超时
except TimeoutError as e:
    print(e)
    driver.quit()
except TimeoutException as e:
    print("WebDriver超时:", e)
    driver.quit()

注意:这个方案在Windows系统上不支持signal.SIGALRM,可以改用threading模块实现类似的超时功能哦。

3. 排查页面本身的问题

你可以先手动打开目标URL,看看是不是页面里有一直加载的第三方资源(比如广告、统计脚本),如果是,可以在WebDriver里拦截这些请求:

  • PhantomJS可以通过配置自定义请求头或者代理拦截
  • ChromeDriver可以用DevTools协议(CDP)阻止特定域名的请求,比如:
# 阻止广告和统计脚本的请求
driver.execute_cdp_cmd('Network.setBlockedURLs', {"urls": ["*.ads.com", "*.analytics.com"]})
driver.execute_cdp_cmd('Network.enable', {})

最后提一句:PhantomJS已经停止维护好几年了,稳定性不如ChromeDriver/FirefoxDriver,建议尽量切换到后者哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:04:05