首页 > 解决方案 > 通过 Python 的 urllib 保存 GIF 文件

问题描述

请注意,我使用的是以下版本的 Python:

(venv) C:\Users\NBenton\PycharmProjects\RES3D_BETA>python Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32

我尝试使用以下两个脚本通过 URL 下载单个 GIF 文件。

1)

from urllib.request import urlretrieve

urlretrieve('http://www.iframeapps.dcnr.state.pa.us/topogeo/PaGWIS_search/DisplayReportImage.aspx?id=IM209132',
            "C:/Users/NBenton/PycharmProjects/RES3D_BETA/image1.gif")

2)

from urllib import request

request.urlretrieve("http://www.iframeapps.dcnr.state.pa.us/topogeo/PaGWIS_search/DisplayReportImage.aspx?id=IM209132",
                    "image2.gif")

对于这些脚本中的每一个,该过程都以退出代码 0 结束 - 因此,据我所知,没有发生任何灾难性事件。

但是,两个输出文件(image1.gif 和 image2.gif)在查看每个文件时都是这样显示的:

输出

任何人都可以对这个问题提供一些见解吗?确实类似(几乎相同)的情况在stackoverflow上,但不是这样。

标签: pythonurllib

解决方案


检索到的 URL 不是图像源,而是包含图像的 HTML 文档。

当您运行(或在浏览器中打开 URL)时:

curl http://www.iframeapps.dcnr.state.pa.us/topogeo/PaGWIS_search/DisplayReportImage.aspx?id=IM209132

src您可以在文档的源文档中查看图像。

<!--...-->
<div style="text-align: center;">
    <img id="imgPhoto" src="./WellReports/<maskedpath>/IM209132.gif" width="100%" border="0" />
</div>

图像的src显示它的位置是相对于 URL 路径的,即

http://www.iframeapps.dcnr.state.pa.us/topogeo/PaGWIS_search/WellReports/<maskedpath>/IM209132.gif

推荐阅读