【问题标题】:Save generated image (graph) from url to a file using python使用python将生成的图像(图形)从url保存到文件
【发布时间】:2018-02-12 20:36:37
【问题描述】:

我正在尝试使用 Python 3 自动将生成的图形从 url 保存到图像文件。链接本身不是 .png,但是当我在浏览器中右键单击图像时,它可以保存为 .png图片。我的其余编码已经在 python 中,因为大多数是自动趋势分析,所以我也希望能够在 python 中完成这一步。编码使用输入并更改链接中的日期以下载某些图表。这是我正在努力解决的代码的简化部分。测试用例工作正常,但我要保存的实际文件却不行。

import os
from urllib.request import urlretrieve

Link_Test = "http://www.catster.com/wp-content/uploads/2017/06/small-kitten-meowing.jpg"
Link_Actual = "https://waterdata.usgs.gov/nwis/dv/?ts_id=52441,52442,52443&format=img_stats&site_no=405902087141501&set_arithscale_y=on&begin_date=20161001&end_date=20170930"

urlretrieve(Link_Test, "Test.jpg") #This saves the test picture correctly
urlretrieve(Link_Actual, "JasperCounty.png") #The saved file is unreadable

我尝试了其他下载图片的方法,它们都适用于测试用例,但我找不到将生成的图形下载为图片的方法。谢谢你的帮助!!!

【问题讨论】:

  • 第二个链接在我的浏览器中返回“日期输入不正确。‘最后一个日期’必须在‘第一个日期’之后。”您的浏览器会发生什么?
  • 我的错。我将日期作为变量,当我发布它时,我对其进行了更改以使其变得简单。我编辑了我的帖子以反映这一点。开始日期应该是 2016 年。
  • 但是地址仍然没有指向图片,它存储在under this address 恕我直言,你必须使用web scraper like Beautifulsoup 或Scrapy 来检索它们

标签: python url


【解决方案1】:

在每个链接的页面中搜索图像并保存这些图像可能更有意义,而不是仅依赖 URL

import re
import requests
from bs4 import BeautifulSoup

site = 'https://waterdata.usgs.gov/nwis/dv/?ts_id=52441,52442,52443&format=img_stats&site_no=405902087141501&set_arithscale_y=on&begin_date=20161001&end_date=20170930'

response = requests.get(site)

soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]


for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)
    with open(filename.group(1), 'wb') as f:
        response = requests.get(url)
        f.write(response.content)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    相关资源
    最近更新 更多