在停止脚本之前捕获 400 Bad 请求

Catch the 400 Bad request before stopping the script

我下载了这样的文件,有时 returns 400 请求。

f = urllib.request.urlretrieve(url,"filename")

所以我想检查是否returns 400错误,跳过并继续下一步。

但是如果它 returns 400 ,程序将停止并出现此错误。

urllib.error.HTTPError: HTTP Error 400: Bad Request

如何才能不让 400 error 停止程序?

使用 try catch 块。假设 urllib 已经导入

try: 
    f = urllib.request.urlretrieve(url,"filename")
except urllib.error.HTTPError as e:
    print("Error: ", e)