python获取网络图片方法及整理过程详解
这篇文章主要介绍了python获取网络图片方法及整理过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
方式1
使用urllib库
importurllib.request
importos,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")
exceptIOErrorase:
print("IOEERROR")
exceptExceptionase:
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,使用系统库文件读写操作
importurllib.request
importos,stat
req=urllib.request.Request(url)
file="/home/baixiaoxu/desk/file-ttttt.jpg"
req.add_header('User-Agent','Mozilla/5.0(WindowsNT6.3;WOW64;rv:51.0)Gecko/20100101Firefox/51.0')
response=urllib.request.urlopen(url)
html=response.read()
withopen(file,'wb')asf:
f.write(html)
网上的方法
importos
os.makedirs('./image/',exist_ok=True)
IMAGE_URL="http://image.nationalgeographic.com.cn/2017/1122/20171122113404332.jpg"
defurllib_download():
fromurllib.requestimporturlretrieve
urlretrieve(IMAGE_URL,'./image/img1.png')
defrequest_download():
importrequests
r=requests.get(IMAGE_URL)
withopen('./image/img2.png','wb')asf:
f.write(r.content)
defchunk_download():
importrequests
r=requests.get(IMAGE_URL,stream=True)
withopen('./image/img3.png','wb')asf:
forchunkinr.iter_content(chunk_size=32):
f.write(chunk)
整理简单的下载图片
importurllib
fromurllibimportrequest
importre
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")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。