zoukankan      html  css  js  c++  java
  • Python 下载图片的几种方法

    总结下:

    url = 'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1707/31/c14/54293429_1501509923353_mthumb.jpg'

    1、urllib库——urlretrieve

    import urllib
    def report_hook(count, block_size, total_size):  
        print '%02d%%'%(100.0 * count * block_size/ total_size)  
       
    urllib.urlretrieve("http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1707/31/c14/54293429_1501509923353_mthumb.jpg",r'D:DESKTOP1.jpg',reporthook= report_hook)

    顺便提一下,report_hook是回调函数——reporthook:是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。我们可以利用这个回调函数来显示当前的下载进度。

    2、还是urllib——urlopen

    import urllib
    r = urllib.urlopen(url)
    data = r.read()
    with open("1234.jpg",'wb') as f:
       f.write(data)

    3、requests

    #coding:utf-8
    import requests
    r= requests.get(url)
    with open("123.jpg",'wb') as f:
       f.write(r.content)

     注意:

    resp.text返回的是Unicode型的数据。

    resp.content返回的是bytes型也就是二进制的数据。

    urlencode的发送请求同时传data表单
    import urllib    
    import urllib2    
      
    url = 'http://www.someserver.com/register.cgi'    
        
    values = {'name' : 'WHY',    
              'location' : 'SDU',    
              'language' : 'Python' }    
      
    data = urllib.urlencode(values) # 编码工作  
    req = urllib2.Request(url, data)  # 发送请求同时传data表单  
    response = urllib2.urlopen(req)  #接受反馈的信息  
    the_page = response.read()  #读取反馈的内容  
  • 相关阅读:
    Merge Two Sorted Lists
    4Sum
    Letter Combinations of a Phone Number
    3Sum Closest
    3Sum
    Longest Common Prefix
    Roman to Integer
    Integer to Roman
    Container With Most Water
    Regular Expression Matching
  • 原文地址:https://www.cnblogs.com/vhills/p/7411034.html
Copyright © 2011-2022 走看看