python requests库模拟浏览器下载图片

#coding=utf-8
import requests
#??????
def download():
    
    headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}
    url="http://images.haiwainet.cn/2016/1120/20161120112109721.jpg"
    response=requests.get(url,headers=headers)
    with open("demo.jpg","wb") as f:
        for chunk in response.iter_content(128):
            f.write(chunk)
    
def download2():
    #??headers??
    headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}
    #??url
    url="http://images.haiwainet.cn/2016/1120/20161120112109721.jpg"
    from contextlib import closing
    with closing(requests.get(url,headers=headers,stream=True)) as response:
        #????
        with open("demo2.jpg","wb") as fd:
            #?128????
            for chunck in response.iter_content(128):
                fd.write(chunck)
                
    
download2()

    


步骤:

1.浏览器模拟

2.指定url

3.去读流的数据

4.存入数据

import urllib
import urllib2
import requests
print "demo1"
URL="https://api.github.com"
def ull():
    response=urllib2.urlopen(URL)
    print "Response >>>>"
    print response.info()#?????????
def user_paramter():
    #??????
    parmes=urllib.urlencode({"wd":"pyhon"})
    print "Parmters >>"
    request=urllib2.Request("?".join([URL,parmes]))
    request.add_header("User-Agent","Mozilla/5.0")
    #????????
    response=urllib2.urlopen(request)
   
    #????
    print "Response >>>>"
    #?????????
def build_url(url):
    return "/".join([URL,url])
def user_request():
#     parmertes={"wd":"python"}
    response=requests.get(build_url("user/emails"),auth=("imoocdemo","imoocdemo123"))
    print "Headers>>"
    print response.text
    print "Response Body"
    
def params_request():
    response=requests.get(build_url("users"),params={"since":11})
    print response.text
    print response.url
    print response.request.headers
def patch_request():
    #response=requests.patch(build_url("user"),auth=("imoocdemo","imoocdemo123"),json={"name":"babymooc3","email":"[email protected]"})
    response=requests.post(build_url("user"),auth=("imoocdemo","imoocdemo123"),json=["[email protected]"])
    print response.headers
    print response.request.body
    print response.status_code
    
patch_request()

你可能感兴趣的:(Python自动化开发)