urllib.error.HTTPError:HTTP错误404:找不到可以在浏览器中打开的链接

2024-10-01 13:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

this is the url that is resulting in an error, it's a link to an image that I can open in my browser.

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

This is the statement which is generating the 404 error. I tried the solutions provided on similar questions but none of them worked for me. I need something like this as my output when I print my img The ss contains the entire error stack trace enter image description here


Tags: theinhttpscomanurlismy
2条回答

你应该试试这个。它返回一个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)

您给出的错误无法再现,您应该显示代码块和错误/堆栈跟踪的副本。我已经建立了一个简单的例子,你说你试图这样做,对我来说很好

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)

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

enter image description here

相关问题 更多 >