从网络下载图像的代码中出现禁止错误

import random
import urllib.request

def download_web_image(url):
  name = random.randrange(1,1000)
  full_name = str(name) + ".jpg"
  urllib.request.urlretrieve(url,full_name)

download_web_image("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg")

我在这里做错了什么?

iCMS 回答:从网络下载图像的代码中出现禁止错误

使用请求模块的更兼容方法如下:

import random
import requests

def download_web_image(url):
    name = random.randrange(1,1000)
    full_name = str(name) + ".jpg"
    r = requests.get(url)
    with open(f'C:\\Test\\{full_name}','wb') as outfile:
        outfile.write(r.content)

download_web_image("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg")

还要确保将 f'C:\\Test\\{full_name}' 修改为您想要的输出文件路径。并且一定要注意导入的模块从 import urllib.request 变成了 import requests

本文链接:https://www.f2er.com/153855.html

大家都在问