保存cookie状态封装

Posted wopuchezhan

tags:

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

from urllib import request, parse
from urllib.error import HTTPError,URLError
#保存cookie
from http import cookiejar

class session(object):
def __init__(self):
cookie_object = cookiejar.CookieJar()

handler = request.HTTPCookieProcessor(cookie_object)

self.opener = request .build_opener(handler)
#每次遇到cookie的时候 都存储到cookie object

def get(self, url, headers=None):
return get(url, headers, self.opener)

def post(self, url, form, headers=None):
return post(url, form, headers, self.opener)


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

def opst(url,form,headers=None,opener=None):
return urlrequests(url, form, headers=headers, opener=opener)

def urlrequests(url,form=None, headers=None,opener = None):
user_agent =‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/67.0.3396.99 Safari/537.36‘
if headers == None:
headers = {
‘User-Agent‘: user_agent
}
html_bytes = b‘‘

try:
if form:
form_str= parse.urlencode(form, encoding=‘utf-8‘)

form_bytes= form_str.encode(‘utf-8‘)

req = request.Request(url, data = form_bytes,headers=headers)

else:
req = request.Request(url, headers=headers)
if opener:
response= opener.open(req)
else:
respones = request,urlopen(req)

html_bytes = reaponse.read()

except HTTPError as e:
print(e)
except URLError as e:
print(e)

retrun html_bytes


if __name__ == ‘__main__‘:

url = ‘http://www.baidu.com‘
html_byte = get(url)
print(html_byte)















































































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

Cookie

Cookie和Session

cookie 保存导航菜单的展开状态

状态管理之cookie使用及其限制session会话

程序中保存状态的方式之Cookies

COOKIESESSION和CACHE