【问题标题】:Getting forbidden error from code downloading image from web从网络下载图像的代码中出现禁止错误
【发布时间】:2021-09-15 04:33:16
【问题描述】:
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")

我在这里做错了什么?

【问题讨论】:

  • 一些网站不允许从那里下载图片。有很多方法可以伪装成浏览器。探索它

标签: python function urllib urlretrieve


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 2014-12-26
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多