简体   繁体   English

Python 请求尝试/排除继续/中断循环

[英]Python Requests try/except continue/break loop

For various reasons I need to put a Requests call inside a try/except/retry loop, rather mounting a retry condition to a requests session.由于各种原因,我需要在 try/except/retry 循环中放置请求调用,而不是将重试条件安装到请求 session。 Expected behaviour is that if a request has been successful, the loop breaks and the code stops.预期的行为是,如果请求成功,则循环中断并且代码停止。 Actual behaviour though is that it repeats the loop from start to finish, with the break statement seemingly having no effect:但实际行为是它从头到尾重复循环,而 break 语句似乎没有效果:

import traceback
import requests
import time

for i in range(0, 15):
    while True:
        try:
            headers ={
            'authority': 'www.wikipedia.org',
            'method': 'GET',
            'path': '/wikipedia.org',
            'scheme': 'https',
            'accept': '*/*',
            'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
            'referer': 'https://google.com',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
            }
            r = requests.get(url='https://wikipedia.org', headers=headers)
            print(i, r.status_code)
        except Exception as exc:
            time.sleep(60)
            print(traceback.format_exc())
            print('continue')
            continue
    
        print('break')
        break
    
    print('Finished')

What do I need to change to get the desired behaviour?我需要更改什么才能获得所需的行为?

Remove while cycle.删除while循环。 while work under for . while for . When python come to break it "break" while cycle.当 python 来break它“打破” while循环。

It's work for me:这对我有用:

import traceback
import requests
import time

for i in range(0, 15):
    try:
        headers ={
        'authority': 'www.wikipedia.org',
        'method': 'GET',
        'path': '/wikipedia.org',
        'scheme': 'https',
        'accept': '*/*',
        'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
        'referer': 'https://google.com',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
        }
        r = requests.get(url='https://wikipedia.org', headers=headers)
        print(i, r.status_code)
    except Exception as exc:
        time.sleep(60)
        print(traceback.format_exc())
        print('continue')
        continue

    print('break')
    break

print('Finished')

try this:尝试这个:

import requests
from requests.exceptions import HTTPError


def get_response(url):

    for i in range(15):
        try:
            response = requests.get(url)
            response.raise_for_status()
            return response.content
        except HTTPError as http_err:
            print(f"HTTP error occurred: {http_err}")
        except Exception as err:
            print(f"Other error occurred: {err}")


url = 'http://google.com'
response = get_response(url)
print(response)
url = 'http://no_valid_address.com'
response = get_response(url)
print(response)

Expected behaviour is that if a request has been successful, the loop breaks and the code stops预期的行为是,如果请求成功,则循环中断并且代码停止

the loop should have 15 attempts at running successfully - at which ever iteration of the loop it is successful at, it should end.循环应该有 15 次成功运行的尝试 - 在它成功的循环迭代中,它应该结束。

You don't need the while block.您不需要while块。 If you want to have 15 attempts or until first successful request, just do it.如果您想尝试 15 次或直到第一次成功请求,请执行此操作。

import random


def random_error():
    if random.random() > 0.2:
        raise Exception


for _ in range(15):
    print('-' * 20)
    try:
        random_error()
    except Exception as exc:
        print('exception raised')
    else:
        print('exception not raised')
        break

print('Finished')


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM