爬虫系列6下载一个网页(异常处理,用户代理,重试次数)

本文介绍了一个简单的网页下载器实现过程,包括基本下载、异常处理、重试机制及用户代理设置等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
import urllib2
# 下载网页
def download(url):
    return urllib2.urlopen(url).read()

# 可能会遇到一些无法遇见的错误,可能会抛出异常

# 捕捉异常版
def download(url):
    print 'Downloading:', url
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print 'Download Error:', e.reason
        html = None
    return html

# 重试下载版(有些错误是临时的,我们可以尝试重新下载,5xx服务器端问题)
def download(url, num_retries=2):
    print 'Downloading:',url
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print 'Download Error:', e.reason
        html = None
        if num_retries > 0:
            if hasattr(e, 'code') and 500 <= e.code < 600:
                return download(url, num_retries-1)
    return html

# 设置用户代理,重试次数
def download(url, user_aget='wswp', num_retries=2):
    print 'Downloading:',url
    headers = {'User-agent':user_aget}
    request = urllib2.Request(url, headers=headers)
    try:
        html = urllib2.Request(request).read()
    except urllib2.URLError as e:
        print 'Download Error:', e.reason
        html = None
        if num_retries > 0:
            if hasattr(e, 'code') and 500 <= e.code < 600:
                return download(url, num_retries-1)
    return html
### 解决爬虫网络不稳定的方法 为了应对网络不稳定带来的挑战,可以采取多种策略来增强爬虫程序的鲁棒性和稳定性。以下是几种有效的方式: #### 重试机制 实现一个合理的重试逻辑对于处理临时性的网络错误至关重要。可以通过设置最大重试次数和指数退避算法来减少频繁失败的影响。 ```python import time from requests import RequestException def fetch_with_retry(url, max_retries=5): retries = 0 while retries < max_retries: try: response = session.get(url) if response.status_code == 200: return response.text except RequestException as e: print(f"Request failed with exception {e}, retrying...") retries += 1 wait_time = (2 ** retries) + random.random() * 0.5 time.sleep(wait_time) raise Exception("Max retries exceeded") ``` #### 动态切换代理IP 由于代理IP可能随时失效,在检测到异常情况时自动更换新的可用代理是非常必要的措施之一[^1]。 ```python proxies_pool = ["http://proxy1.example.com", "http://proxy2.example.com"] def get_random_proxy(): return {"http": random.choice(proxies_pool), "https": random.choice(proxies_pool)} response = session.get(target_url, proxies=get_random_proxy()) if not is_valid_response(response): # 自定义函数判断响应是否正常 change_to_new_proxy() ``` #### 设置超时参数 适当调整HTTP请求中的timeout参数有助于防止长时间挂起的情况发生,并能及时终止无响应的任务。 ```python session = requests.Session() try: resp = session.get('http://example.org', timeout=(connect_timeout, read_timeout)) except TimeoutError: handle_timeout_error() ``` #### 日志记录与监控报警 完善的日志系统可以帮助追踪问题根源;而实时监测则可以在第一时间发现潜在风险并向相关人员发出警报。 通过上述方法组合运用,可大大提高爬虫面对复杂多变互联网环境下的适应能力,从而保障数据采集工作的连续性和准确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆豆orz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值