How to use cookies method in Playwright Internal

Best JavaScript code snippet using playwright-internal

tests.py

Source:tests.py Github

copy

Full Screen

1import time2from django.test import TestCase3from django.conf.urls.defaults import *4from django.http import HttpResponse5from django.conf import settings6import paranoidsessions7def test_view(request):8 """Simple little view for testing purposes.9 This adds a unique timestamp into the session if it doesn't already10 have one; used to make sure no info leaks between sessions.11 """12 if "timestamp" not in request.session:13 request.session["timestamp"] = time.time()14 return HttpResponse("OK")15def request_filter(request):16 """Test filtering of requests; anything with "safe" in it is filtered."""17 if "safe" in request.path:18 return False19 return True20urlpatterns = patterns('',21 (r'^$', test_view), 22 (r'^safeview$', test_view),23)24def with_settings(**new_settings):25 """Decorator to temporarily change django settings during a test."""26 def with_settings_dec(func):27 def newfunc(*args,**kwds):28 old_settings = {}29 for (key,value) in new_settings.iteritems():30 old_settings[key] = getattr(settings,key)31 setattr(settings,key,value)32 try:33 return func(*args,**kwds)34 finally:35 for (key,value) in old_settings.iteritems():36 setattr(settings,key,value)37 return newfunc38 return with_settings_dec39class TestParanoidSessions(TestCase):40 """Testcases for paranoidsessions module."""41 urls = "paranoidsessions.tests"42 def setUp(self):43 self.orig_clear_session = settings.PSESSION_CLEAR_SESSION_FUNCTION44 settings.PSESSION_CLEAR_SESSION_FUNCTION = lambda r: r.session.flush()45 def tearDown(self):46 settings.PSESSION_CLEAR_SESSION_FUNCTION = self.orig_clear_session47 @with_settings(PSESSION_SECURE_COOKIE_NAME="secureid")48 def test_secure_key_handling(self):49 # No secure key gets sent as it's not a secure request50 r = self.client.get("/")51 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value52 self.assertFalse("secureid" in self.client.cookies)53 # Secure key generated and sent in secure cookie54 r = self.client.get("/",**{"wsgi.url_scheme":"https"})55 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value56 key1 = self.client.cookies["secureid"].value57 self.assertEquals(session1,session2)58 self.assertTrue(self.client.cookies["secureid"]["secure"])59 # Additional request accepted, key not sent again60 r = self.client.get("/",**{"wsgi.url_scheme":"https"})61 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value62 self.assertEquals(session1,session3)63 self.assertFalse("secureid" in r.cookies)64 # Insecure requests are accepted with an invalid secure key65 # (Django test client dosen't respect 'secure' cookie setting)66 self.client.cookies["secureid"] = "invalid"67 r = self.client.get("/")68 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value69 self.assertEquals(session1,session4)70 self.assertFalse("secureid" in r.cookies)71 # And with no secure key at all72 del self.client.cookies["secureid"]73 r = self.client.get("/")74 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value75 self.assertEquals(session1,session4)76 self.assertFalse("secureid" in r.cookies)77 # But secure requests are rejected with an invalid key78 self.client.cookies["secureid"] = "invalid"79 r = self.client.get("/",**{"wsgi.url_scheme":"https"})80 session5 = self.client.cookies[settings.SESSION_COOKIE_NAME].value81 key2 = self.client.cookies["secureid"].value82 self.assertNotEquals(session1,session5)83 self.assertNotEquals(key1,key2)84 # Rejected session is new, and works OK85 r = self.client.get("/",**{"wsgi.url_scheme":"https"})86 session6 = self.client.cookies[settings.SESSION_COOKIE_NAME].value87 self.assertEquals(session5,session6)88 # But is rejected again when secureid is not provided89 del self.client.cookies["secureid"]90 r = self.client.get("/",**{"wsgi.url_scheme":"https"})91 session7 = self.client.cookies[settings.SESSION_COOKIE_NAME].value92 self.assertNotEquals(session5,session7)93 # It's possible to directly start a session over secure connection94 del self.client.cookies[settings.SESSION_COOKIE_NAME]95 r = self.client.get("/",**{"wsgi.url_scheme":"https"})96 session8 = self.client.cookies[settings.SESSION_COOKIE_NAME].value97 self.assertNotEquals(session8,session7)98 r = self.client.get("/",**{"wsgi.url_scheme":"https"})99 session9 = self.client.cookies[settings.SESSION_COOKIE_NAME].value100 self.assertEquals(session8,session9)101 @with_settings(PSESSION_NONCE_TIMEOUT=0)102 def test_nonce_generation(self):103 # We are initially assigned a nonce104 r = self.client.get("/")105 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value106 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value107 # And the next request gets a new one108 r = self.client.get("/")109 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value110 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value111 self.assertEqual(session1,session2)112 self.assertNotEqual(nonce1,nonce2)113 @with_settings(PSESSION_NONCE_TIMEOUT=0.2)114 def test_nonce_timeout(self):115 # We keep the same nonce for a few requests116 r = self.client.get("/")117 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value118 r = self.client.get("/")119 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value120 self.assertEqual(nonce1,nonce2)121 # But get a new one after the timeout122 time.sleep(0.2)123 r = self.client.get("/")124 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value125 self.assertNotEqual(nonce1,nonce2)126 @with_settings(PSESSION_NONCE_TIMEOUT=0)127 def test_invalid_nonce(self):128 # Proving proper nonces gives access to our session data129 r = self.client.get("/")130 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value131 timestamp1 = self.client.session["timestamp"]132 r = self.client.get("/")133 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value134 timestamp2 = self.client.session["timestamp"]135 self.assertEqual(session1,session2)136 self.assertEqual(timestamp1,timestamp2)137 # But an invalid nonce gets us booted into a fresh session138 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = "invalid"139 r = self.client.get("/")140 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value141 timestamp3 = self.client.session["timestamp"]142 self.assertNotEqual(session1,session3)143 self.assertNotEqual(timestamp1,timestamp3)144 @with_settings(PSESSION_NONCE_WINDOW=2,PSESSION_NONCE_TIMEOUT=0)145 def test_nonce_window(self):146 # Generate two nonces, we'll use the old one for requests147 r = self.client.get("/")148 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value149 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value150 r = self.client.get("/")151 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value152 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value153 self.assertEqual(session1,session2)154 # Use the old nonce, it should still work155 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1156 r = self.client.get("/")157 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value158 self.assertEqual(session1,session3)159 # Use the old nonce again, it should still work160 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1161 r = self.client.get("/")162 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value163 self.assertEqual(session1,session3)164 # But using it a third time should fail165 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1166 r = self.client.get("/")167 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value168 self.assertNotEqual(session1,session4)169 @with_settings(PSESSION_NONCE_WINDOW=3,PSESSION_NONCE_TIMEOUT=0,PSESSION_NONCE_WINDOW_TIMEOUT=0.2)170 def test_nonce_window_timeout(self):171 # Generate two nonces, we'll use the old one for requests172 r = self.client.get("/")173 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value174 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value175 r = self.client.get("/")176 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value177 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value178 self.assertEqual(session1,session2)179 # Use the old nonce, it should still work180 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1181 r = self.client.get("/")182 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value183 self.assertEqual(session1,session3)184 # After the window timeout has elapsed, we get our session booted.185 time.sleep(0.2)186 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1187 r = self.client.get("/")188 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value189 self.assertNotEqual(session1,session4)190 @with_settings(PSESSION_KEY_TIMEOUT=0.2)191 def test_key_timeout(self):192 # No nonces here, just check the session key.193 r = self.client.get("/")194 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value195 timestamp1 = self.client.session["timestamp"]196 # Session key stays the same for a while197 r = self.client.get("/")198 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value199 timestamp2 = self.client.session["timestamp"]200 self.assertEqual(session1,session2)201 self.assertEqual(timestamp1,timestamp2)202 # But is cycled after the timeout has elapsed203 time.sleep(0.2)204 r = self.client.get("/")205 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value206 timestamp3 = self.client.session["timestamp"]207 self.assertNotEqual(session1,session3)208 self.assertEqual(timestamp1,timestamp3)209 @with_settings(PSESSION_CHECK_HEADERS=["REMOTE_ADDR","HTTP_USER_AGENT"])210 def test_check_headers(self):211 # Test a missing header suddenly appearing212 r = self.client.get("/")213 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value214 r = self.client.get("/",HTTP_USER_AGENT="attacker")215 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value216 self.assertNotEqual(session1,session2)217 # Test a header changing its value218 r = self.client.get("/",HTTP_USER_AGENT="goodguy")219 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value220 r = self.client.get("/",HTTP_USER_AGENT="badguy")221 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value222 self.assertNotEqual(session1,session2)223 # Test a header disappearing224 r = self.client.get("/",HTTP_USER_AGENT="goodguy")225 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value226 r = self.client.get("/")227 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value228 self.assertNotEqual(session1,session2)229 # Test a change and a disappear230 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")231 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value232 r = self.client.get("/",REMOTE_ADDR="yyy")233 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value234 self.assertNotEqual(session1,session2)235 # Test everything staying the same236 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")237 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value238 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")239 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value240 self.assertEqual(session1,session2)241 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")242 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value243 self.assertEqual(session1,session3)244 @with_settings(PSESSION_REQUEST_FILTER_FUNCTION=request_filter,PSESSION_CHECK_HEADERS=["HTTP_USER_AGENT"])245 def test_request_filter(self):246 r = self.client.get("/")247 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value248 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value249 # Requests to the safe view aren't validated250 r = self.client.get("/safeview",HTTP_USER_AGENT="attacker")251 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value252 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value253 self.assertEqual(session1,session2)254 self.assertEqual(nonce1,nonce2)255 # But requests to the other view get booted256 r = self.client.get("/",HTTP_USER_AGENT="attacker")257 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value258 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value259 self.assertNotEqual(session1,session2)...

Full Screen

Full Screen

api.py

Source:api.py Github

copy

Full Screen

1__author__ = 'powergx'2import json3import requests4from crysadm_helper import r_session5from requests.adapters import HTTPAdapter6import time7from urllib.parse import urlparse, parse_qs8requests.packages.urllib3.disable_warnings()9# 迅雷API接口10appversion = '3.1.1'11server_address = 'http://2-api-red.xunlei.com'12agent_header = {'user-agent': "RedCrystal/3.0.0 (iPhone; iOS 9.9; Scale/2.00)"}13# 负载均衡14def api_proxies():15 return {}16# 提交迅雷链接,返回信息17def api_post(cookies, url, data, verify=False, headers=agent_header, timeout=60):18 address = server_address + url19 try:20 proxies = api_proxies()21 r = requests.post(url=address, data=data, proxies=proxies, verify=verify, headers=headers, cookies=cookies, timeout=timeout) 22 except requests.exceptions.RequestException as e:23 return __handle_exception(e=e)24 if r.status_code != 200: 25 return __handle_exception(rd=r.reason)26 return json.loads(r.text)27# 申请提现请求28def exec_draw_cash(cookies, limits=None):29 r = get_can_drawcash(cookies)30 if r.get('r') != 0:31 return r32 if r.get('is_tm') == 0:33 return dict(r=0, rd=r.get('tm_tip'))34 r = get_balance_info(cookies)35 if r.get('r') != 0:36 return r37 wc_pkg = r.get('wc_pkg')38 if limits is not None and wc_pkg < limits: 39 return dict(r=1, rd='帐户金额少于下限值%s元' % limits)40 if wc_pkg > 200:41 wc_pkg = 20042 r = draw_cash(cookies, wc_pkg)43 if r.get('r') != 0:44 return r45 return r46# 获取提现信息47def get_can_drawcash(cookies):48 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'49 body = dict(v='1', appversion=appversion)50 return api_post(url='/?r=usr/drawcashInfo', data=body, cookies=cookies)51# 检测提现余额52def get_balance_info(cookies):53 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'54 body = dict(v='2', appversion=appversion)55 return api_post(url='/?r=usr/asset', data=body, cookies=cookies)56# 提交提现请求57def draw_cash(cookies, money):58 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'59 body = dict(v='3', m=str(money))60 return api_post(url='?r=usr/drawpkg', data=body, cookies=cookies)61# 获取MINE信息62def get_mine_info(cookies):63 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'64 body = dict(v='4', appversion=appversion)65 return api_post(url='/?r=mine/info', data=body, cookies=cookies)66# 获取收益信息67def get_produce_stat(cookies):68 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'69 body = dict(appversion=appversion)70 return api_post(url="/?r=mine/produce_stat", data=body, cookies=cookies)71# 获取速度状态72def get_speed_stat(cookies):73 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'74 try:75 proxies = api_proxies()76 r = requests.post(server_address + '/?r=mine/speed_stat', data=None, proxies=proxies, verify=False, cookies=cookies, headers=agent_header, timeout=60)77 except requests.exceptions.RequestException as e:78 __handle_exception(e=e)79 return [0] * 2480 if r.status_code != 200:81 __handle_exception(rd=r.reason)82 return [0] * 2483 return json.loads(r.text).get('sds')84# 获取个人信息85def get_privilege(cookies):86 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'87 body = dict(v='1', appversion=appversion, ver=appversion)88 return api_post(url='/?r=usr/privilege', data=body, cookies=cookies)89# 获取设备状态90def get_device_stat(s_type, cookies):91 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'92 body = dict(type=s_type, hand='0', v='2', ver='1')93 return api_post(url='/?r=mine/devices_stat', data=body, cookies=cookies)94# 提交收集水晶请求95def collect(cookies):96 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'97 return api_post(url='/index.php?r=mine/collect', data=None, cookies=cookies)98# 获取宝箱信息99def api_giftbox(cookies):100 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'101 body = dict(tp='0', p='0', ps='60', t='', v='2', cmid='-1')102 return api_post(url='/?r=usr/giftbox', data=body, cookies=cookies)103# 提交打开宝箱请求104def api_openStone(cookies, giftbox_id, direction):105 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'106 body = dict(v='1', id=str(giftbox_id), side=direction)107 return api_post(url='/?r=usr/openStone', data=body, cookies=cookies)108# 提交放弃宝箱请求109def api_giveUpGift(cookies, giftbox_id):110 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'111 body = dict(v='2', id=str(giftbox_id), tag='0')112 return api_post(url='/?r=usr/giveUpGift', data=body, cookies=cookies)113# 获取幸运转盘信息114def api_getconfig(cookies):115 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'116 return api_post(url='/?r=turntable/getconfig', data=None, cookies=cookies)117# 提交幸运转盘请求118def api_getaward(cookies):119 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'120 return api_post(url='/?r=turntable/getaward', data=None, cookies=cookies)121# 获取秘银进攻信息122def api_sys_getEntry(cookies):123 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'124 body = dict(v='6')125 return api_post(url='/?r=sys/getEntry', data=body, cookies=cookies)126# 获取秘银复仇信息127def api_steal_stolenSilverHistory(cookies):128 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'129 body = dict(v='2', p='0', ps='20')130 return api_post(url='/?r=steal/stolenSilverHistory', data=body, cookies=cookies)131# 提交秘银进攻请求132def api_steal_search(cookies, searcht_id=0):133 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'134 body = dict(v='2', sid=str(searcht_id))135 return api_post(url='/?r=steal/search', data=body, cookies=cookies)136# 提交收集秘银请求137def api_steal_collect(cookies, searcht_id):138 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'139 body = dict(sid=str(searcht_id), cmid='-2', v='2')140 return api_post(url='/?r=steal/collect', data=body, cookies=cookies)141# 提交进攻结果请求142def api_steal_summary(cookies, searcht_id):143 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'144 body = dict(sid=str(searcht_id), v='2')145 return api_post(url='/?r=steal/summary', data=body, cookies=cookies)146# 获取星域存储相关信息147def ubus_cd(session_id, account_id, action, out_params, url_param=None):148 url = "http://kjapi.peiluyou.com:5171/ubus_cd?account_id=%s&session_id=%s&action=%s" % (account_id, session_id, action)149 if url_param is not None:150 url += url_param151 params = ["%s" % session_id] + out_params152 data = {"jsonrpc": "2.0", "id": 1, "method": "call", "params": params}153 try:154 body = dict(data=json.dumps(data), action='onResponse%d' % int(time.time() * 1000))155 s = requests.Session()156 s.mount('http://', HTTPAdapter(max_retries=5))157 proxies = api_proxies()158 r = s.post(url, data=body, proxies=proxies)159 result = r.text[r.text.index('{'):r.text.rindex('}')+1]160 return json.loads(result)161 except requests.exceptions.RequestException as e:162 return __handle_exception(e=e)163# 发送设置链接164def parse_setting_url(url):165 query_s = parse_qs(urlparse(url).query, keep_blank_values=True)166 device_id = query_s['device_id'][0]167 session_id = query_s['session_id'][0]168 account_id = query_s['user_id'][0]169 return device_id, session_id, account_id170# 检测是否API错误171def is_api_error(r):172 if r.get('r') == -12345:173 return True174 return False175# 接口故障176def __handle_exception(e=None, rd='接口故障', r=-12345):177 if e is None:178 print(rd)179 else:180 print(e)181 b_err_count = r_session.get('api_error_count')182 if b_err_count is None:183 r_session.setex('api_error_count', '1', 60)184 return dict(r=r, rd=rd)185 err_count = int(b_err_count.decode('utf-8')) + 1186 if err_count > 200:187 r_session.setex('api_error_info', '迅雷矿场API故障中,攻城狮正在赶往事故现场,请耐心等待.', 60)188 err_count_ttl = r_session.ttl('api_error_count')189 if err_count_ttl is None:190 err_count_ttl = 30191 r_session.setex('api_error_count', str(err_count), err_count_ttl + 1)192 return dict(r=r, rd=rd)...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1#coding:utf-82import BeautifulSoup3import requests4from requests.cookies import RequestsCookieJar5import time6import re7import os8import sys9import json10from generic_variables import *11'''12get a raw_inpupt13return the striped string from the raw_input14'''15def GetRawInput(str = ''):16 message = str(raw_input(str))17 return message.strip()18'''19Read the recorded Cookies values20if get the cookies then return it 21else return None22'''23def ReadCookies():24 jar = RequestsCookieJar()25 try:26 with open('cookies.txt','r') as f:27 cookies = json.load(f)28 # print type(cookies)29 for cookie in cookies:30 # print cookie31 # jar.set(cookie["name"],cookie["value"])32 jar.set(cookie,cookies[cookie])33 # print jar34 except :35 # print 'get cookie error'36 return None37 return jar38'''39Save the Cookies value 40get a cookies and save it to 'cookies.txt' file41if saved successfully return True42else return False43'''44def SaveCookies(cookies):45 print 'save cookies',cookies46 cookies = requests.utils.dict_from_cookiejar(cookies)47 # print cookies48 try:49 with open('cookies.txt','w') as f:50 json.dump(cookies,f)51 except :52 # print 'save cookie error'53 return False54 return True55'''56Update the cookies value through access the LoginUrl and call SaveCookies57'''58def RenewCookies():59 # print 'renew the cookies'60 SaveCookies(requests.get(LoginUrl).cookies)61'''62check whether the cookies is valuable 63get the session(have the cookies)64if the session can get the home page return True65else return False66'''67def CheckCookies(session):68 print 'CheckCookies',session.cookies69 rsq =session.get(LoginUrl+'/Home/StudentIndex')70 rr = re.compile(r'1\d{7}')71 # print rsq.content72 s = rr.findall(rsq.content)73 # print s74 if s != []:75 return True76 else :77 return False78'''79get the session that has the valuable cookies to login 80'''81def GetSession():82 session = requests.session()83 cookie = ReadCookies()84 if cookie != None :85 # print 'cookie is not none'86 session.cookies = cookie87 if (CheckCookies(session)):88 # print 'check login seccess'89 return session90 else:91 RenewCookies()92 cookie = ReadCookies()93 session.cookies = cookie94 LoginCMS(session)95 if (CheckCookies(session)):96 return session97 RenewCookies()98 GetSession()99'''100to get login the CurriculumManagementSystem101get a session that hasn't been logged in yet102get the Username and Password through input 103return a response from login104'''105def LoginCMS(session):106 UserName = GetRawInput('input the Username:')107 UserPassword = GetRawInput('input the Password:')108 ValidateCode = GetVc(session)109 print 'logincmscookie:',session.cookies110 parms = {'txtUserName':UserName,'txtPassword':UserPassword,'txtvaliCode':ValidateCode}111 return session.post(LoginUrl,parms)112'''113get the ValidateCode114get the validatecode through input and return it115'''116def GetVc(session):117 print 'getvccookie:',session.cookies118 res = session.get(LoginUrl+ValidateCodeUrl)119 with open('validatecode.png','wb') as f:120 f.write(res.content)121 return str(raw_input('input the validatecode:'))122'''123get the student course table message124get the logged session and access the trul url125save the response to a html file126'''127def GetCrouseTable(session):128 QueryCTUrl = LoginUrl+QueryCourseTableUrl129 # QueryCTUrl = 'http://xk.autoisp.shu.edu.cn:8080/StudentQuery/CtrlViewQueryCourseTable'130 rsp = session.get(QueryCTUrl)131 # print rsp.content132 with open('coursetable.html', 'wb')as f:133 f.write(rsp.content)134'''135get the student course rank table message136get the logged session and access the trul url137save the response to a html file138'''139def GetEnrollRankTable(session):140 QueryERUrl = LoginUrl+QueryEnrollRankUrl141 rsp = session.get(QueryERUrl)142 # print rsp.content143 with open('enrollranktable.html', 'wb')as f:144 f.write(rsp.content)145'''146get the student deleted course table message147get the logged session and access the trul url148save the response to a html file149'''150def GetDeleteCourseTable(session):151 QueryERUrl = LoginUrl+QueryDeleteCourseUrl152 rsp = session.get(QueryERUrl)153 # print rsp.content154 with open('deletecoursetable.html', 'wb')as f:155 f.write(rsp.content)156'''157get the student deleted course table message158get the logged session and access the trul url159save the response to a html file160'''161def GetQueryParmsData():162 ParmsName = ['CourseNo', 'CourseName', 'TeachNo', 'TeachName',163 'CourseTime', 'NotFull', 'Credit', 'Campus', 'Enrolls',164 'DataCount', 'MinCapacicy', 'MaxCapacity', 'PageIndex',165 'PageSize', 'FunctionString']166 # ParmsValue = ['12', '', '', '',167 # '', 'false', '', '0', '',168 # '0', '', '', '1',169 # '1000', 'InitPage']170 parms = {}171 for i in ParmsName:172 if i == 'NotFull':173 print i ,":0 is false and 1 is true,default false"174 print "input your choose [0/1]:"175 ForT = GetRawInput()176 parms[i] = 'false'177 if ForT == 1:178 parms[i] = 'true'179 elif i == 'Campus':180 print i,":get 7 choose"181 print "0:全部 1:本部 2:延长 3:嘉定 4:待用 5:徐经 6:宝山东校区"182 print "input you choose [0-6]:"183 ChooseCampus = GetRawInput()184 if ChooseCampus!='':185 parms[i] = ChooseCampus186 else:187 parms[i] = 0188 elif i == 'DataCount':189 print i,":0 is not limit and other num is the response data num"190 LimitDataCount = GetRawInput()191 if LimitDataCount != '':192 parms[i] = LimitDataCount193 else:194 parms[i] = 0195 elif i == 'PageSize':196 print i,"default 20:"197 PageSize = GetRawInput()198 if PageSize != '':199 parms[i] = PageSize200 else:201 parms[i] = 20202 elif i == 'FunctionString':203 parms[i] = 'InitPage'204 elif i == 'PageIndex':205 PageIndex = GetRawInput()206 if PageIndex != '':207 parms[i] = PageIndex208 else:209 parms[i] = 1210 else:211 print i,":"212 parms[i] = GetRawInput()213 return parms214'''215'''216def GetQueryCourseTable(session):217 QueryERUrl = LoginUrl+QueryCourseTUrl218 # QueryERUrl ='http://xk.autoisp.shu.edu.cn:8080/StudentQuery/CtrlViewQueryCourse'219 headers = {220 "Host": "xk.autoisp.shu.edu.cn:8080",221 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0",222 "Accept": "*/*",223 "Accept-Language": "en-US,en;q=0.5",224 "Accept-Encoding": "gzip, deflate",225 "Content-Type": "application/x-www-form-urlencoded",226 "X-Requested-With": "XMLHttpRequest",227 "Referer": "http://xk.autoisp.shu.edu.cn:8080/StudentQuery/QueryCourse",228 "Content-Length": "181",229 }230 parms = GetQueryParmsData()231 rsp = session.post(QueryERUrl,parms,headers=headers)232 print rsp.content233 with open('querycoursetable.html', 'wb')as f:234 f.write(rsp.content)235'''236'''237def ValiWhereValue(session):238 QueryERUrl = 'http://xk.autoisp.shu.edu.cn:8080/Login/ValiWhereValue'239 headers = {240 "Host": "xk.autoisp.shu.edu.cn:8080",241 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0",242 "Accept": "*/*",243 "Accept-Language": "en-US,en;q=0.5",244 "Accept-Encoding": "gzip, deflate",245 "Content-Type": "application/x-www-form-urlencoded",246 "X-Requested-With": "XMLHttpRequest",247 "Referer": "http://xk.autoisp.shu.edu.cn:8080/StudentQuery/QueryCourse",248 "Content-Length": "121",249 }250 ParmsName = ['CourseNo','CourseName','TeachNo','TeachName',251 'CourseTime','NotFull','Credit','Campus','Enrolls',252 'MinCapacicy','MaxCapacity']253 # ParmsValue = []254 ParmsValue = ['12', '', '', '',255 '', 'false', '', '0', '','','',]256 parms = {}257 for i in range(len(ParmsName)):258 print "input the ",ParmsName[i],":"259 # parms[ParmsName[i]] = GetRawInput()260 print ParmsValue[i]261 parms[ParmsName[i]] = ParmsValue[i]262 print parms263 rsp = session.post(QueryERUrl,data=parms,headers = headers)264 print rsp.content265 with open('vali.html', 'wb')as f:266 f.write(rsp.content)267'''268'''269if __name__ == '__main__':270 session = GetSession()271 GetCrouseTable(session)272 GetEnrollRankTable(session)273 GetDeleteCourseTable(session)274 # ValiWhereValue(session)...

Full Screen

Full Screen

test_auth_tkt.py

Source:test_auth_tkt.py Github

copy

Full Screen

...14 '''15 The returned cookies are in the format we expect, with HttpOnly flag.16 '''17 plugin = make_plugin(secret='sosecret')18 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},19 value='HELLO')20 expected_cookies = [21 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),22 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),23 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')24 ]25 assert cookies == expected_cookies26 @helpers.change_config('who.httponly', False)27 def test_httponly_expected_cookies_with_config_httponly_false(self):28 '''29 The returned cookies are in the format we expect, without HttpOnly30 flag.31 '''32 plugin = make_plugin(secret='sosecret')33 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},34 value='HELLO')35 expected_cookies = [36 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/'),37 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0'),38 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0')39 ]40 assert cookies == expected_cookies41 def test_httponly_expected_cookies_without_config_httponly(self):42 '''43 The returned cookies are in the format we expect, with HttpOnly flag.44 '''45 plugin = make_plugin(secret='sosecret')46 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},47 value='HELLO')48 expected_cookies = [49 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),50 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),51 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')52 ]53 assert cookies == expected_cookies54 @helpers.change_config('who.secure', True)55 def test_secure_expected_cookies_with_config_secure_true(self):56 '''57 The returned cookies are in the format we expect, with secure flag.58 '''59 plugin = make_plugin(secret='sosecret')60 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},61 value='HELLO')62 expected_cookies = [63 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; secure; HttpOnly'),64 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; secure; HttpOnly'),65 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; secure; HttpOnly')66 ]67 assert cookies == expected_cookies68 @helpers.change_config('who.secure', False)69 def test_secure_expected_cookies_with_config_secure_false(self):70 '''71 The returned cookies are in the format we expect, without secure72 flag.73 '''74 plugin = make_plugin(secret='sosecret')75 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},76 value='HELLO')77 expected_cookies = [78 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),79 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),80 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')81 ]82 assert cookies == expected_cookies83 def test_secure_expected_cookies_without_config_secure(self):84 '''85 The returned cookies are in the format we expect, without secure flag.86 '''87 plugin = make_plugin(secret='sosecret')88 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},89 value='HELLO')90 expected_cookies = [91 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),92 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),93 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')94 ]95 assert cookies == expected_cookies96 def test_timeout_not_set_in_config(self):97 '''98 Creating a CkanAuthTktCookiePlugin instance without setting timeout in99 config sets correct values in CkanAuthTktCookiePlugin instance.100 '''101 plugin = make_plugin(secret='sosecret')102 nose_tools.assert_equal(plugin.timeout, None)...

Full Screen

Full Screen

generator.py

Source:generator.py Github

copy

Full Screen

...40 # desired_capabilities = selenium_proxy() #添加代理IP41 # driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chromedriver_path,desired_capabilities=desired_capabilities)42 # , desired_capabilities = desired_capabilities43 self.browser = webdriver.Chrome(chrome_options=chrome_options, executable_path=chromedriver_path)44 def new_cookies(self, username, password):45 """46 新生成Cookies,子类需要重写47 :param username: 用户名48 :param password: 密码49 :return:50 """51 raise NotImplementedError52 53 def process_cookies(self, cookies):54 """55 处理Cookies56 :param cookies:57 :return:58 """59 dict = {}60 for cookie in cookies:61 dict[cookie['name']] = cookie['value']62 return dict63 64 def run(self):65 """66 运行, 得到所有账户, 然后顺次模拟登录67 :return:68 """69 accounts_usernames = self.accounts_db.usernames()70 cookies_usernames = self.cookies_db.usernames()71 72 for username in accounts_usernames:73 # if not username in cookies_usernames:74 if username not in cookies_usernames:75 password = self.accounts_db.get(username)76 print('正在生成Cookies', '账号', username, '密码', password)77 result = self.new_cookies(username, password)78 # 成功获取79 if result.get('status') == 1:80 cookies = self.process_cookies(result.get('content'))81 print('成功获取到Cookies', cookies)82 if self.cookies_db.set(username, json.dumps(cookies)):83 print('成功保存Cookies')84 # 密码错误,移除账号85 elif result.get('status') == 2:86 print(result.get('content'))87 if self.accounts_db.delete(username):88 print('成功删除账号')89 else:90 print(result.get('content'))91 else:92 print('所有账号都已经成功获取Cookies')93 94 def close(self):95 """96 关闭97 :return:98 """99 try:100 print('Closing Browser')101 self.browser.close()102 self.driver_service.stop()103 del self.browser104 except TypeError:105 print('Browser not opened')106class WeiboCookiesGenerator(CookiesGenerator):107 def __init__(self, website='weibo'):108 """109 初始化操作110 :param website: 站点名称111 :param browser: 使用的浏览器112 """113 CookiesGenerator.__init__(self, website)114 self.website = website115 116 def new_cookies(self, username, password):117 """118 生成Cookies119 :param username: 用户名120 :param password: 密码121 :return: 用户名和Cookies122 """123 return WeiboCookies(username, password, self.browser,self.driver_service).main() #124if __name__ == '__main__':125 generator = WeiboCookiesGenerator()...

Full Screen

Full Screen

test_cookies.py

Source:test_cookies.py Github

copy

Full Screen

...15 "value": "bar",16 "path": "/",17 "secure": False}18 def tearDown(self):19 self.marionette.delete_all_cookies()20 MarionetteTestCase.tearDown(self)21 def test_add_cookie(self):22 self.marionette.add_cookie(self.COOKIE_A)23 cookie_returned = str(self.marionette.execute_script("return document.cookie"))24 self.assertTrue(self.COOKIE_A["name"] in cookie_returned)25 def test_adding_a_cookie_that_expired_in_the_past(self):26 cookie = self.COOKIE_A.copy()27 cookie["expiry"] = calendar.timegm(time.gmtime()) - 128 self.marionette.add_cookie(cookie)29 cookies = self.marionette.get_cookies()30 self.assertEquals(0, len(cookies))31 def test_chrome_error(self):32 with self.marionette.using_context("chrome"):33 self.assertRaises(UnsupportedOperationException,34 self.marionette.add_cookie, self.COOKIE_A)35 self.assertRaises(UnsupportedOperationException,36 self.marionette.delete_cookie, self.COOKIE_A)37 self.assertRaises(UnsupportedOperationException,38 self.marionette.delete_all_cookies)39 self.assertRaises(UnsupportedOperationException,40 self.marionette.get_cookies)41 def test_delete_all_cookie(self):42 self.marionette.add_cookie(self.COOKIE_A)43 cookie_returned = str(self.marionette.execute_script("return document.cookie"))44 print cookie_returned45 self.assertTrue(self.COOKIE_A["name"] in cookie_returned)46 self.marionette.delete_all_cookies()47 self.assertFalse(self.marionette.get_cookies())48 def test_delete_cookie(self):49 self.marionette.add_cookie(self.COOKIE_A)50 cookie_returned = str(self.marionette.execute_script("return document.cookie"))51 self.assertTrue(self.COOKIE_A["name"] in cookie_returned)52 self.marionette.delete_cookie("foo")53 cookie_returned = str(self.marionette.execute_script("return document.cookie"))54 self.assertFalse(self.COOKIE_A["name"] in cookie_returned)55 def test_should_get_cookie_by_name(self):56 key = "key_{}".format(int(random.random()*10000000))57 self.marionette.execute_script("document.cookie = arguments[0] + '=set';", [key])58 cookie = self.marionette.get_cookie(key)59 self.assertEquals("set", cookie["value"])60 def test_get_all_cookies(self):61 key1 = "key_{}".format(int(random.random()*10000000))62 key2 = "key_{}".format(int(random.random()*10000000))63 cookies = self.marionette.get_cookies()64 count = len(cookies)65 one = {"name" :key1,66 "value": "value"}67 two = {"name":key2,68 "value": "value"}69 self.marionette.add_cookie(one)70 self.marionette.add_cookie(two)71 test_url = self.marionette.absolute_url('test.html')72 self.marionette.navigate(test_url)73 cookies = self.marionette.get_cookies()74 self.assertEquals(count + 2, len(cookies))75 def test_should_not_delete_cookies_with_a_similar_name(self):76 cookieOneName = "fish"77 cookie1 = {"name" :cookieOneName,78 "value":"cod"}79 cookie2 = {"name" :cookieOneName + "x",80 "value": "earth"}81 self.marionette.add_cookie(cookie1)82 self.marionette.add_cookie(cookie2)83 self.marionette.delete_cookie(cookieOneName)84 cookies = self.marionette.get_cookies()85 self.assertFalse(cookie1["name"] == cookies[0]["name"], msg=str(cookies))86 self.assertEquals(cookie2["name"] , cookies[0]["name"], msg=str(cookies))87 def test_we_get_required_elements_when_available(self):88 self.marionette.add_cookie(self.COOKIE_A)89 cookies = self.marionette.get_cookies()90 self.assertIn("name", cookies[0], 'name not available')91 self.assertIn("value", cookies[0], 'value not available')...

Full Screen

Full Screen

cookies.py

Source:cookies.py Github

copy

Full Screen

...19 if request.meta.get('dont_merge_cookies', False):20 return21 cookiejarkey = request.meta.get("cookiejar")22 jar = self.jars[cookiejarkey]23 for cookie in self._get_request_cookies(jar, request):24 jar.set_cookie_if_ok(cookie, request)25 # set Cookie header26 request.headers.pop('Cookie', None)27 jar.add_cookie_header(request)28 self._debug_cookie(request, spider)29 def process_response(self, request, response, spider):30 if request.meta.get('dont_merge_cookies', False):31 return response32 # extract cookies from Set-Cookie and drop invalid/expired cookies33 cookiejarkey = request.meta.get("cookiejar")34 jar = self.jars[cookiejarkey]35 jar.extract_cookies(response, request)36 self._debug_set_cookie(response, spider)37 return response38 def _debug_cookie(self, request, spider):39 if self.debug:40 cl = [to_unicode(c, errors='replace')41 for c in request.headers.getlist('Cookie')]42 if cl:43 cookies = "\n".join(f"Cookie: {c}\n" for c in cl)44 msg = f"Sending cookies to: {request}\n{cookies}"45 logger.debug(msg, extra={'spider': spider})46 def _debug_set_cookie(self, response, spider):47 if self.debug:48 cl = [to_unicode(c, errors='replace')49 for c in response.headers.getlist('Set-Cookie')]50 if cl:51 cookies = "\n".join(f"Set-Cookie: {c}\n" for c in cl)52 msg = f"Received cookies from: {response}\n{cookies}"53 logger.debug(msg, extra={'spider': spider})54 def _format_cookie(self, cookie, request):55 """56 Given a dict consisting of cookie components, return its string representation.57 Decode from bytes if necessary.58 """59 decoded = {}60 for key in ("name", "value", "path", "domain"):61 if cookie.get(key) is None:62 if key in ("name", "value"):63 msg = "Invalid cookie found in request {}: {} ('{}' is missing)"64 logger.warning(msg.format(request, cookie, key))65 return66 continue67 if isinstance(cookie[key], str):68 decoded[key] = cookie[key]69 else:70 try:71 decoded[key] = cookie[key].decode("utf8")72 except UnicodeDecodeError:73 logger.warning("Non UTF-8 encoded cookie found in request %s: %s",74 request, cookie)75 decoded[key] = cookie[key].decode("latin1", errors="replace")76 cookie_str = f"{decoded.pop('name')}={decoded.pop('value')}"77 for key, value in decoded.items(): # path, domain78 cookie_str += f"; {key.capitalize()}={value}"79 return cookie_str80 def _get_request_cookies(self, jar, request):81 """82 Extract cookies from the Request.cookies attribute83 """84 if not request.cookies:85 return []86 elif isinstance(request.cookies, dict):87 cookies = ({"name": k, "value": v} for k, v in request.cookies.items())88 else:89 cookies = request.cookies90 formatted = filter(None, (self._format_cookie(c, request) for c in cookies))91 response = Response(request.url, headers={"Set-Cookie": formatted})...

Full Screen

Full Screen

middlewares.py

Source:middlewares.py Github

copy

Full Screen

...38 def __init__(self, cookies_url):39 self.logger = logging.getLogger(__name__)40 self.cookies_url = cookies_url41 42 def get_random_cookies(self):43 try:44 response = requests.get(self.cookies_url)45 if response.status_code == 200:46 cookies = json.loads(response.text)47 return cookies48 except requests.ConnectionError:49 return False50 51 def process_request(self, request, spider):52 self.logger.debug('正在获取Cookies')53 cookies = self.get_random_cookies()54 if cookies:55 request.cookies = cookies56 self.logger.debug('使用Cookies ' + json.dumps(cookies))57 58 @classmethod59 def from_crawler(cls, crawler):60 settings = crawler.settings61 return cls(62 cookies_url=settings.get('COOKIES_URL')...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({5 });6 const page = await context.newPage();7 await page.screenshot({ path: `google.png` });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext({14 });15 const page = await context.newPage();16 await page.screenshot({ path: `google.png` });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext({23 viewport: { width: 1280, height: 720 }24 });25 const page = await context.newPage();26 await page.screenshot({ path: `google.png` });27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext({33 viewport: { width: 1280, height: 720 }34 });35 const page = await context.newPage();36 await page.screenshot({ path: `google.png` });37 await browser.close();38})();39const { chromium } = require('playwright');40(async () => {41 const browser = await chromium.launch();42 const context = await browser.newContext({43 viewport: { width: 1280, height: 720 }44 });45 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('[aria-label="Search"]');7 await page.fill('[aria-label="Search"]', 'Playwright');8 await page.press('[aria-label="Search"]', 'Enter');9 await page.close();10 await context.addCookies([{11 }]);12 const cookies = await context.cookies();13 console.log(cookies);14 await browser.close();15})();16const { chromium } = require('playwright');17(async () => {18 const browser = await chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.click('[aria-label="Search"]');22 await page.fill('[aria-label="Search"]', 'Playwright');23 await page.press('[aria-label="Search"]', 'Enter');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'google.png' });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'google.png' });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'google.png' });39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.screenshot({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({5 {6 },7 });8 const page = await context.newPage();9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext({16 extraHTTPHeaders: {17 }18 });19 const page = await context.newPage();20 await page.screenshot({ path: `example.png` });21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext({27 geolocation: { latitude: 59.95, longitude: 30.31667 },28 });29 const page = await context.newPage();30 await page.screenshot({ path: `colosseum-geolocation.png` });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext({37 });38 const page = await context.newPage();39 await page.screenshot({ path: `colosseum-locale.png` });40 await browser.close();41})();42const { chromium } = require('playwright');43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext({5 viewport: { width: 500, height: 500 },6 userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36',7 });8 const page = await context.newPage();9 await page.click('[placeholder="Search"]');10 await page.fill('[placeholder="Search"]', 'playwright');11 await page.press('[placeholder="Search"]', 'Enter');12 await page.close();13 await context.close();14 await browser.close();15})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await context.addCookies([{7 expires: Date.now() + 100000000,8 }]);9 const cookies = await context.cookies();10 console.log(cookies);11 await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch({ headless: false });16 const context = await browser.newContext();17 const page = await context.newPage();18 await context.addCookies([{19 expires: Date.now() + 100000000,20 }]);21 const cookies = await context.cookies();22 console.log(cookies);23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 await context.addCookies([{31 expires: Date.now() + 100000000,32 }]);33 const cookies = await context.cookies();34 console.log(cookies);35 await browser.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _electron } = require('playwright');2const path = require('path');3(async () => {4 const app = await _electron.launch({5 args: [path.join(__dirname, 'app')],6 });7 const page = await app.firstWindow();8 await page.click('text=Set Cookie');9 await page.click('text=Get Cookie');10 await app.close();11})();12const { app, BrowserWindow } = require('electron');13const path = require('path');14const url = require('url');15let win;16function createWindow() {17 win = new BrowserWindow({18 webPreferences: {19 },20 });21 win.loadURL(22 url.format({23 pathname: path.join(__dirname, '../index.html'),24 })25 );26 win.webContents.openDevTools();27 win.on('closed', () => {28 win = null;29 });30}31app.on('ready', createWindow);32app.on('window-all-closed', () => {33 if (process.platform !== 'darwin') {34 app.quit();35 }36});37app.on('activate', () => {38 if (win === null) {39 createWindow();40 }41});42 function setCookie() {43 document.cookie = 'name=John Doe;';44 }45 function getCookie() {46 console.log(document.cookie);47 }48 <button id="set-cookie" onclick="setCookie()">Set Cookie</button>49 <button id="get-cookie" onclick="getCookie()">Get Cookie</button>

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful