首页 > 解决方案 > 使用 request.get 时如何跳过字符串中的错误 url?

问题描述

我有一串 url 链接到我试图下载的 pdf。有些网址不好,但我的字符串有 41,000 长,所以我想使用 requests.get 的例外来传递这些网址并继续搜索和下载列表中的下一个。

我试过使用下面的 except 函数,我也尝试过其他一些格式和位置,但我似乎无法让它发挥作用。

try:
    r = requests.get(url, allow_redirects=True)
    r.raise_for_status()
    with open(('file'+str(u)+'.pdf'),"wb") as code:
            code.write(r.content)
    print("pdf")
except requests.exceptions.HTTPError as err:
    print(err)
    sys.exit(1)

发生错误时,我会得到这种读数:

requests.exceptions.SSLError: HTTPSConnectionPool(host=

(Caused by SSLError(CertificateError("hostname

标签: pythonpython-3.xexceptionpython-requests

解决方案


尝试这个 :)


# urls is the list of url
for url in urls:

    try:
        r = requests.get(url, allow_redirects=True)
        r.raise_for_status()
        with open(('file'+str(u)+'.pdf'),"wb") as code:
            code.write(r.content)
        print("pdf")

    except requests.exceptions.HTTPError as err:
        print('[http_error]: {}'.format(err))

    except requests.exceptions.SSLError as bad_url:
        print('[bad_url]: {}'.format(bad_url))

    except Exception as e:
        print('[error]: {}'.format(e))



推荐阅读