How to use cookies method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_auth_tkt.py

Source: test_auth_tkt.py Github

copy
1# encoding: utf-8
2
3from nose import tools as nose_tools
4
5from ckan.tests import helpers
6from ckan.lib.auth_tkt import make_plugin
7
8
9class TestCkanAuthTktCookiePlugin(helpers.FunctionalTestBase):
10
11    '''
12    Test the added methods used by this subclass of
13    repoze.who.plugins.auth_tkt.AuthTktCookiePlugin
14
15    Subclassing FunctionalTestBase ensures the original config is restored
16    after each test.
17    '''
18
19    @helpers.change_config('who.httponly', True)
20    def test_httponly_expected_cookies_with_config_httponly_true(self):
21        '''
22        The returned cookies are in the format we expect, with HttpOnly flag.
23        '''
24        plugin = make_plugin(secret='sosecret')
25        cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},
26                                      value='HELLO')
27        expected_cookies = [
28            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),
29            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),
30            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')
31        ]
32        assert cookies == expected_cookies
33
34    @helpers.change_config('who.httponly', False)
35    def test_httponly_expected_cookies_with_config_httponly_false(self):
36        '''
37        The returned cookies are in the format we expect, without HttpOnly
38        flag.
39        '''
40        plugin = make_plugin(secret='sosecret')
41        cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},
42                                      value='HELLO')
43        expected_cookies = [
44            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/'),
45            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0'),
46            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0')
47        ]
48        assert cookies == expected_cookies
49
50    def test_httponly_expected_cookies_without_config_httponly(self):
51        '''
52        The returned cookies are in the format we expect, with HttpOnly flag.
53        '''
54        plugin = make_plugin(secret='sosecret')
55        cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},
56                                      value='HELLO')
57        expected_cookies = [
58            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),
59            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),
60            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')
61        ]
62        assert cookies == expected_cookies
63
64    @helpers.change_config('who.secure', True)
65    def test_secure_expected_cookies_with_config_secure_true(self):
66        '''
67        The returned cookies are in the format we expect, with secure flag.
68        '''
69        plugin = make_plugin(secret='sosecret')
70        cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},
71                                      value='HELLO')
72        expected_cookies = [
73            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; secure; HttpOnly'),
74            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; secure; HttpOnly'),
75            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; secure; HttpOnly')
76        ]
77        assert cookies == expected_cookies
78
79    @helpers.change_config('who.secure', False)
80    def test_secure_expected_cookies_with_config_secure_false(self):
81        '''
82        The returned cookies are in the format we expect, without secure
83        flag.
84        '''
85        plugin = make_plugin(secret='sosecret')
86        cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},
87                                      value='HELLO')
88        expected_cookies = [
89            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),
90            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),
91            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')
92        ]
93        assert cookies == expected_cookies
94
95    def test_secure_expected_cookies_without_config_secure(self):
96        '''
97        The returned cookies are in the format we expect, without secure flag.
98        '''
99        plugin = make_plugin(secret='sosecret')
100        cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},
101                                      value='HELLO')
102        expected_cookies = [
103            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),
104            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),
105            ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')
106        ]
107        assert cookies == expected_cookies
108
109    def test_timeout_not_set_in_config(self):
110        '''
111        Creating a CkanAuthTktCookiePlugin instance without setting timeout in
112        config sets correct values in CkanAuthTktCookiePlugin instance.
113        '''
114        plugin = make_plugin(secret='sosecret')
115
116        nose_tools.assert_equal(plugin.timeout, None)
117        nose_tools.assert_equal(plugin.reissue_time, None)
118
119    @helpers.change_config('who.timeout', 9000)
120    def test_timeout_set_in_config(self):
121        '''
122        Setting who.timeout in config sets correct values in
123        CkanAuthTktCookiePlugin instance.
124        '''
125        plugin = make_plugin(secret='sosecret')
126
127        nose_tools.assert_equal(plugin.timeout, 9000)
128        nose_tools.assert_equal(plugin.reissue_time, 900)
129
130    @helpers.change_config('who.timeout', 9000)
131    @helpers.change_config('who.reissue_time', 200)
132    def test_reissue_set_in_config(self):
133        '''
134        Setting who.reissue in config sets correct values in
135        CkanAuthTktCookiePlugin instance.
136        '''
137        plugin = make_plugin(secret='sosecret')
138
139        nose_tools.assert_equal(plugin.timeout, 9000)
140        nose_tools.assert_equal(plugin.reissue_time, 200)
141
Full Screen

cookies.py

Source: cookies.py Github

copy
1import logging
2from collections import defaultdict
3
4from scrapy.exceptions import NotConfigured
5from scrapy.http import Response
6from scrapy.http.cookies import CookieJar
7from scrapy.utils.python import to_unicode
8
9
10logger = logging.getLogger(__name__)
11
12
13class CookiesMiddleware:
14    """This middleware enables working with sites that need cookies"""
15
16    def __init__(self, debug=False):
17        self.jars = defaultdict(CookieJar)
18        self.debug = debug
19
20    @classmethod
21    def from_crawler(cls, crawler):
22        if not crawler.settings.getbool('COOKIES_ENABLED'):
23            raise NotConfigured
24        return cls(crawler.settings.getbool('COOKIES_DEBUG'))
25
26    def process_request(self, request, spider):
27        if request.meta.get('dont_merge_cookies', False):
28            return
29
30        cookiejarkey = request.meta.get("cookiejar")
31        jar = self.jars[cookiejarkey]
32        for cookie in self._get_request_cookies(jar, request):
33            jar.set_cookie_if_ok(cookie, request)
34
35        # set Cookie header
36        request.headers.pop('Cookie', None)
37        jar.add_cookie_header(request)
38        self._debug_cookie(request, spider)
39
40    def process_response(self, request, response, spider):
41        if request.meta.get('dont_merge_cookies', False):
42            return response
43
44        # extract cookies from Set-Cookie and drop invalid/expired cookies
45        cookiejarkey = request.meta.get("cookiejar")
46        jar = self.jars[cookiejarkey]
47        jar.extract_cookies(response, request)
48        self._debug_set_cookie(response, spider)
49
50        return response
51
52    def _debug_cookie(self, request, spider):
53        if self.debug:
54            cl = [to_unicode(c, errors='replace')
55                  for c in request.headers.getlist('Cookie')]
56            if cl:
57                cookies = "\n".join(f"Cookie: {c}\n" for c in cl)
58                msg = f"Sending cookies to: {request}\n{cookies}"
59                logger.debug(msg, extra={'spider': spider})
60
61    def _debug_set_cookie(self, response, spider):
62        if self.debug:
63            cl = [to_unicode(c, errors='replace')
64                  for c in response.headers.getlist('Set-Cookie')]
65            if cl:
66                cookies = "\n".join(f"Set-Cookie: {c}\n" for c in cl)
67                msg = f"Received cookies from: {response}\n{cookies}"
68                logger.debug(msg, extra={'spider': spider})
69
70    def _format_cookie(self, cookie, request):
71        """
72        Given a dict consisting of cookie components, return its string representation.
73        Decode from bytes if necessary.
74        """
75        decoded = {}
76        for key in ("name", "value", "path", "domain"):
77            if cookie.get(key) is None:
78                if key in ("name", "value"):
79                    msg = "Invalid cookie found in request {}: {} ('{}' is missing)"
80                    logger.warning(msg.format(request, cookie, key))
81                    return
82                continue
83            if isinstance(cookie[key], str):
84                decoded[key] = cookie[key]
85            else:
86                try:
87                    decoded[key] = cookie[key].decode("utf8")
88                except UnicodeDecodeError:
89                    logger.warning("Non UTF-8 encoded cookie found in request %s: %s",
90                                   request, cookie)
91                    decoded[key] = cookie[key].decode("latin1", errors="replace")
92
93        cookie_str = f"{decoded.pop('name')}={decoded.pop('value')}"
94        for key, value in decoded.items():  # path, domain
95            cookie_str += f"; {key.capitalize()}={value}"
96        return cookie_str
97
98    def _get_request_cookies(self, jar, request):
99        """
100        Extract cookies from the Request.cookies attribute
101        """
102        if not request.cookies:
103            return []
104        elif isinstance(request.cookies, dict):
105            cookies = ({"name": k, "value": v} for k, v in request.cookies.items())
106        else:
107            cookies = request.cookies
108        formatted = filter(None, (self._format_cookie(c, request) for c in cookies))
109        response = Response(request.url, headers={"Set-Cookie": formatted})
110        return jar.make_cookies(response, request)
111
Full Screen

generator.py

Source: generator.py Github

copy
1import json
2from selenium import webdriver
3from selenium.webdriver import DesiredCapabilities
4from cookiespool.config import *
5from cookiespool.db import RedisClient
6from login.weibo.cookies import WeiboCookies
7from selenium.webdriver.chrome.options import Options
8from selenium.webdriver.chrome.service import Service
9from cookiespool.proxyip import selenium_proxy
10
11
12class CookiesGenerator(object):
13    def __init__(self, website='default'):
14        """
15        父类, 初始化一些对象
16        :param website: 名称
17        :param browser: 浏览器, 若不使用浏览器则可设置为 None
18        """
19        self.website = website
20        self.cookies_db = RedisClient('cookies', self.website)
21        self.accounts_db = RedisClient('accounts', self.website)
22        self.init_browser()
23
24    def __del__(self):
25        self.close()
26
27    def init_browser(self):
28        """
29        通过browser参数初始化全局浏览器供模拟登录使用
30        :return:
31        """
32        if BROWSER_TYPE == 'PhantomJS':
33            caps = DesiredCapabilities.PHANTOMJS
34            caps[
35                "phantomjs.page.settings.userAgent"] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
36            self.browser = webdriver.PhantomJS(desired_capabilities=caps)
37            self.browser.set_window_size(1400, 500)
38        elif BROWSER_TYPE == 'Chrome':
39            # 启用谷歌浏览器
40            self.driver_service = Service(executable_path=chromedriver_path)  # 括号内填写 驱动路径
41            chrome_options = Options()
42            chrome_options.add_argument('--headless')
43            chrome_options.add_argument('--no-sandbox')  # 这个配置很重要
44            # desired_capabilities = selenium_proxy() #添加代理IP
45            # driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chromedriver_path,desired_capabilities=desired_capabilities)
46            # , desired_capabilities = desired_capabilities
47            self.browser = webdriver.Chrome(chrome_options=chrome_options, executable_path=chromedriver_path)
48
49    def new_cookies(self, username, password):
50        """
51        新生成Cookies,子类需要重写
52        :param username: 用户名
53        :param password: 密码
54        :return:
55        """
56        raise NotImplementedError
57    
58    def process_cookies(self, cookies):
59        """
60        处理Cookies
61        :param cookies:
62        :return:
63        """
64        dict = {}
65        for cookie in cookies:
66            dict[cookie['name']] = cookie['value']
67        return dict
68    
69    def run(self):
70        """
71        运行, 得到所有账户, 然后顺次模拟登录
72        :return:
73        """
74        accounts_usernames = self.accounts_db.usernames()
75        cookies_usernames = self.cookies_db.usernames()
76        
77        for username in accounts_usernames:
78            # if not username in cookies_usernames:
79            if username not in cookies_usernames:
80                password = self.accounts_db.get(username)
81                print('正在生成Cookies', '账号', username, '密码', password)
82                result = self.new_cookies(username, password)
83                # 成功获取
84                if result.get('status') == 1:
85                    cookies = self.process_cookies(result.get('content'))
86                    print('成功获取到Cookies', cookies)
87                    if self.cookies_db.set(username, json.dumps(cookies)):
88                        print('成功保存Cookies')
89                # 密码错误,移除账号
90                elif result.get('status') == 2:
91                    print(result.get('content'))
92                    if self.accounts_db.delete(username):
93                        print('成功删除账号')
94                else:
95                    print(result.get('content'))
96        else:
97            print('所有账号都已经成功获取Cookies')
98    
99    def close(self):
100        """
101        关闭
102        :return:
103        """
104        try:
105            print('Closing Browser')
106            self.browser.close()
107            self.driver_service.stop()
108            del self.browser
109        except TypeError:
110            print('Browser not opened')
111
112
113class WeiboCookiesGenerator(CookiesGenerator):
114    def __init__(self, website='weibo'):
115        """
116        初始化操作
117        :param website: 站点名称
118        :param browser: 使用的浏览器
119        """
120        CookiesGenerator.__init__(self, website)
121        self.website = website
122    
123    def new_cookies(self, username, password):
124        """
125        生成Cookies
126        :param username: 用户名
127        :param password: 密码
128        :return: 用户名和Cookies
129        """
130
131        return WeiboCookies(username, password, self.browser,self.driver_service).main()   #
132
133
134if __name__ == '__main__':
135    generator = WeiboCookiesGenerator()
136    generator.run()
137
Full Screen

angular-cookies.js

Source: angular-cookies.js Github

copy
1/**
2 * @license AngularJS v1.2.11
3 * (c) 2010-2014 Google, Inc. http://angularjs.org
4 * License: MIT
5 */
6(function(window, angular, undefined) {'use strict';
7
8/**
9 * @ngdoc overview
10 * @name ngCookies
11 * @description
12 *
13 * # ngCookies
14 *
15 * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. 
16 *
17 * {@installModule cookies}
18 *
19 * <div doc-module-components="ngCookies"></div>
20 *
21 * See {@link ngCookies.$cookies `$cookies`} and
22 * {@link ngCookies.$cookieStore `$cookieStore`} for usage.
23 */
24
25
26angular.module('ngCookies', ['ng']).
27  /**
28   * @ngdoc object
29   * @name ngCookies.$cookies
30   * @requires $browser
31   *
32   * @description
33   * Provides read/write access to browser's cookies.
34   *
35   * Only a simple Object is exposed and by adding or removing properties to/from
36   * this object, new cookies are created/deleted at the end of current $eval.
37   *
38   * Requires the {@link ngCookies `ngCookies`} module to be installed.
39   *
40   * @example
41   <doc:example>
42     <doc:source>
43       <script>
44         function ExampleController($cookies) {
45           // Retrieving a cookie
46           var favoriteCookie = $cookies.myFavorite;
47           // Setting a cookie
48           $cookies.myFavorite = 'oatmeal';
49         }
50       </script>
51     </doc:source>
52   </doc:example>
53   */
54   factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
55      var cookies = {},
56          lastCookies = {},
57          lastBrowserCookies,
58          runEval = false,
59          copy = angular.copy,
60          isUndefined = angular.isUndefined;
61
62      //creates a poller fn that copies all cookies from the $browser to service & inits the service
63      $browser.addPollFn(function() {
64        var currentCookies = $browser.cookies();
65        if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
66          lastBrowserCookies = currentCookies;
67          copy(currentCookies, lastCookies);
68          copy(currentCookies, cookies);
69          if (runEval) $rootScope.$apply();
70        }
71      })();
72
73      runEval = true;
74
75      //at the end of each eval, push cookies
76      //TODO: this should happen before the "delayed" watches fire, because if some cookies are not
77      //      strings or browser refuses to store some cookies, we update the model in the push fn.
78      $rootScope.$watch(push);
79
80      return cookies;
81
82
83      /**
84       * Pushes all the cookies from the service to the browser and verifies if all cookies were
85       * stored.
86       */
87      function push() {
88        var name,
89            value,
90            browserCookies,
91            updated;
92
93        //delete any cookies deleted in $cookies
94        for (name in lastCookies) {
95          if (isUndefined(cookies[name])) {
96            $browser.cookies(name, undefined);
97          }
98        }
99
100        //update all cookies updated in $cookies
101        for(name in cookies) {
102          value = cookies[name];
103          if (!angular.isString(value)) {
104            if (angular.isDefined(lastCookies[name])) {
105              cookies[name] = lastCookies[name];
106            } else {
107              delete cookies[name];
108            }
109          } else if (value !== lastCookies[name]) {
110            $browser.cookies(name, value);
111            updated = true;
112          }
113        }
114
115        //verify what was actually stored
116        if (updated){
117          updated = false;
118          browserCookies = $browser.cookies();
119
120          for (name in cookies) {
121            if (cookies[name] !== browserCookies[name]) {
122              //delete or reset all cookies that the browser dropped from $cookies
123              if (isUndefined(browserCookies[name])) {
124                delete cookies[name];
125              } else {
126                cookies[name] = browserCookies[name];
127              }
128              updated = true;
129            }
130          }
131        }
132      }
133    }]).
134
135
136  /**
137   * @ngdoc object
138   * @name ngCookies.$cookieStore
139   * @requires $cookies
140   *
141   * @description
142   * Provides a key-value (string-object) storage, that is backed by session cookies.
143   * Objects put or retrieved from this storage are automatically serialized or
144   * deserialized by angular's toJson/fromJson.
145   *
146   * Requires the {@link ngCookies `ngCookies`} module to be installed.
147   *
148   * @example
149   */
150   factory('$cookieStore', ['$cookies', function($cookies) {
151
152      return {
153        /**
154         * @ngdoc method
155         * @name ngCookies.$cookieStore#get
156         * @methodOf ngCookies.$cookieStore
157         *
158         * @description
159         * Returns the value of given cookie key
160         *
161         * @param {string} key Id to use for lookup.
162         * @returns {Object} Deserialized cookie value.
163         */
164        get: function(key) {
165          var value = $cookies[key];
166          return value ? angular.fromJson(value) : value;
167        },
168
169        /**
170         * @ngdoc method
171         * @name ngCookies.$cookieStore#put
172         * @methodOf ngCookies.$cookieStore
173         *
174         * @description
175         * Sets a value for given cookie key
176         *
177         * @param {string} key Id for the `value`.
178         * @param {Object} value Value to be stored.
179         */
180        put: function(key, value) {
181          $cookies[key] = angular.toJson(value);
182        },
183
184        /**
185         * @ngdoc method
186         * @name ngCookies.$cookieStore#remove
187         * @methodOf ngCookies.$cookieStore
188         *
189         * @description
190         * Remove given cookie
191         *
192         * @param {string} key Id of the key-value pair to delete.
193         */
194        remove: function(key) {
195          delete $cookies[key];
196        }
197      };
198
199    }]);
200
201
202})(window, window.angular);
203
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)