python - urllib.request.urlretrieve 在仅从站点检索一张图片时卡住了
问题描述
python代码(python3)
import time
import urllib.response, requests
from config.dev import CONTENT_IMAGE_UPLOAD
directory = CONTENT_IMAGE_UPLOAD + "en_" + time.strftime('%Y%m%d')
filename = "sample.jpg"
try:
urllib.request.urlretrieve("https://www.miamiherald.com/latest-news/wfeh98/picture238148999/alternates/LANDSCAPE_1140/Screenshot%20(150).png", directory + "/" + filename)
print("image is saved")
except Exception as e:
print(e)
我希望在不到一分钟的时间内获得图像,但它需要too long
打印输出,如下所示。
[Errno 60] Operation timed out
我确定图像已经存在,因为当我复制和粘贴时我得到了图像,但似乎 URL 在这部分包含一些特殊字符Screenshot%20(150).png
,
我该如何解决这个错误?
解决方案
你应该添加用户代理来绕过这个问题,我从不直接使用 urllib 我通常使用请求,因为它对我来说更容易,如果你愿意,你可以使用 urllib 实现相同的概念,但你需要查一下,这里有一个示例代码
import time
import urllib.response, requests
# from config.dev import CONTENT_IMAGE_UPLOAD
headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
# directory = CONTENT_IMAGE_UPLOAD + "en_" + time.strftime('%Y%m%d')
filename = "sample.jpg"
try:
resp = requests.get("https://www.miamiherald.com/latest-news/wfeh98/picture238148999/alternates/LANDSCAPE_1140/Screenshot%20(150).png", headers=headers).content
with open(filename, "wb") as f:
f.write(resp)
print("image is saved")
except Exception as e:
print(e)
这可能会帮助你:)
推荐阅读
- python - MyClass(k=random.randint(1,7) == 1) 是什么意思?
- snakemake - snakemake-wrappers 是否被获取一次并存储在本地?还是每次都从远程 URL 获取?
- c# - 即使在调用“Complete()”之后,C# TransformBlock 也不会运行
- java - JAVA - Apache BEAM- GCP:GroupByKey 与 Direct Runner 一起工作正常,但与 Dataflow runner 一起失败
- python - 如何在 python 中获取我在 Firefox 上打开的页面的 HTML 代码源
- linux - centos系统无法编译lkm
- machine-learning - 我应该首先为支持向量回归算法找到正则化参数或度数吗?
- javascript - 基于 Vue 的数组过滤
- pandas - pd 将多行转置为单列
- http - 如何使用 TCP 发送 HTTP 响应?