Python requests使用cookie

class Api(object):
    def __init__(self, hostname, user_name, user_password):
        """
        python3 DMP API SDK
        :param hostname:
        :param user_name:
        :param user_password:
        """
        self.url = 'http://%s/' % hostname
        self.user_name = user_name
        self.user_password = user_password
        self.send_headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0",
            "Connection": "keep-alive",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2"}
        self.cookie = self.login
    @property
    def login(self):
        """
        登录DMP
        :return: cookie dict
        """
        data = {'user_name': self.user_name, 'user_password': self.user_password}
        try:
            response = requests.post(url=self.server_url('login'), data=data, headers=self.send_headers, )
            cookies = response.cookies
            cookie = requests.utils.dict_from_cookiejar(cookies)
            self.cookie = cookie
            return cookie
        except Exception as err:
            print('获取cookie失败:\n{0}'.format(err))
posted @ 2020-10-27 09:44  国际一级退堂鼓鼓手  阅读(135)  评论(0编辑  收藏  举报