【问题标题】:Error when trying to download jpg files via urllib2 in python尝试在 python 中通过 urllib2 下载 jpg 文件时出错
【发布时间】:2014-02-20 09:08:58
【问题描述】:

我想制作一个程序来从一些网址下载 jpg 文件(日本漫画),我在网上看到了一些示例,但它们在我的情况下不起作用:

import urllib2
jpgfile = urllib2.urlopen("http://mangas2013.centraldemangas.com.br/attack_on_titan/attack_on_titan001-01.jpg")
output = open('attack_on_titan001-01.jpg','wb')
output.write(jpgfile.read())
output.close()

通过这个 url,我得到一个 28kb 的 jpg 文件文件(原始文件是 120kb),当我尝试打开时,图像没有出现在 windows 图片查看器中......这很奇怪,因为我可以下载和查看 jpg 文件从其他网站使用相同的代码...

我是python的新手,所以尽量给我最简单的答案。

【问题讨论】:

  • 可能是服务器试图阻止您下载?
  • 你可以试试requestsrequests.get(url) 然后f.write(response.content)

标签: python download urllib2


【解决方案1】:

您可以尝试使用urllib.urlretrieve() 而不是urllib2.urlopen

import urllib
jpg_filename, headers = urllib.urlretrieve('http://mangas2013.centraldemangas.com.br/attack_on_titan/attack_on_titan001-01.jpg', 'attack_on_titan001-01.jpg')

编辑:我重新阅读了您的问题,但我不确定为什么该网站特别不起作用。这可能是因为您需要通过身份验证才能访问该文件。检查您收到的回复:

import urllib2
jpgfile = urllib2.urlopen("http://mangas2013.centraldemangas.com.br/attack_on_titan/attack_on_titan001-01.jpg")
print jpgfile.getcode()
print jpgfile.read()

这可能是因为缺少身份验证而重定向。

【讨论】:

  • 我得到了同样的错误,你尝试运行你的代码吗?
  • 您很可能需要在该站点上进行身份验证才能访问 jpeg 文件。您可以使用代理服务器和浏览器查看有效请求,以查看该站点用于身份验证的内容,但我确信您违反了某些服务条款。它可能需要设置正确的 cookie 值。查看stackoverflow.com/a/8206372/2337592
  • 我收到一个很长的html代码作为回复,代码来自漫画主页:centraldemangas.com.br/mangas/info/attack-on-titan
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2017-05-14
  • 1970-01-01
  • 2011-09-26
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多