Selenium自动化遭站点检测:jQuery阻塞及PR_CONNECT_RESET_ERROR求助
问题排查与解决方案
核心问题分析
点击「gerar 2a via」按钮后页面冻结、出现jQuery错误,刷新返回PR_CONNECT_RESET_ERROR,本质是目标站点的反爬机制拦截了自动化请求,或浏览器环境与真实用户差异过大,导致请求被服务器主动断开,静态资源加载异常引发JS报错。
1. 优化浏览器配置,模拟真实用户环境
针对Firefox完善启动配置,隐藏自动化特征、补全环境参数,缩小与真实浏览器的差异:
from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.desired_capabilities import DesiredCapabilities options = Options() # 隐藏webdriver核心特征 options.set_preference("dom.webdriver.enabled", False) options.set_preference('useAutomationExtension', False) # 禁用弹窗、通知,避免干扰页面流程 options.set_preference("dom.disable_open_during_load", True) options.set_preference("dom.webnotifications.enabled", False) # 设置站点匹配的葡萄牙语环境 options.set_preference("intl.accept_languages", "pt-BR,pt") # 允许加载图片、样式表,防止静态资源缺失引发jQuery错误 options.set_preference("permissions.default.image", 1) options.set_preference("permissions.default.stylesheet", 1) # 处理SSL证书兼容性问题 desired_caps = DesiredCapabilities.FIREFOX.copy() desired_caps['acceptInsecureCerts'] = True desired_caps['acceptSslCerts'] = True # 替换真实浏览器UA,避免被识别为自动化工具 profile = webdriver.FirefoxProfile() profile.set_preference("general.useragent.override", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0") options.profile = profile driver = webdriver.Firefox(options=options, desired_capabilities=desired_caps) driver.get('https://iptu.prefeitura.sp.gov.br/')
2. 优化按钮点击逻辑,避免请求拦截
使用JS点击替代原生点击,同时添加显式等待确保元素可交互,捕获JS错误定位问题:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待按钮加载完成再操作 btn_gerar = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//*[@id="btnGerarSegundaVia"]')) ) # 用JS点击绕过部分点击拦截 driver.execute_script("arguments[0].click();", btn_gerar) # 等待页面响应,同时捕获JS错误 try: # 替换为生成成功后会出现的元素ID/选择器 WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.ID, 'resultadoGeracao')) ) except Exception as e: # 打印页面中的JS错误信息 js_errors = driver.execute_script("return window.JavaScriptErrors || [];") print("页面JS错误:", js_errors)
3. 排查网络层面问题
PR_CONNECT_RESET_ERROR大概率是IP被站点封禁,可更换代理(需支持HTTPS):# 配置HTTPS代理(替换为有效代理) PROXY_HOST = "xxx.xxx.xxx.xxx" PROXY_PORT = "xxxx" options.set_preference("network.proxy.type", 1) options.set_preference("network.proxy.https", PROXY_HOST) options.set_preference("network.proxy.https_port", int(PROXY_PORT))- 先手动访问站点测试:确认是否需要填写前置表单(如房产编号、证件号)才能点击按钮,当前代码仅打开首页,可能缺少必要的前置操作。
4. 检查反爬细节
- 点击按钮后是否弹出验证码?需补充验证码识别或人工介入逻辑。
- 站点是否有会话验证机制?可尝试保存手动登录的Cookie,在自动化中加载复用。
内容的提问来源于stack exchange,提问作者Jean Carlo
相关产品推荐
相关产品推荐

