请求模块速度慢,因为正在重新编码

2024-09-28 05:42:45 发布

您现在位置:Python中文网/ 问答频道 /正文

python中的模块请求在尝试猜测编码时变得非常慢(至少使用编码ISO-8859-1)

import requests
url = 'https://geoportal.minetur.gob.es/VCTEL/infoantenasGeoJSON.do?idCapa=null&bbox=-1.5525697885398,39.26519497205,-1.549179476345,39.273649294864&zoom=4'
r = requests.get(url)

这需要2分钟以上

import os
url = 'https://geoportal.minetur.gob.es/VCTEL/infoantenasGeoJSON.do?idCapa=null&bbox=-1.5525697885398,39.26519497205,-1.549179476345,39.273649294864&zoom=4'
url2 = url.replace("&", "\&")
os.system(f"curl {url2} > ./fast_answer")
with open("./fast_answer", "r", encoding = "ISO-8859-1") as f:
    data = f.read()
j = json.loads(data)

这需要不到1秒的时间

我知道curl可能比请求快,但2分钟比1秒太多了。这是我这边的问题还是一个requestsbug


Tags: httpsimporturl编码esisorequestsdo
1条回答
网友
1楼 · 发布于 2024-09-28 05:42:45

如果仍然存在此问题,也可以尝试urllib.urlopen(url):

from urllib.request import urlopen  
url = urlopen('https://geoportal.minetur.gob.es/VCTEL/infoantenasGeoJSON.do?idCapa=null&bbox=-1.5525697885398,39.26519497205,-1.549179476345,39.273649294864&zoom=4')
print(url.read())

关于您的“比较问题”,requests包尝试从header()中猜测编码,并且可能会花费时间在上面。您可以设置它并检查它是否有所改进:

import requests
url = 'https://geoportal.minetur.gob.es/VCTEL/infoantenasGeoJSON.do?idCapa=null&bbox=-1.5525697885398,39.26519497205,-1.549179476345,39.273649294864&zoom=4'
r = requests.get(url)
r.encoding = 'ISO-8859-1'
print(r.text)

相关问题 更多 >

    热门问题