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

Python网络爬虫在SQL Server Agent中运行不稳定故障求助

问题根因
  • 无界面环境兼容问题:当前代码启动Chrome带图形界面,SQL Server Agent服务默认禁用桌面交互,无图形环境下Chrome启动偶尔卡死,符合偶发故障特征,手动执行有桌面环境所以100%成功
  • 权限冲突:SQL Server Agent默认运行身份为LocalSystem服务账号,对Chrome、chromedriver、下载目录、脚本目录的权限不足,上次调度残留的进程由服务账号启动,下次调度无权限操作就会阻塞
  • 代码鲁棒性不足:使用硬编码time.sleep()等待不可靠,服务调度时系统资源波动可能导致页面加载超时,元素查找失败直接报错;无异常捕获逻辑,代码运行中途出错就走不到driver.quit(),残留进程占用资源
  • 路径转义问题:代码中chromedriver = "C:\Script\chromedriver.exe"的反斜杠未转义,可能出现字符串转义冲突,偶发找不到驱动文件的错误
解决方案

1. 修正Chrome启动参数适配无界面环境

更新ChromeOptions配置,新增无头模式等服务环境适配参数:

option = webdriver.ChromeOptions()
# 无头模式,适配无图形界面的服务调度场景
option.add_argument("--headless=new")
# 禁用GPU,避免无头模式渲染异常
option.add_argument("--disable-gpu")
# 禁用沙箱,解决服务账号权限不足导致的启动失败
option.add_argument("--no-sandbox")
# 禁用共享内存,防止资源不足崩溃
option.add_argument("--disable-dev-shm-usage")
prefs = {"download.default_directory" : "C:\\DownloadFolder\\"}
option.add_experimental_option("prefs",prefs)

2. 优化代码鲁棒性与进程清理逻辑

2.1 启动前清理残留进程

导入os模块,脚本启动前先杀死残留的Chrome和chromedriver进程,避免资源占用:

import os
# 清理残留进程,忽略不存在进程的报错
os.popen('taskkill /f /im chromedriver.exe /t 2>nul')
os.popen('taskkill /f /im chrome.exe /t 2>nul')
time.sleep(2)

2.2 替换硬等待为显式等待,添加异常捕获

将固定time.sleep替换为显式等待,用try-finally保证无论是否出错都关闭驱动、清理进程:

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

driver = None
try:
    # 路径添加r前缀避免转义,或使用双反斜杠
    chromedriver = r"C:\Script\chromedriver.exe"
    driver = webdriver.Chrome(executable_path=chromedriver, options=option)
    BASE_URL = "https://www.mywebsite.com"
    driver.get(BASE_URL)
    # 最多等待15秒加载目标元素,超时才报错
    WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, "mypath")))
    link2 = driver.find_element(By.XPATH, "mypath").text
    WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.LINK_TEXT, link2)))
    link = driver.find_element(By.LINK_TEXT, link2)
    link.click()
    # 可根据实际场景替换为下载完成/页面跳转的判断逻辑,减少硬等待
    time.sleep(10)
except Exception as e:
    # 可添加日志输出错误信息,方便后续排查
    print(f"执行出错:{str(e)}")
    sys.exit(1)
finally:
    if driver:
        try:
            driver.quit()
        except:
            pass
    # 执行结束再次清理残留进程
    os.popen('taskkill /f /im chromedriver.exe /t 2>nul')
    os.popen('taskkill /f /im chrome.exe /t 2>nul')
sys.exit(0)

3. 修正SQL Server Agent配置

  • 将SQL Server Agent服务的运行身份改为手动执行脚本成功的Windows用户,确保该账号对C:\Script、C:\DownloadFolder、Python安装目录都有完全控制权限
  • 作业步骤的运行身份选择对应账号,确认命令中的Python路径、脚本路径全部使用绝对路径,工作目录设置为C:\Script

4. 添加日志定位问题

可在脚本中新增日志输出到本地文件,出错后直接查看日志即可定位具体故障点:

import logging
logging.basicConfig(
    filename=r'C:\Script\spider_run.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
# 关键步骤打日志
logging.info("脚本启动,清理残留进程完成")
# 异常时输出详细报错
except Exception as e:
    logging.error(f"执行失败:{str(e)}", exc_info=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 06:00:02