Python的post和get请求封装

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

# 定义cookie函数
class session(object):
    def __init__(self):
        # 创建一个cookie容器
        cookie_object = cookiejar.CookieJar()
        # 对应的一个操作,cookie的添加
        handler = request.HTTPCookieProcessor(cookie_object)
        # 实例化一个cookie方法
        self.opener = request.build_opener(handler)
    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)


# 定义函数,form传参为post,不传参为get
def urlrequests(url,form=None,headers=None, opener=None):
    # 定义默认headers,如果不传参就用默认的,传参就替换默认的。
    if headers == None:
        headers={
            'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'

        }
    html_bytes = b''

    try:
        if form:
            # 有form传参则为post请求
            # 转化成str
            form_str = parse.urlencode(form)
            print(form_str)
            # 转化成bytes
            form_byes = form_str.encode('utf-8')
            print(form_byes)
            req = request.Request(url,data=form_byes,headers=headers)
        else:
            # 其他的为get请求
            req = request.Request(url,headers=headers)
        # 假如有传入opener 则用opener调用
        if opener:
            response = opener.open(req)
        else:
            response = request.urlopen(req)
        # 发送请求
        html_bytes = response.read()
    except HTTPError as e:
        print(e)
    except URLError as e:
        print(e)
    return html_bytes

# get请求封装
def get(url, headers=None, opener=None):
    return urlrequests(url, headers=headers,opener=opener)

# post请求封装
def post(url, form, headers=None,opener=None):
    return urlrequests(url, form, headers=headers,opener=opener)

if __name__=='__main__':
    # 直接调用
    # url = 'http://fanyi.baidu.com/sug'
    # form = {
    #     'kw':'呵呵'
    # }
    # html = urlrequests(url,form)
    # print(html)

    # post请求调用
    # url = 'http://fanyi.baidu.com/sug'
    # form = {
    #     'kw':'呵呵'
    # }
    # html = post(url,form=form)
    # print(html)

    # get请求调用
    url = 'http://www.baidu.com'
    html = get(url)
    print(html)

你可能感兴趣的:(爬虫)