Python爬虫requests判断请求超时并重新post/get发送请求


在使用Python爬虫中,你可以使用requests

import requests
#Python爬虫requests判断请求超时并重新post发送请求,proxies为代理
def send_request_post(url, data, headers , proxies , max_retries=3, timeout=5):
    retries = 0
    while retries < max_retries:
        try:
            # 去掉警告
            requests.packages.urllib3.disable_warnings()
            response = requests.post(url=url, json=data, headers=headers , verify=False, proxies=proxies,timeout=timeout)
            if response.status_code == 200:
                # 请求成功,返回响应
                return response
        except requests.exceptions.Timeout:
            print(f"POST请求超时,正在进行第 {retries + 1} 次重试...")
        except requests.exceptions.RequestException as e:
            print(f"请求发生异常:{e}")
        retries += 1

    print("请求失败,达到最大重试次数。")
    return None

#Python爬虫requests判断请求超时并重新get发送请求,
def send_request_get(url, max_retries=3, timeout=5):
    retries = 0
    while retries < max_retries:
        try:
            response = requests.get(url, timeout=timeout)
            if response.status_code == 200:
                # 请求成功,返回响应
                return response
        except requests.exceptions.Timeout:
            print(f"GET请求超时,正在进行第 {retries + 1} 次重试...")
        except requests.exceptions.RequestException as e:
            print(f"请求发生异常:{e}")
        retries += 1

    print("请求失败,达到最大重试次数。")
    return None
#示例:get获取代理ip
def get_ip():
    response = send_request_get('http:/xxxxxxxxxxxxxx/tip')
    if response:
        data = json.loads(response.text)
           proxies = {
         "http": "http://%(proxy)s" % {"proxy": data["ip"]}, 
         "https": "http://%(proxy)s" % {"proxy": data["ip"]}
            }
           return proxies
#示例post
send_request_post(url, data, headers, proxies)

在上面的示例中,send_request_get函数接受一个URL作为参数,并可选地指定最大重试次数和超时时间。函数使用requests.get发送GET请求,并设置了超时时间为5秒。如果请求超时,会捕获requests.exceptions.Timeout异常,并输出重试信息。如果发生其他异常,会捕获requests.exceptions.RequestException并输出相关信息。

你可以调整max_retriestimeout的值来适应需求。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫中,requests库是非常常用的一个库,它提供了简洁而强大的API来发送HTTP请求。对于使用requests库进行爬虫,以下是一些基本操作和高级用法的介绍: 基本操作: 1. 安装requests库:使用pip命令可以安装requests库,例如:`pip install requests`。 2. 导入requests库:在Python脚本中导入requests库,例如:`import requests`。 3. 发起GET请求:使用requests库的get方法可以发起GET请求,例如:`response = requests.get(url)`。 4. 发起POST请求:使用requests库的post方法可以发起POST请求,例如:`response = requests.post(url, data)`。 5. 响应内容:通过response对象可以获取请求的响应内容,例如:`response.text`返回响应内容的字符串形式。 高级用法: 1. 请求头部信息:可以通过headers参数来设置请求头部信息,例如:`headers = {"User-Agent": "Mozilla/5.0"}`,然后将headers作为参数传入GET或POST请求中。 2. 发送参数:可以通过params参数来发送请求参数,例如:`params = {"key": "value"}`,然后将params作为参数传入GET请求中。 3. 发送数据:可以通过data参数来发送POST请求的数据,例如:`data = {"key": "value"}`,然后将data作为参数传入POST请求中。 4. 文件上传:可以通过files参数来上传文件,例如:`files = {"file": open("filename", "rb")}`,然后将files作为参数传入POST请求中。 5. 超时设置:可以通过timeout参数来设置请求超时时间,例如:`timeout = 5`,表示设置超时时间为5秒。 6. 会话管理:可以使用Session对象来管理会话,例如:`session = requests.Session()`,然后可以使用session对象发送多个请求,会话对象会自动保存和使用Cookies信息。 7. 重定向处理:可以通过allow_redirects参数来控制是否允许重定向,默认为True,可以设置为False来禁止重定向。 8. SSL验证:可以通过verify参数来控制SSL证书验证,默认为True,可以设置为False来禁止验证。 总结:以上是Python爬虫中使用requests库的一些基本操作和高级用法。你可以根据具体的需求来选择合适的方法和参数来发送HTTP请求,并获取响应内容。记得根据实际情况进行异常处理和错误判断,以保证爬虫的稳定性和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值