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

如何配置WebDriver遇到连接拒绝时跳过列表中的对应URL?

解决Python遍历IoT设备URL时跳过无效链接的方案

核心思路是利用Python的异常捕获机制,在请求每个URL时捕获连接失败、加载超时等异常,遇到错误时跳过当前URL,继续处理列表中的下一个地址。

场景1:使用requests库请求URL

如果你的脚本是用requests直接发送HTTP请求,可按以下方式修改:

import requests

iot_urls = ["http://192.168.1.1", "http://192.168.1.2", "http://192.168.1.3"]

for url in iot_urls:
    try:
        # 自定义超时时间,避免长时间等待
        response = requests.get(url, timeout=5)
        # 这里写你的设备信息收集逻辑
        print(f"成功获取{url}的信息")
    except requests.exceptions.ConnectionError:
        print(f"连接被拒绝:{url}")
        continue
    except requests.exceptions.Timeout:
        print(f"请求超时:{url}")
        continue
    except Exception as e:
        # 捕获其他未预料到的异常
        print(f"{url}处理出错:{str(e)}")
        continue

场景2:使用Selenium操控浏览器

针对你遇到的WebDriverException(比如net::ERR_CONNECTION_REFUSED),可以捕获Selenium相关异常,确保脚本不终止:

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

iot_urls = ["http://192.168.1.1", "http://192.168.1.2", "http://192.168.1.3"]
driver = webdriver.Chrome()

for url in iot_urls:
    try:
        driver.get(url)
        # 这里写你的设备信息收集逻辑
        print(f"成功加载{url}")
    except WebDriverException as e:
        if "ERR_CONNECTION_REFUSED" in str(e):
            print(f"连接被拒绝:{url}")
        else:
            print(f"{url}加载出错:{str(e)}")
        continue
    except TimeoutException:
        print(f"{url}加载超时")
        continue

driver.quit()

关键说明

  • 尽量精准捕获特定异常(比如ConnectionError、WebDriverException),避免用except Exception直接捕获所有异常,方便排查真正的问题。
  • 设置合理的超时时间,避免脚本在无效链接上浪费过多时间。
  • 若使用Selenium,遇到异常后无需重启浏览器,直接继续请求下一个URL即可;如果浏览器状态异常,可在except块中添加driver.refresh()或重新打开标签页的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:15:39