python - 从网络下载图像的代码中出现禁止错误
问题描述
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")
我在这里做错了什么?
解决方案
使用请求模块的更兼容的方法如下:
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
.
推荐阅读
- javascript - 登录后设置不记名令牌
- php - 在php中重定向到Iframe之外的另一个页面
- ansible - 从 ansible playbook 内部执行 docker-compose
- sql - 使用 DAX 在 Power BI 中分离列
- javascript - 如何正确地将“this”对象发送到函数
- firebase - Firebase 实时数据库中有关身份验证的信息
- flask - 烧瓶护身符。将sha256列入白名单不起作用
- python - 在电脑上运行没有安装 python 的 python 脚本
- selenium - 无法在 selenium 中使用“$”字符编译 xpath
- java - PDFTextStripper 不支持同一 PDF 中的多种语言