为什么 urllib.request 这么慢?

Why is urllib.request so slow?

当我使用 urllib.request.decode 从 JSON 格式获取 python 字典时,它花费的时间太长了。但是看了数据,我才发现,我根本不想全部。

  1. 有什么办法只能获取部分数据,例如从 JSON 字典的一个键中获取数据,而不是从所有的键中获取数据?
  2. 或者,是否有任何更快的方法来获取同样有效的数据?
  3. 还是仅仅是连接问题,无法解决?
  4. 也是 urllib.request.urlopen 的问题,还是 json.loads.read().decode() 的问题。

问题的主要症状 是在尝试接收信息时花费大约 5 秒,而这些信息甚至不是那么多(不到 1 页非格式化字典)。另一个症状是,当我尝试接收越来越多的信息时,有时我根本没有收到网页的任何响应!

占用时间最多的2行是:

response = urllib.request.urlopen(url) # url is a string with the url
data = json.loads(response.read().decode())

关于这是什么的一些上下文,我正在使用 Edamam 食谱 API。

不胜感激。

Is there any way that I can only get some of the data, for example get the data from one of the keys of the JSON dictionary rather than all of them?

您可以尝试使用流式 json 解析器,但我认为您不会因此获得任何加速。

Alternatively, if there was any faster way to get the data that could work as well?

如果您必须从 url 检索 json 文档并解析 json 内容,我无法想象有什么比发送 http 请求、阅读响应内容并解析。

Or is it simply a problem with the connection and cannot be helped?

鉴于您提到的数字,问题确实出在网络部分,这意味着您的 python 进程和服务器进程之间的任何问题。请注意,这包括您的整个系统(proxy/firewall、您的网卡、您的 OS tcp/ip 堆栈等,可能还有 window 上的一些防病毒软件)、您的网络本身,以及当然,终端服务器有时可能很慢或有点过载,或者只是故意限制您的请求以避免过载。

Also is the problem with the urllib.request.urlopen or is it with the json.loads or with the .read().decode().

不在你自己的机器上计时,我们怎么知道?但是可以很容易地检查出来,只需计算各个部分的执行时间并记录它们。

The other symptom is that as I try to receive more and more information, there is a point when I simply receive no response from the webpage at all!

cf 以上 - 如果您连续发送数百个请求,服务器可能会限制您的请求以避免过载(大多数 API 端点将以这种方式运行)或者只是过载。您是否至少检查了 http 响应状态代码?您可能会收到 503(服务器过载)或 429(太多请求)响应。