为什么在 Python 中使用 requests 模块时会出现 ChunkedEncodingError 错误?

Han*_*nes 2 python pubmed python-requests

https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi 我尝试使用这些参数查询此 API?db=mesh&id=68016019 所以整个 URL 是https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=mesh&id=68016019 在 Postman 中执行此操作时一切正常并且输出符合预期:

1: Survival Analysis
A class of statistical procedures for estimating the survival function (function 
of time, starting with a population 100% well at a given time and providing the
percentage of the population still well at later times). The survival analysis is
then used for making inferences about the effects of treatments, prognostic
etc.
*
*
*
Run Code Online (Sandbox Code Playgroud)

但是当我尝试通过 Python 中的 requests 模块查询时,我收到此错误:

("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))
Run Code Online (Sandbox Code Playgroud)

那么我到底在做什么呢?我只是触发这个命令:

response2 = requests.get(
        "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=mesh&id=" + str(id))
Run Code Online (Sandbox Code Playgroud)

(id 被转换为字符串,因为当我不这样做时会遇到一些问题。)对于 99.9% 的情况,这种方法绝对没问题,但也有 0.1% 的情况我迷失了。我不明白这个 ChunkedEncodingError 是关于什么的。

这个错误是来自 API 还是我的脚本?有人可以帮忙吗?

我尝试在 Postman 中查询 -> 它有效 我尝试在一个完整的新脚本中从我的脚本执行相同的查询 -> 它有效(???)

但为什么不在我原来的剧本中呢?

lar*_*sks 5

如果您偶尔收到ChunkedEncodingError,您可以在这种情况下实现一些重试逻辑:

像这样的事情会重试给定的 URL 3 次(每次重试之间暂停 1 秒):

import requests
import time

article_id=68016019

for attempt in range(3):
    try:
        res = requests.get(
            f"https://eutils.ncbi.nlm.nih.gov/entre/eutils/efetch.fcgi?db=mesh&id={article_id}")
        break
    except requests.exceptions.ChunkedEncodingError:
        time.sleep(1)
else:
    print("Failed to retrieve url")
Run Code Online (Sandbox Code Playgroud)

显然,您希望实现更好的错误处理,而不是简单地打印消息并继续。