【问题标题】:Python3 Urllib image download return HTTP Error 403: ForbiddenPython3 Urllib 图像下载返回 HTTP 错误 403: Forbidden
【发布时间】:2018-09-02 08:18:41
【问题描述】:

我正在做一个 python 项目,我需要从一个 URL 下载一个图像,我用谷歌搜索了很多,尝试了很多解决方案,但对我不起作用。

已更新:现在我已将代码更新为:

from PIL import Image
from flask import Flask
import requests
app = Flask(__name__)


@app.route('/<path:image_url>')
def grab_image(image_url):
    url = str(image_url)
    r = requests.get(url, allow_redirects=True)
    print('Url is as: {}'.format(url))
    filename = url.split('/')[-1]
    open(filename, 'wb').write(r.content)
    img = Image.open(filename)
    img.show()
    return img


if __name__ == '__main__':
    app.run()

现在,它会下载图像并显示它,但不会将图像保存在 我的目录,这里有什么问题?

以下是以前/旧代码。

这是我尝试过的:

from flask import Flask
import urllib.request
app = Flask(__name__)


def download_img(image_url, file_path, file_name):
    full_path = file_path + file_name + '.jpg'
    urllib.request.urlretrieve(image_url, full_path)
    pass


@app.route('/<path:image_url>')
def hello_world(image_url):
    file_name = 'async'
    download_img(image_url, 'img/', file_name)
    return 'Hello World!'


if __name__ == '__main__':
    app.run()

这是我的要求:

http://127.0.0.1:5000/https://www.thelaurelmagazine.com/sites/default/files/styles/hero_image/public/mary_abryani_highlands_nc_yoga.jpg

但它返回此错误:

urllib.error.HTTPError: HTTP Error 403: Forbidden
127.0.0.1 - - [02/Sep/2018 13:13:57] "GET /https://www.thelaurelmagazine.com/sites/default/files/styles/hero_image/public/mary_abryani_highlands_nc_yoga.jpg HTTP/1.1" 500 -

我也尝试过使用http 而不是https,但它返回相同的错误。

请帮帮我!

提前致谢!

【问题讨论】:

  • 您似乎输入错误。查看请求的开头 :) 你有 https twise
  • 嗨@HermanWilén,第二个HTTPhttps 是作为URL 参数传递的,所以这不是错字。

标签: python python-3.x urllib


【解决方案1】:

必须在您发送的请求的标头中指定用户代理。

from flask import Flask
import urllib.request
from PIL import Image
app = Flask(__name__)

user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'


def download_img(image_url, file_path, file_name):
    full_path = file_path + file_name + '.jpg'
    headers={'User-Agent':user_agent,} 
    request=urllib.request.Request(image_url,None,headers)
    response = urllib.request.urlopen(request)
    #install PIL package to convert the response into a PIL Image object to further save it
    image=Image.open(response)
    image.save(full_path)
    pass


@app.route('/<path:image_url>')
def hello_world(image_url):
    file_name = 'async'
    download_img(image_url, 'img/', file_name)
    return 'Hello World!'


if __name__ == '__main__':
    app.run()

【讨论】:

  • 这并不能解决问题,因为 porobljavanja 它的 url 无效。此外,在一般情况下,用户代理必须是标头中的幸存者是不正确的。如果这是需要的特殊情况,答案应该说明这一点。
  • 嗨@ramnithin,它返回另一个错误raise ValueError("unknown url type: %r" % self.full_url) ValueError: unknown url type: 'favicon.ico'
  • 嗨@ramnithin,我已经更新了上面的代码,请看一下!
【解决方案2】:

在之前的回答中我误解了你的问题,对不起。

img.show()

只会尝试在屏幕上显示图像,不会将其保存到工作目录。

你没有关闭你创建的文件,也没有将文件对象的链接分配给任何变量,所以它只是在创建后被垃圾收集器收集

url = str(image_url)
r = requests.get(url, allow_redirects=True)
print('Url is as: {}'.format(url))
filename = url.split('/')[-1]
with open(filename, 'wb') as file:
    file.write(r.content)
return send_file(filename)

url = str(image_url)
r = requests.get(url, allow_redirects=True)
print('Url is as: {}'.format(url))
filename = url.split('/')[-1]
file = open(filename, 'wb')
file.write(r.content)
file.close()
return send_file(filename)

现在应该可以解决您的问题(第一个变体编写使用上下文管理器with,第二个是传统方法)
flask.send_file() docs

另外我建议不要在服务器端使用img.show()(如果您已将项目部署到远程服务器,它将没有影响)

【讨论】:

  • 嗨@AlexKorienev,我已经更新了上面的代码,请看一下!
猜你喜欢
  • 2020-06-22
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 2016-03-19
  • 2018-01-03
相关资源
最近更新 更多