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

请求失败时自动重试:网页内容获取代码问题求助

解决连接失败自动重试的问题

要让你的代码在连接失败时自动重试,需要添加异常捕获和重试逻辑,同时修正headers里的拼写错误,具体修改如下:

修改后的完整代码

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
import time

url = 'https://website.com'

def get_page_content(url, head, max_retries=3, retry_delay=2):
    """
    带自动重试功能的网页内容获取函数
    """
    for attempt in range(max_retries):
        try:
            req = Request(url, headers=head)
            response = urlopen(req)
            return response
        except HTTPError as e:
            # 区分HTTP状态码:5xx服务器错误重试,4xx客户端错误直接抛出
            if 500 <= e.code < 600:
                print(f"请求失败,状态码{e.code},第{attempt+1}次重试中...")
                time.sleep(retry_delay)
            else:
                # 4xx错误(如403、404)属于客户端问题,重试无效,直接抛出
                raise e
        except URLError as e:
            print(f"网络连接失败:{e.reason},第{attempt+1}次重试中...")
            time.sleep(retry_delay)
    # 所有重试均失败,抛出最终异常
    raise Exception(f"经过{max_retries}次重试后仍无法连接到{url}")

# 修正headers拼写错误:'refere' -> 'Referer'
head = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Accept-Encoding': 'none',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive',
    'Referer': 'https://example.com',
    'cookie': "your cookie value ( you can get that from your web page)"
}

try:
    data = get_page_content(url, head).read()
    # 这里可以添加data的后续处理逻辑
except Exception as e:
    print(f"最终请求失败:{e}")

关键修改说明

  • 异常捕获与重试逻辑:通过for循环控制重试次数,捕获网络连接错误(URLError)和HTTP状态码错误(HTTPError),失败后等待指定时间再重试
  • 错误类型区分:针对5xx系列服务器错误重试(这类错误多为临时故障),4xx系列客户端错误直接抛出(重试无法解决)
  • headers修正:原代码中'refere'是拼写错误,正确字段名为'Referer',拼写错误可能导致目标网站拒绝请求
  • 异常兜底:所有重试失败后抛出明确异常,避免程序静默崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:53:44