gpt4 book ai didi

python - 未在 except block 中捕获错误

转载 作者:行者123 更新时间:2023-12-04 17:21:15 29 4
gpt4 key购买 nike

我正尝试在 Python 中捕获以下错误的错误,但我无法这样做:

from app_store_scraper import AppStore
import requests
import logging

logger = logging.getLogger()

try:
minecraft = AppStore(country='sk', app_name='telekom')
minecraft.review(how_many=20)
reviews = (minecraft.reviews)
print(reviews)
except AttributeError:
logging.error("Please check the appname")
except requests.exceptions.ConnectionError:
logging.error("Connection error1")
except requests.TooManyRedirects:
logging.error("Connection error2")
except requests.RequestException:
logging.error("Connection error3")
except Exception as e:
logging.error("xxxxxxxxxxxxxxxxxxxxxxx")

错误:

 Something went wrong: HTTPSConnectionPool(host='amp-api.apps.apple.com', port=443): Max retries exceeded with url: /v1/catalog/sk/apps/1106471260/reviews?l=en-GB&offset=0&limit=20&platform=web&additionalPlatforms=appletv%2Cipad%2Ciphone%2Cmac (Caused by ResponseError('too many 404 error responses'))

但是它没有在任何 except block 中被捕获。

注意:我正在使用 Python 中的 apple app scraper 库来抓取数据。

最佳答案

基本思想是捕获从 app_store_scraper 库(由其 Base 类定义的记录器)中发出的记录器输出并引发重试错误的手动异常:

from app_store_scraper import AppStore
import logging
from io import StringIO
import urllib3
import sys


tmp_stderr = StringIO()

log_stream = StringIO()
log_handler = logging.StreamHandler(stream=log_stream)
log_handler.setLevel(logging.ERROR)
loggerBase = logging.getLogger("Base")
base_handlers = [oh for oh in loggerBase.handlers]

class ModifyLogger():
def __init__(self, stder, tmpstrm):
self.stder = stder
self.tmpstrm = tmpstrm

def __enter__(self):
#logging.disable(logging.ERROR)
sys.stderr = self.tmpstrm # redirecting stderr

# Removing existing handlers for "Base" logger and adding our own
for oh in base_handlers:
loggerBase.removeHandler(oh)
loggerBase.addHandler(log_handler)
loggerBase.setLevel(logging.ERROR)

def __exit__(self, exit_type, exit_value, exit_traceback):
#logging.disable(logging.NOTSET)
# Removing our handler for "Base" logger and adding originals back
loggerBase.removeHandler(log_handler)
for oh in base_handlers:
loggerBase.addHandler(oh)

sys.stderr = self.stder # restoring stderr


with ModifyLogger(sys.stderr, tmp_stderr): # a context manager
try:
minecraft = AppStore(country='sk', app_name='telekom')
minecraft.review(how_many=20)
reviews = (minecraft.reviews)
print(reviews)

logs = log_stream.getvalue()
if len(logs.split('\n'))==2 and logs.find('HTTPSConnectionPool', 0, 100) and logs.find('Max retries exceeded', 0, -1):
# Extracting the URL
url1 = logs.split('=')[1].split(',')[0].strip("'").strip()
url2 = logs.split(':')[3].split('(')[0].strip()
# Raising a manual exception for maximum retries
raise urllib3.exceptions.MaxRetryError(pool='HTTPSConnectionPool', url=url1+url2, reason='Max Retries exceeded')

except urllib3.exceptions.MaxRetryError as e:
print('\"{}\" while accessing URL: {}'.format(e.reason, e.url))

以上代码的输出:

[]
"Max Retries exceeded" while accessing URL: amp-api.apps.apple.com/v1/catalog/sk/apps/1106471260/reviews?l=en-GB&offset=0&limit=20&platform=web&additionalPlatforms=appletv%2Cipad%2Ciphone%2Cmac

关于python - 未在 except block 中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66121449/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com