Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。

官网:https://pypi.python.org/pypi/requests/
中文资料:http://cn.python-requests.org/zh_CN/latest/

一、初步认知

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'disk_usage': 368627, u'private_gists': 484, ...}

二、下载图片

def downloadImageFile(imgUrl):  
    local_filename = imgUrl.split('/')[-1]  
    print "Download Image File=", local_filename  
    r = requests.get(imgUrl, stream=True) # here we need to set stream = True parameter  
    with open("/home/pandy/"+local_filename, 'wb') as f:  
        for chunk in r.iter_content(chunk_size=1024):  
            if chunk: # filter out keep-alive new chunks  
                f.write(chunk)  
                f.flush()  
        f.close()  
    return local_filename 

案例:

def download_pic()
   img_file = requests.post(download_api, stream=True)
   with open(img_name2, "wb") as data1:
   for chunk in img_file.iter_content():
       data1.write(chunk)

参考资料:
http://panyongzheng.iteye.com/blog/1950119

发表评论

电子邮件地址不会被公开。 必填项已用*标注