python获取网络图片方法及整理过程详解

yipeiwu_com5年前Python基础

这篇文章主要介绍了python获取网络图片方法及整理过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

方式1

使用urllib库

import urllib.request
import os ,stat
url = "https://cn.bing.com/th?id=OHR.Lidong2019_ZH-CN0761273672_1920x1080.jpg"
try:
  urllib.request.urlretrieve(url,filename="/home/baixiaoxu/desk/123.jpg")
except IOError as e:
  print("IOE ERROR")
except Exception as e:
  print("Exception")

注意:
1,获取地址,判断地址是否存在
2,本地保存地址,判断存在
3,获取远程地址的图片名,或改名
"""
url = "https://cn.bing.com/th?id=OHR.Lidong2019_ZH-CN0761273672_1920x1080.jpg"
file_suffix = os.path.split(url)[1][-20:-1]
print(file_suffix)
"""

2,使用系统库文件读写操作

import urllib.request
import os ,stat

req = urllib.request.Request(url)
file = "/home/baixiaoxu/desk/file-ttttt.jpg"
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0')
response = urllib.request.urlopen(url)
html = response.read()
with open(file, 'wb') as f:
   f.write(html)

网上的方法

import os
os.makedirs('./image/', exist_ok=True)
IMAGE_URL = "/zb_users/upload/202003/wfxvl5bk5bi.jpg"
 
def urllib_download():
  from urllib.request import urlretrieve
  urlretrieve(IMAGE_URL, './image/img1.png')   
 
def request_download():
  import requests
  r = requests.get(IMAGE_URL)
  with open('./image/img2.png', 'wb') as f:
    f.write(r.content)           
 
def chunk_download():
  import requests
  r = requests.get(IMAGE_URL, stream=True)  
  with open('./image/img3.png', 'wb') as f:
    for chunk in r.iter_content(chunk_size=32):
      f.write(chunk)

整理简单的下载图片

import urllib
from  urllib import request
import re

response = request.urlopen('https://cn.bing.com/')
html = response.read()
ht = html.decode()
pattern = r'bgLink(.*?\.jpg)'
compile_re = re.compile(pattern)

hh = compile_re.findall(ht)
url = hh[0].split('/')[1]

download = 'https://cn.bing.com/' + url
urllib.request.urlretrieve(download,filename="/home/baixiaoxu/desk/download.jpg")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中input与raw_input 之间的比较

Python中input与raw_input 之间的比较 input和raw_input均可以接收输入,其差别如下所示: #input假设用户输入的是合法的Python表达式 >...

python 通过手机号识别出对应的微信性别(实例代码)

python 通过手机号识别出对应的微信性别,具体代码如下所述: def getGender(self,tel): self.d(resourceId="com.tencent....

Python装饰器模式定义与用法分析

Python装饰器模式定义与用法分析

本文实例讲述了Python装饰器模式定义与用法。分享给大家供大家参考,具体如下: 装饰器模式定义:动态地给一个对象添加一些额外的职责。 在Python中Decorator mode可以按...

django创建最简单HTML页面跳转方法

假设已经通过: django-admin startproject +项目名称 python manage.py +项目应用 创建好一个项目以及内部的项目应用后,并且会运行django看...

python实现AES加密与解密

AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windo...