• 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 = "http://image.nationalgeographic.com.cn/2017/1122/20171122113404332.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")
    
    
  • 相关阅读:
    Linux 下动态查找磁盘数量方法
    Laravel 学习 .env文件 getenv 获得环境变量的值
    win10系统怎样手动安装cab更新补丁
    TP框架中模糊查询实现
    PHP函数之HTMLSPECIALCHARS_DECODE
    Tp框架—方法中处理数据
    TP框架I方法详解
    鼠标经过图像改变实现
    TP视图命名规则之一
    Json_decode:详解
  • 原文地址:https://www.cnblogs.com/g2thend/p/11818599.html
Copyright © 2020-2023  润新知