get和post ,保存cookie

Posted lxh777

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了get和post ,保存cookie相关的知识,希望对你有一定的参考价值。

from urllib import request,parse


def get(url,headers=None):
    return urlrequests(url,headers=headers)

def post(url,form,headers=None):
    return urlrequests(url,form,headers=headers)
#1,传入url
#2.user-agent
#3.headers
#4.定义request
#5.urlopen
#6.返回bytes数组
def urlrequests(url,form=None,headers=None):

    from http import cookiejar
    cookie = cookiejar.CookieJar()
    handler = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(handler)

    #如果需要用户自行传入headers则覆盖当前的headers
    if headers == None:
        headers = {
            User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/68.0.3440.106 Safari/537.36,
        }
    html_bytes = b‘‘
    try:
        if form:
            # POST
            #先转成str再转成bytes
            form_bytes = parse.urlencode(form).encode(utf-8)

            req = request.Request(url,data=form_bytes,headers=headers)
        else:
            #GET
            req = request.Request(url,headers=headers)

        response = opener.open(req)
        html_bytes = response.read()
    except:
        pass

    return html_bytes

if __name__ == __main__:
    url = http://www.baidu.com
    ss = get(url)
    print(ss)

 

以上是关于get和post ,保存cookie的主要内容,如果未能解决你的问题,请参考以下文章

C#用HttpClient类post get,怎么设置cookies

php中$_REQUEST $_GET $_POST $_COOKIE 的关系和区别

CURL PHP模拟浏览器get和post

接口测试-Get与Post的区别

php curl get 下载远程zip文件保存在本地例子

Spring RestTemplate用法 Post Get Cookie