【问题标题】:urllib.error.HTTPError: HTTP Error 404: Not Found for a link that I can open in my browserurllib.error.HTTPError:HTTP 错误 404:找不到可以在浏览器中打开的链接
【发布时间】:2020-03-22 19:07:22
【问题描述】:
Iurl = 'https://i7y3a6q5.stackpathcdn.com/media/14490/क-स-न.jpg?width=350&mode=max&animationprocessmode=first'

The above url might generate an error as not all of the characters in it are in Unicode format. So, here's the converted url:

https://i7y3a6q5.stackpathcdn.com/media/14490/%E0%A4%95-%E0%A4%B8-%E0%A4%A8.jpg?width=350&mode=max&animationprocessmode=first

这是导致错误的 url,它是我可以在浏览器中打开的图像的链接。

img = urllib.request.urlopen(Iurl)  # Downloading the image

这是产生 404 错误的语句。 我尝试了针对类似问题提供的解决方案,但没有一个对我有用。 当我打印我的 img 时,我需要这样的东西作为我的输出 ss 包含整个错误堆栈跟踪

【问题讨论】:

  • 无法重现/img = request.urlopen('https://i7y3a6q5.stackpathcdn.com/media/14490/%E0%A4%95-%E0%A4%B8-%E0%A4%A8.jpg?width=350&mode=max&animationprocessmode=first') 返回http状态码200即成功
  • 如果您尝试打印img的内容,它仍然会打印错误404,我也尝试过这种方法。在这里,您不会在外部收到任何错误,但也不会收到任何内容。它应该返回一个包含该图像的对象。
  • 你能把实际的错误贴出来
  • 这是我尝试打印 img 变量时得到的结果。

标签: python python-3.x web-scraping urllib


【解决方案1】:

你应该试试这个。它返回 200 响应并能够将内容打印到控制台。

import requests

url = 'https://i7y3a6q5.stackpathcdn.com/media/14490/क-स-न.jpg?width=350&mode=max&animationprocessmode=first'

img = requests.get(url)
print(img.content)

如果你想把它下载到你的机器上,你可以这样写

import requests
import shutil

url = 'https://i7y3a6q5.stackpathcdn.com/media/14490/क-स-न.jpg?width=350&mode=max&animationprocessmode=first'

with open('image.jpg', 'wb') as output_file, requests.get(url, stream=True) as response:
    shutil.copyfileobj(response.raw, output_file)

【讨论】:

  • 这是我需要的内容类型,这个响应对象包含该图像的数据。
  • 我将内容以字节为单位打印到我的控制台。这是你打印 img.content 时得到的吗?
  • 是的,所以我需要投射内容吗?如果是,那我该怎么做?感谢您的帮助。
【解决方案2】:

您给出的错误无法重现,您应该显示您的代码块和错误/堆栈跟踪的副本。我已经构建了一个简单的示例,说明您所说的尝试这样做并且对我来说效果很好。

import urllib.request

with open("img.jpg", 'wb') as image:
    Iurl = 'https://i7y3a6q5.stackpathcdn.com/media/14490/%E0%A4%95-%E0%A4%B8-%E0%A4%A8.jpg?width=350&mode=max&animationprocessmode=first'
    img = urllib.request.urlopen(Iurl)
    print(f"Fetching url {Iurl}, HTTP Response Code: {img.msg}({img.status})")
    image.write(img.read())

控制台输出

Fetching url https://i7y3a6q5.stackpathcdn.com/media/14490/%E0%A4%95-%E0%A4%B8-%E0%A4%A8.jpg?width=350&mode=max&animationprocessmode=first, HTTP Response Code: OK(200)

这会在我的代码运行的目录中创建一个文件。当我打开文件时,图像就在那里。

【讨论】:

  • 非常感谢您的成功。但我不明白怎么做?我的意思是我实际上在做同样的事情,除了你在代码中提到的打印语句。
猜你喜欢
  • 2022-10-14
  • 2020-11-21
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2012-05-27
  • 1970-01-01
相关资源
最近更新 更多