_generated.py 828 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177
  1. # Copyright (c) Microsoft Corporation.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import datetime
  15. import pathlib
  16. import typing
  17. from typing import Literal
  18. from playwright._impl._api_structures import (
  19. ClientCertificate,
  20. Cookie,
  21. FilePayload,
  22. FloatRect,
  23. Geolocation,
  24. HttpCredentials,
  25. NameValue,
  26. PdfMargins,
  27. Position,
  28. ProxySettings,
  29. RemoteAddr,
  30. RequestSizes,
  31. ResourceTiming,
  32. SecurityDetails,
  33. SetCookieParam,
  34. SourceLocation,
  35. StorageState,
  36. TracingGroupLocation,
  37. ViewportSize,
  38. )
  39. from playwright._impl._assertions import (
  40. APIResponseAssertions as APIResponseAssertionsImpl,
  41. )
  42. from playwright._impl._assertions import LocatorAssertions as LocatorAssertionsImpl
  43. from playwright._impl._assertions import PageAssertions as PageAssertionsImpl
  44. from playwright._impl._browser import Browser as BrowserImpl
  45. from playwright._impl._browser_context import BrowserContext as BrowserContextImpl
  46. from playwright._impl._browser_type import BrowserType as BrowserTypeImpl
  47. from playwright._impl._cdp_session import CDPSession as CDPSessionImpl
  48. from playwright._impl._clock import Clock as ClockImpl
  49. from playwright._impl._console_message import ConsoleMessage as ConsoleMessageImpl
  50. from playwright._impl._dialog import Dialog as DialogImpl
  51. from playwright._impl._download import Download as DownloadImpl
  52. from playwright._impl._element_handle import ElementHandle as ElementHandleImpl
  53. from playwright._impl._errors import Error
  54. from playwright._impl._fetch import APIRequest as APIRequestImpl
  55. from playwright._impl._fetch import APIRequestContext as APIRequestContextImpl
  56. from playwright._impl._fetch import APIResponse as APIResponseImpl
  57. from playwright._impl._file_chooser import FileChooser as FileChooserImpl
  58. from playwright._impl._frame import Frame as FrameImpl
  59. from playwright._impl._input import Keyboard as KeyboardImpl
  60. from playwright._impl._input import Mouse as MouseImpl
  61. from playwright._impl._input import Touchscreen as TouchscreenImpl
  62. from playwright._impl._js_handle import JSHandle as JSHandleImpl
  63. from playwright._impl._locator import FrameLocator as FrameLocatorImpl
  64. from playwright._impl._locator import Locator as LocatorImpl
  65. from playwright._impl._network import Request as RequestImpl
  66. from playwright._impl._network import Response as ResponseImpl
  67. from playwright._impl._network import Route as RouteImpl
  68. from playwright._impl._network import WebSocket as WebSocketImpl
  69. from playwright._impl._network import WebSocketRoute as WebSocketRouteImpl
  70. from playwright._impl._page import Page as PageImpl
  71. from playwright._impl._page import Worker as WorkerImpl
  72. from playwright._impl._playwright import Playwright as PlaywrightImpl
  73. from playwright._impl._selectors import Selectors as SelectorsImpl
  74. from playwright._impl._sync_base import (
  75. EventContextManager,
  76. SyncBase,
  77. SyncContextManager,
  78. mapping,
  79. )
  80. from playwright._impl._tracing import Tracing as TracingImpl
  81. from playwright._impl._video import Video as VideoImpl
  82. from playwright._impl._web_error import WebError as WebErrorImpl
  83. class Request(SyncBase):
  84. @property
  85. def url(self) -> str:
  86. """Request.url
  87. URL of the request.
  88. Returns
  89. -------
  90. str
  91. """
  92. return mapping.from_maybe_impl(self._impl_obj.url)
  93. @property
  94. def resource_type(self) -> str:
  95. """Request.resource_type
  96. Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the
  97. following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,
  98. `eventsource`, `websocket`, `manifest`, `other`.
  99. Returns
  100. -------
  101. str
  102. """
  103. return mapping.from_maybe_impl(self._impl_obj.resource_type)
  104. @property
  105. def service_worker(self) -> typing.Optional["Worker"]:
  106. """Request.service_worker
  107. The Service `Worker` that is performing the request.
  108. **Details**
  109. This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.
  110. Requests originated in a Service Worker do not have a `request.frame()` available.
  111. Returns
  112. -------
  113. Union[Worker, None]
  114. """
  115. return mapping.from_impl_nullable(self._impl_obj.service_worker)
  116. @property
  117. def method(self) -> str:
  118. """Request.method
  119. Request's method (GET, POST, etc.)
  120. Returns
  121. -------
  122. str
  123. """
  124. return mapping.from_maybe_impl(self._impl_obj.method)
  125. @property
  126. def post_data(self) -> typing.Optional[str]:
  127. """Request.post_data
  128. Request's post body, if any.
  129. Returns
  130. -------
  131. Union[str, None]
  132. """
  133. return mapping.from_maybe_impl(self._impl_obj.post_data)
  134. @property
  135. def post_data_json(self) -> typing.Optional[typing.Any]:
  136. """Request.post_data_json
  137. Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.
  138. When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.
  139. Otherwise it will be parsed as JSON.
  140. Returns
  141. -------
  142. Union[Any, None]
  143. """
  144. return mapping.from_maybe_impl(self._impl_obj.post_data_json)
  145. @property
  146. def post_data_buffer(self) -> typing.Optional[bytes]:
  147. """Request.post_data_buffer
  148. Request's post body in a binary form, if any.
  149. Returns
  150. -------
  151. Union[bytes, None]
  152. """
  153. return mapping.from_maybe_impl(self._impl_obj.post_data_buffer)
  154. @property
  155. def frame(self) -> "Frame":
  156. """Request.frame
  157. Returns the `Frame` that initiated this request.
  158. **Usage**
  159. ```py
  160. frame_url = request.frame.url
  161. ```
  162. **Details**
  163. Note that in some cases the frame is not available, and this method will throw.
  164. - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.
  165. - When navigation request is issued before the corresponding frame is created. You can use
  166. `request.is_navigation_request()` to check that.
  167. Here is an example that handles all the cases:
  168. Returns
  169. -------
  170. Frame
  171. """
  172. return mapping.from_impl(self._impl_obj.frame)
  173. @property
  174. def redirected_from(self) -> typing.Optional["Request"]:
  175. """Request.redirected_from
  176. Request that was redirected by the server to this one, if any.
  177. When the server responds with a redirect, Playwright creates a new `Request` object. The two requests are connected
  178. by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
  179. construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
  180. **Usage**
  181. For example, if the website `http://example.com` redirects to `https://example.com`:
  182. ```py
  183. response = page.goto(\"http://example.com\")
  184. print(response.request.redirected_from.url) # \"http://example.com\"
  185. ```
  186. If the website `https://google.com` has no redirects:
  187. ```py
  188. response = page.goto(\"https://google.com\")
  189. print(response.request.redirected_from) # None
  190. ```
  191. Returns
  192. -------
  193. Union[Request, None]
  194. """
  195. return mapping.from_impl_nullable(self._impl_obj.redirected_from)
  196. @property
  197. def redirected_to(self) -> typing.Optional["Request"]:
  198. """Request.redirected_to
  199. New request issued by the browser if the server responded with redirect.
  200. **Usage**
  201. This method is the opposite of `request.redirected_from()`:
  202. ```py
  203. assert request.redirected_from.redirected_to == request
  204. ```
  205. Returns
  206. -------
  207. Union[Request, None]
  208. """
  209. return mapping.from_impl_nullable(self._impl_obj.redirected_to)
  210. @property
  211. def failure(self) -> typing.Optional[str]:
  212. """Request.failure
  213. The method returns `null` unless this request has failed, as reported by `requestfailed` event.
  214. **Usage**
  215. Example of logging of all the failed requests:
  216. ```py
  217. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure))
  218. ```
  219. Returns
  220. -------
  221. Union[str, None]
  222. """
  223. return mapping.from_maybe_impl(self._impl_obj.failure)
  224. @property
  225. def timing(self) -> ResourceTiming:
  226. """Request.timing
  227. Returns resource timing information for given request. Most of the timing values become available upon the
  228. response, `responseEnd` becomes available when request finishes. Find more information at
  229. [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
  230. **Usage**
  231. ```py
  232. with page.expect_event(\"requestfinished\") as request_info:
  233. page.goto(\"http://example.com\")
  234. request = request_info.value
  235. print(request.timing)
  236. ```
  237. Returns
  238. -------
  239. {startTime: float, domainLookupStart: float, domainLookupEnd: float, connectStart: float, secureConnectionStart: float, connectEnd: float, requestStart: float, responseStart: float, responseEnd: float}
  240. """
  241. return mapping.from_impl(self._impl_obj.timing)
  242. @property
  243. def headers(self) -> typing.Dict[str, str]:
  244. """Request.headers
  245. An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return
  246. security-related headers, including cookie-related ones. You can use `request.all_headers()` for complete
  247. list of headers that include `cookie` information.
  248. Returns
  249. -------
  250. Dict[str, str]
  251. """
  252. return mapping.from_maybe_impl(self._impl_obj.headers)
  253. def sizes(self) -> RequestSizes:
  254. """Request.sizes
  255. Returns resource size information for given request.
  256. Returns
  257. -------
  258. {requestBodySize: int, requestHeadersSize: int, responseBodySize: int, responseHeadersSize: int}
  259. """
  260. return mapping.from_impl(self._sync(self._impl_obj.sizes()))
  261. def response(self) -> typing.Optional["Response"]:
  262. """Request.response
  263. Returns the matching `Response` object, or `null` if the response was not received due to error.
  264. Returns
  265. -------
  266. Union[Response, None]
  267. """
  268. return mapping.from_impl_nullable(self._sync(self._impl_obj.response()))
  269. def is_navigation_request(self) -> bool:
  270. """Request.is_navigation_request
  271. Whether this request is driving frame's navigation.
  272. Some navigation requests are issued before the corresponding frame is created, and therefore do not have
  273. `request.frame()` available.
  274. Returns
  275. -------
  276. bool
  277. """
  278. return mapping.from_maybe_impl(self._impl_obj.is_navigation_request())
  279. def all_headers(self) -> typing.Dict[str, str]:
  280. """Request.all_headers
  281. An object with all the request HTTP headers associated with this request. The header names are lower-cased.
  282. Returns
  283. -------
  284. Dict[str, str]
  285. """
  286. return mapping.from_maybe_impl(self._sync(self._impl_obj.all_headers()))
  287. def headers_array(self) -> typing.List[NameValue]:
  288. """Request.headers_array
  289. An array with all the request HTTP headers associated with this request. Unlike `request.all_headers()`,
  290. header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
  291. times.
  292. Returns
  293. -------
  294. List[{name: str, value: str}]
  295. """
  296. return mapping.from_impl_list(self._sync(self._impl_obj.headers_array()))
  297. def header_value(self, name: str) -> typing.Optional[str]:
  298. """Request.header_value
  299. Returns the value of the header matching the name. The name is case-insensitive.
  300. Parameters
  301. ----------
  302. name : str
  303. Name of the header.
  304. Returns
  305. -------
  306. Union[str, None]
  307. """
  308. return mapping.from_maybe_impl(
  309. self._sync(self._impl_obj.header_value(name=name))
  310. )
  311. mapping.register(RequestImpl, Request)
  312. class Response(SyncBase):
  313. @property
  314. def url(self) -> str:
  315. """Response.url
  316. Contains the URL of the response.
  317. Returns
  318. -------
  319. str
  320. """
  321. return mapping.from_maybe_impl(self._impl_obj.url)
  322. @property
  323. def ok(self) -> bool:
  324. """Response.ok
  325. Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
  326. Returns
  327. -------
  328. bool
  329. """
  330. return mapping.from_maybe_impl(self._impl_obj.ok)
  331. @property
  332. def status(self) -> int:
  333. """Response.status
  334. Contains the status code of the response (e.g., 200 for a success).
  335. Returns
  336. -------
  337. int
  338. """
  339. return mapping.from_maybe_impl(self._impl_obj.status)
  340. @property
  341. def status_text(self) -> str:
  342. """Response.status_text
  343. Contains the status text of the response (e.g. usually an \"OK\" for a success).
  344. Returns
  345. -------
  346. str
  347. """
  348. return mapping.from_maybe_impl(self._impl_obj.status_text)
  349. @property
  350. def headers(self) -> typing.Dict[str, str]:
  351. """Response.headers
  352. An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return
  353. security-related headers, including cookie-related ones. You can use `response.all_headers()` for complete
  354. list of headers that include `cookie` information.
  355. Returns
  356. -------
  357. Dict[str, str]
  358. """
  359. return mapping.from_maybe_impl(self._impl_obj.headers)
  360. @property
  361. def from_service_worker(self) -> bool:
  362. """Response.from_service_worker
  363. Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via
  364. [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).
  365. Returns
  366. -------
  367. bool
  368. """
  369. return mapping.from_maybe_impl(self._impl_obj.from_service_worker)
  370. @property
  371. def request(self) -> "Request":
  372. """Response.request
  373. Returns the matching `Request` object.
  374. Returns
  375. -------
  376. Request
  377. """
  378. return mapping.from_impl(self._impl_obj.request)
  379. @property
  380. def frame(self) -> "Frame":
  381. """Response.frame
  382. Returns the `Frame` that initiated this response.
  383. Returns
  384. -------
  385. Frame
  386. """
  387. return mapping.from_impl(self._impl_obj.frame)
  388. def all_headers(self) -> typing.Dict[str, str]:
  389. """Response.all_headers
  390. An object with all the response HTTP headers associated with this response.
  391. Returns
  392. -------
  393. Dict[str, str]
  394. """
  395. return mapping.from_maybe_impl(self._sync(self._impl_obj.all_headers()))
  396. def headers_array(self) -> typing.List[NameValue]:
  397. """Response.headers_array
  398. An array with all the request HTTP headers associated with this response. Unlike `response.all_headers()`,
  399. header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
  400. times.
  401. Returns
  402. -------
  403. List[{name: str, value: str}]
  404. """
  405. return mapping.from_impl_list(self._sync(self._impl_obj.headers_array()))
  406. def header_value(self, name: str) -> typing.Optional[str]:
  407. """Response.header_value
  408. Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same
  409. name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\\n` separator is
  410. used. If no headers are found, `null` is returned.
  411. Parameters
  412. ----------
  413. name : str
  414. Name of the header.
  415. Returns
  416. -------
  417. Union[str, None]
  418. """
  419. return mapping.from_maybe_impl(
  420. self._sync(self._impl_obj.header_value(name=name))
  421. )
  422. def header_values(self, name: str) -> typing.List[str]:
  423. """Response.header_values
  424. Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.
  425. Parameters
  426. ----------
  427. name : str
  428. Name of the header.
  429. Returns
  430. -------
  431. List[str]
  432. """
  433. return mapping.from_maybe_impl(
  434. self._sync(self._impl_obj.header_values(name=name))
  435. )
  436. def server_addr(self) -> typing.Optional[RemoteAddr]:
  437. """Response.server_addr
  438. Returns the IP address and port of the server.
  439. Returns
  440. -------
  441. Union[{ipAddress: str, port: int}, None]
  442. """
  443. return mapping.from_impl_nullable(self._sync(self._impl_obj.server_addr()))
  444. def security_details(self) -> typing.Optional[SecurityDetails]:
  445. """Response.security_details
  446. Returns SSL and other security information.
  447. Returns
  448. -------
  449. Union[{issuer: Union[str, None], protocol: Union[str, None], subjectName: Union[str, None], validFrom: Union[float, None], validTo: Union[float, None]}, None]
  450. """
  451. return mapping.from_impl_nullable(self._sync(self._impl_obj.security_details()))
  452. def finished(self) -> None:
  453. """Response.finished
  454. Waits for this response to finish, returns always `null`.
  455. """
  456. return mapping.from_maybe_impl(self._sync(self._impl_obj.finished()))
  457. def body(self) -> bytes:
  458. """Response.body
  459. Returns the buffer with response body.
  460. Returns
  461. -------
  462. bytes
  463. """
  464. return mapping.from_maybe_impl(self._sync(self._impl_obj.body()))
  465. def text(self) -> str:
  466. """Response.text
  467. Returns the text representation of response body.
  468. Returns
  469. -------
  470. str
  471. """
  472. return mapping.from_maybe_impl(self._sync(self._impl_obj.text()))
  473. def json(self) -> typing.Any:
  474. """Response.json
  475. Returns the JSON representation of response body.
  476. This method will throw if the response body is not parsable via `JSON.parse`.
  477. Returns
  478. -------
  479. Any
  480. """
  481. return mapping.from_maybe_impl(self._sync(self._impl_obj.json()))
  482. mapping.register(ResponseImpl, Response)
  483. class Route(SyncBase):
  484. @property
  485. def request(self) -> "Request":
  486. """Route.request
  487. A request to be routed.
  488. Returns
  489. -------
  490. Request
  491. """
  492. return mapping.from_impl(self._impl_obj.request)
  493. def abort(self, error_code: typing.Optional[str] = None) -> None:
  494. """Route.abort
  495. Aborts the route's request.
  496. Parameters
  497. ----------
  498. error_code : Union[str, None]
  499. Optional error code. Defaults to `failed`, could be one of the following:
  500. - `'aborted'` - An operation was aborted (due to user action)
  501. - `'accessdenied'` - Permission to access a resource, other than the network, was denied
  502. - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the
  503. specified host or network.
  504. - `'blockedbyclient'` - The client chose to block the request.
  505. - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are
  506. not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
  507. - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
  508. - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
  509. - `'connectionfailed'` - A connection attempt failed.
  510. - `'connectionrefused'` - A connection attempt was refused.
  511. - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
  512. - `'internetdisconnected'` - The Internet connection has been lost.
  513. - `'namenotresolved'` - The host name could not be resolved.
  514. - `'timedout'` - An operation timed out.
  515. - `'failed'` - A generic failure occurred.
  516. """
  517. return mapping.from_maybe_impl(
  518. self._sync(self._impl_obj.abort(errorCode=error_code))
  519. )
  520. def fulfill(
  521. self,
  522. *,
  523. status: typing.Optional[int] = None,
  524. headers: typing.Optional[typing.Dict[str, str]] = None,
  525. body: typing.Optional[typing.Union[str, bytes]] = None,
  526. json: typing.Optional[typing.Any] = None,
  527. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  528. content_type: typing.Optional[str] = None,
  529. response: typing.Optional["APIResponse"] = None,
  530. ) -> None:
  531. """Route.fulfill
  532. Fulfills route's request with given response.
  533. **Usage**
  534. An example of fulfilling all requests with 404 responses:
  535. ```py
  536. page.route(\"**/*\", lambda route: route.fulfill(
  537. status=404,
  538. content_type=\"text/plain\",
  539. body=\"not found!\"))
  540. ```
  541. An example of serving static file:
  542. ```py
  543. page.route(\"**/xhr_endpoint\", lambda route: route.fulfill(path=\"mock_data.json\"))
  544. ```
  545. Parameters
  546. ----------
  547. status : Union[int, None]
  548. Response status code, defaults to `200`.
  549. headers : Union[Dict[str, str], None]
  550. Response headers. Header values will be converted to a string.
  551. body : Union[bytes, str, None]
  552. Response body.
  553. json : Union[Any, None]
  554. JSON response. This method will set the content type to `application/json` if not set.
  555. path : Union[pathlib.Path, str, None]
  556. File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,
  557. then it is resolved relative to the current working directory.
  558. content_type : Union[str, None]
  559. If set, equals to setting `Content-Type` response header.
  560. response : Union[APIResponse, None]
  561. `APIResponse` to fulfill route's request with. Individual fields of the response (such as headers) can be
  562. overridden using fulfill options.
  563. """
  564. return mapping.from_maybe_impl(
  565. self._sync(
  566. self._impl_obj.fulfill(
  567. status=status,
  568. headers=mapping.to_impl(headers),
  569. body=body,
  570. json=mapping.to_impl(json),
  571. path=path,
  572. contentType=content_type,
  573. response=response._impl_obj if response else None,
  574. )
  575. )
  576. )
  577. def fetch(
  578. self,
  579. *,
  580. url: typing.Optional[str] = None,
  581. method: typing.Optional[str] = None,
  582. headers: typing.Optional[typing.Dict[str, str]] = None,
  583. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  584. max_redirects: typing.Optional[int] = None,
  585. max_retries: typing.Optional[int] = None,
  586. timeout: typing.Optional[float] = None,
  587. ) -> "APIResponse":
  588. """Route.fetch
  589. Performs the request and fetches result without fulfilling it, so that the response could be modified and then
  590. fulfilled.
  591. **Usage**
  592. ```py
  593. def handle(route):
  594. response = route.fetch()
  595. json = response.json()
  596. json[\"message\"][\"big_red_dog\"] = []
  597. route.fulfill(response=response, json=json)
  598. page.route(\"https://dog.ceo/api/breeds/list/all\", handle)
  599. ```
  600. **Details**
  601. Note that `headers` option will apply to the fetched request as well as any redirects initiated by it. If you want
  602. to only apply `headers` to the original request, but not to redirects, look into `route.continue_()`
  603. instead.
  604. Parameters
  605. ----------
  606. url : Union[str, None]
  607. If set changes the request URL. New URL must have same protocol as original one.
  608. method : Union[str, None]
  609. If set changes the request method (e.g. GET or POST).
  610. headers : Union[Dict[str, str], None]
  611. If set changes the request HTTP headers. Header values will be converted to a string.
  612. post_data : Union[Any, bytes, str, None]
  613. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  614. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  615. header will be set to `application/octet-stream` if not explicitly set.
  616. max_redirects : Union[int, None]
  617. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  618. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  619. max_retries : Union[int, None]
  620. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  621. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  622. timeout : Union[float, None]
  623. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  624. Returns
  625. -------
  626. APIResponse
  627. """
  628. return mapping.from_impl(
  629. self._sync(
  630. self._impl_obj.fetch(
  631. url=url,
  632. method=method,
  633. headers=mapping.to_impl(headers),
  634. postData=mapping.to_impl(post_data),
  635. maxRedirects=max_redirects,
  636. maxRetries=max_retries,
  637. timeout=timeout,
  638. )
  639. )
  640. )
  641. def fallback(
  642. self,
  643. *,
  644. url: typing.Optional[str] = None,
  645. method: typing.Optional[str] = None,
  646. headers: typing.Optional[typing.Dict[str, str]] = None,
  647. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  648. ) -> None:
  649. """Route.fallback
  650. Continues route's request with optional overrides. The method is similar to `route.continue_()` with the
  651. difference that other matching handlers will be invoked before sending the request.
  652. **Usage**
  653. When several routes match the given pattern, they run in the order opposite to their registration. That way the
  654. last registered route can always override all the previous ones. In the example below, request will be handled by
  655. the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
  656. registered route.
  657. ```py
  658. page.route(\"**/*\", lambda route: route.abort()) # Runs last.
  659. page.route(\"**/*\", lambda route: route.fallback()) # Runs second.
  660. page.route(\"**/*\", lambda route: route.fallback()) # Runs first.
  661. ```
  662. Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for
  663. example API calls vs page resources or GET requests vs POST requests as in the example below.
  664. ```py
  665. # Handle GET requests.
  666. def handle_get(route):
  667. if route.request.method != \"GET\":
  668. route.fallback()
  669. return
  670. # Handling GET only.
  671. # ...
  672. # Handle POST requests.
  673. def handle_post(route):
  674. if route.request.method != \"POST\":
  675. route.fallback()
  676. return
  677. # Handling POST only.
  678. # ...
  679. page.route(\"**/*\", handle_get)
  680. page.route(\"**/*\", handle_post)
  681. ```
  682. One can also modify request while falling back to the subsequent handler, that way intermediate route handler can
  683. modify url, method, headers and postData of the request.
  684. ```py
  685. def handle(route, request):
  686. # override headers
  687. headers = {
  688. **request.headers,
  689. \"foo\": \"foo-value\", # set \"foo\" header
  690. \"bar\": None # remove \"bar\" header
  691. }
  692. route.fallback(headers=headers)
  693. page.route(\"**/*\", handle)
  694. ```
  695. Use `route.continue_()` to immediately send the request to the network, other matching handlers won't be
  696. invoked in that case.
  697. Parameters
  698. ----------
  699. url : Union[str, None]
  700. If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the
  701. route matching, all the routes are matched using the original request URL.
  702. method : Union[str, None]
  703. If set changes the request method (e.g. GET or POST).
  704. headers : Union[Dict[str, str], None]
  705. If set changes the request HTTP headers. Header values will be converted to a string.
  706. post_data : Union[Any, bytes, str, None]
  707. If set changes the post data of request.
  708. """
  709. return mapping.from_maybe_impl(
  710. self._sync(
  711. self._impl_obj.fallback(
  712. url=url,
  713. method=method,
  714. headers=mapping.to_impl(headers),
  715. postData=mapping.to_impl(post_data),
  716. )
  717. )
  718. )
  719. def continue_(
  720. self,
  721. *,
  722. url: typing.Optional[str] = None,
  723. method: typing.Optional[str] = None,
  724. headers: typing.Optional[typing.Dict[str, str]] = None,
  725. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  726. ) -> None:
  727. """Route.continue_
  728. Sends route's request to the network with optional overrides.
  729. **Usage**
  730. ```py
  731. def handle(route, request):
  732. # override headers
  733. headers = {
  734. **request.headers,
  735. \"foo\": \"foo-value\", # set \"foo\" header
  736. \"bar\": None # remove \"bar\" header
  737. }
  738. route.continue_(headers=headers)
  739. page.route(\"**/*\", handle)
  740. ```
  741. **Details**
  742. The `headers` option applies to both the routed request and any redirects it initiates. However, `url`, `method`,
  743. and `postData` only apply to the original request and are not carried over to redirected requests.
  744. `route.continue_()` will immediately send the request to the network, other matching handlers won't be
  745. invoked. Use `route.fallback()` If you want next matching handler in the chain to be invoked.
  746. **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,
  747. `Content-Length` and others, see
  748. [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an
  749. override is provided for a forbidden header, it will be ignored and the original request header will be used.
  750. To set custom cookies, use `browser_context.add_cookies()`.
  751. Parameters
  752. ----------
  753. url : Union[str, None]
  754. If set changes the request URL. New URL must have same protocol as original one.
  755. method : Union[str, None]
  756. If set changes the request method (e.g. GET or POST).
  757. headers : Union[Dict[str, str], None]
  758. If set changes the request HTTP headers. Header values will be converted to a string.
  759. post_data : Union[Any, bytes, str, None]
  760. If set changes the post data of request.
  761. """
  762. return mapping.from_maybe_impl(
  763. self._sync(
  764. self._impl_obj.continue_(
  765. url=url,
  766. method=method,
  767. headers=mapping.to_impl(headers),
  768. postData=mapping.to_impl(post_data),
  769. )
  770. )
  771. )
  772. mapping.register(RouteImpl, Route)
  773. class WebSocket(SyncBase):
  774. @typing.overload
  775. def on(
  776. self, event: Literal["close"], f: typing.Callable[["WebSocket"], "None"]
  777. ) -> None:
  778. """
  779. Fired when the websocket closes."""
  780. @typing.overload
  781. def on(
  782. self,
  783. event: Literal["framereceived"],
  784. f: typing.Callable[["typing.Union[bytes, str]"], "None"],
  785. ) -> None:
  786. """
  787. Fired when the websocket receives a frame."""
  788. @typing.overload
  789. def on(
  790. self,
  791. event: Literal["framesent"],
  792. f: typing.Callable[["typing.Union[bytes, str]"], "None"],
  793. ) -> None:
  794. """
  795. Fired when the websocket sends a frame."""
  796. @typing.overload
  797. def on(
  798. self, event: Literal["socketerror"], f: typing.Callable[["str"], "None"]
  799. ) -> None:
  800. """
  801. Fired when the websocket has an error."""
  802. def on(self, event: str, f: typing.Callable[..., None]) -> None:
  803. return super().on(event=event, f=f)
  804. @typing.overload
  805. def once(
  806. self, event: Literal["close"], f: typing.Callable[["WebSocket"], "None"]
  807. ) -> None:
  808. """
  809. Fired when the websocket closes."""
  810. @typing.overload
  811. def once(
  812. self,
  813. event: Literal["framereceived"],
  814. f: typing.Callable[["typing.Union[bytes, str]"], "None"],
  815. ) -> None:
  816. """
  817. Fired when the websocket receives a frame."""
  818. @typing.overload
  819. def once(
  820. self,
  821. event: Literal["framesent"],
  822. f: typing.Callable[["typing.Union[bytes, str]"], "None"],
  823. ) -> None:
  824. """
  825. Fired when the websocket sends a frame."""
  826. @typing.overload
  827. def once(
  828. self, event: Literal["socketerror"], f: typing.Callable[["str"], "None"]
  829. ) -> None:
  830. """
  831. Fired when the websocket has an error."""
  832. def once(self, event: str, f: typing.Callable[..., None]) -> None:
  833. return super().once(event=event, f=f)
  834. @property
  835. def url(self) -> str:
  836. """WebSocket.url
  837. Contains the URL of the WebSocket.
  838. Returns
  839. -------
  840. str
  841. """
  842. return mapping.from_maybe_impl(self._impl_obj.url)
  843. def expect_event(
  844. self,
  845. event: str,
  846. predicate: typing.Optional[typing.Callable] = None,
  847. *,
  848. timeout: typing.Optional[float] = None,
  849. ) -> EventContextManager:
  850. """WebSocket.expect_event
  851. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  852. value. Will throw an error if the webSocket is closed before the event is fired. Returns the event data value.
  853. Parameters
  854. ----------
  855. event : str
  856. Event name, same one would pass into `webSocket.on(event)`.
  857. predicate : Union[Callable, None]
  858. Receives the event data and resolves to truthy value when the waiting should resolve.
  859. timeout : Union[float, None]
  860. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  861. default value can be changed by using the `browser_context.set_default_timeout()`.
  862. Returns
  863. -------
  864. EventContextManager
  865. """
  866. return EventContextManager(
  867. self,
  868. self._impl_obj.expect_event(
  869. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  870. ).future,
  871. )
  872. def wait_for_event(
  873. self,
  874. event: str,
  875. predicate: typing.Optional[typing.Callable] = None,
  876. *,
  877. timeout: typing.Optional[float] = None,
  878. ) -> typing.Any:
  879. """WebSocket.wait_for_event
  880. **NOTE** In most cases, you should use `web_socket.expect_event()`.
  881. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  882. and waits for `predicate(event)` to return a truthy value. Will throw an error if the socket is closed before the
  883. `event` is fired.
  884. Parameters
  885. ----------
  886. event : str
  887. Event name, same one typically passed into `*.on(event)`.
  888. predicate : Union[Callable, None]
  889. Receives the event data and resolves to truthy value when the waiting should resolve.
  890. timeout : Union[float, None]
  891. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  892. default value can be changed by using the `browser_context.set_default_timeout()`.
  893. Returns
  894. -------
  895. Any
  896. """
  897. return mapping.from_maybe_impl(
  898. self._sync(
  899. self._impl_obj.wait_for_event(
  900. event=event,
  901. predicate=self._wrap_handler(predicate),
  902. timeout=timeout,
  903. )
  904. )
  905. )
  906. def is_closed(self) -> bool:
  907. """WebSocket.is_closed
  908. Indicates that the web socket has been closed.
  909. Returns
  910. -------
  911. bool
  912. """
  913. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  914. mapping.register(WebSocketImpl, WebSocket)
  915. class WebSocketRoute(SyncBase):
  916. @property
  917. def url(self) -> str:
  918. """WebSocketRoute.url
  919. URL of the WebSocket created in the page.
  920. Returns
  921. -------
  922. str
  923. """
  924. return mapping.from_maybe_impl(self._impl_obj.url)
  925. def close(
  926. self, *, code: typing.Optional[int] = None, reason: typing.Optional[str] = None
  927. ) -> None:
  928. """WebSocketRoute.close
  929. Closes one side of the WebSocket connection.
  930. Parameters
  931. ----------
  932. code : Union[int, None]
  933. Optional [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code).
  934. reason : Union[str, None]
  935. Optional [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
  936. """
  937. return mapping.from_maybe_impl(
  938. self._sync(self._impl_obj.close(code=code, reason=reason))
  939. )
  940. def connect_to_server(self) -> "WebSocketRoute":
  941. """WebSocketRoute.connect_to_server
  942. By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This
  943. method connects to the actual WebSocket server, and returns the server-side `WebSocketRoute` instance, giving the
  944. ability to send and receive messages from the server.
  945. Once connected to the server:
  946. - Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless
  947. `web_socket_route.on_message()` is called on the server-side `WebSocketRoute`.
  948. - Messages sent by the [`WebSocket.send()`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) call
  949. in the page will be **automatically forwarded** to the server, unless `web_socket_route.on_message()` is
  950. called on the original `WebSocketRoute`.
  951. See examples at the top for more details.
  952. Returns
  953. -------
  954. WebSocketRoute
  955. """
  956. return mapping.from_impl(self._impl_obj.connect_to_server())
  957. def send(self, message: typing.Union[str, bytes]) -> None:
  958. """WebSocketRoute.send
  959. Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called
  960. on the result of `web_socket_route.connect_to_server()`, sends the message to the server. See examples at the
  961. top for more details.
  962. Parameters
  963. ----------
  964. message : Union[bytes, str]
  965. Message to send.
  966. """
  967. return mapping.from_maybe_impl(self._impl_obj.send(message=message))
  968. def on_message(
  969. self, handler: typing.Callable[[typing.Union[str, bytes]], typing.Any]
  970. ) -> None:
  971. """WebSocketRoute.on_message
  972. This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.
  973. When called on the original WebSocket route, this method handles messages sent from the page. You can handle this
  974. messages by responding to them with `web_socket_route.send()`, forwarding them to the server-side connection
  975. returned by `web_socket_route.connect_to_server()` or do something else.
  976. Once this method is called, messages are not automatically forwarded to the server or to the page - you should do
  977. that manually by calling `web_socket_route.send()`. See examples at the top for more details.
  978. Calling this method again will override the handler with a new one.
  979. Parameters
  980. ----------
  981. handler : Callable[[Union[bytes, str]], Any]
  982. Function that will handle messages.
  983. """
  984. return mapping.from_maybe_impl(
  985. self._impl_obj.on_message(handler=self._wrap_handler(handler))
  986. )
  987. def on_close(
  988. self,
  989. handler: typing.Callable[
  990. [typing.Optional[int], typing.Optional[str]], typing.Any
  991. ],
  992. ) -> None:
  993. """WebSocketRoute.on_close
  994. Allows to handle [`WebSocket.close`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close).
  995. By default, closing one side of the connection, either in the page or on the server, will close the other side.
  996. However, when `web_socket_route.on_close()` handler is set up, the default forwarding of closure is disabled,
  997. and handler should take care of it.
  998. Parameters
  999. ----------
  1000. handler : Callable[[Union[int, None], Union[str, None]], Any]
  1001. Function that will handle WebSocket closure. Received an optional
  1002. [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code) and an optional
  1003. [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
  1004. """
  1005. return mapping.from_maybe_impl(
  1006. self._impl_obj.on_close(handler=self._wrap_handler(handler))
  1007. )
  1008. mapping.register(WebSocketRouteImpl, WebSocketRoute)
  1009. class Keyboard(SyncBase):
  1010. def down(self, key: str) -> None:
  1011. """Keyboard.down
  1012. Dispatches a `keydown` event.
  1013. `key` can specify the intended
  1014. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  1015. to generate the text for. A superset of the `key` values can be found
  1016. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  1017. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  1018. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  1019. etc.
  1020. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  1021. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  1022. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  1023. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  1024. texts.
  1025. If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that
  1026. modifier active. To release the modifier key, use `keyboard.up()`.
  1027. After the key is pressed once, subsequent calls to `keyboard.down()` will have
  1028. [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,
  1029. use `keyboard.up()`.
  1030. **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
  1031. Parameters
  1032. ----------
  1033. key : str
  1034. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1035. """
  1036. return mapping.from_maybe_impl(self._sync(self._impl_obj.down(key=key)))
  1037. def up(self, key: str) -> None:
  1038. """Keyboard.up
  1039. Dispatches a `keyup` event.
  1040. Parameters
  1041. ----------
  1042. key : str
  1043. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1044. """
  1045. return mapping.from_maybe_impl(self._sync(self._impl_obj.up(key=key)))
  1046. def insert_text(self, text: str) -> None:
  1047. """Keyboard.insert_text
  1048. Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
  1049. **Usage**
  1050. ```py
  1051. page.keyboard.insert_text(\"嗨\")
  1052. ```
  1053. **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper
  1054. case.
  1055. Parameters
  1056. ----------
  1057. text : str
  1058. Sets input to the specified text value.
  1059. """
  1060. return mapping.from_maybe_impl(
  1061. self._sync(self._impl_obj.insert_text(text=text))
  1062. )
  1063. def type(self, text: str, *, delay: typing.Optional[float] = None) -> None:
  1064. """Keyboard.type
  1065. **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
  1066. there is special keyboard handling on the page - in this case use `locator.press_sequentially()`.
  1067. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
  1068. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  1069. **Usage**
  1070. ```py
  1071. page.keyboard.type(\"Hello\") # types instantly
  1072. page.keyboard.type(\"World\", delay=100) # types slower, like a user
  1073. ```
  1074. **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.
  1075. **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.
  1076. Parameters
  1077. ----------
  1078. text : str
  1079. A text to type into a focused element.
  1080. delay : Union[float, None]
  1081. Time to wait between key presses in milliseconds. Defaults to 0.
  1082. """
  1083. return mapping.from_maybe_impl(
  1084. self._sync(self._impl_obj.type(text=text, delay=delay))
  1085. )
  1086. def press(self, key: str, *, delay: typing.Optional[float] = None) -> None:
  1087. """Keyboard.press
  1088. **NOTE** In most cases, you should use `locator.press()` instead.
  1089. `key` can specify the intended
  1090. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  1091. to generate the text for. A superset of the `key` values can be found
  1092. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  1093. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  1094. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  1095. etc.
  1096. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  1097. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  1098. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  1099. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  1100. texts.
  1101. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  1102. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  1103. **Usage**
  1104. ```py
  1105. page = browser.new_page()
  1106. page.goto(\"https://keycode.info\")
  1107. page.keyboard.press(\"a\")
  1108. page.screenshot(path=\"a.png\")
  1109. page.keyboard.press(\"ArrowLeft\")
  1110. page.screenshot(path=\"arrow_left.png\")
  1111. page.keyboard.press(\"Shift+O\")
  1112. page.screenshot(path=\"o.png\")
  1113. browser.close()
  1114. ```
  1115. Shortcut for `keyboard.down()` and `keyboard.up()`.
  1116. Parameters
  1117. ----------
  1118. key : str
  1119. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1120. delay : Union[float, None]
  1121. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  1122. """
  1123. return mapping.from_maybe_impl(
  1124. self._sync(self._impl_obj.press(key=key, delay=delay))
  1125. )
  1126. mapping.register(KeyboardImpl, Keyboard)
  1127. class Mouse(SyncBase):
  1128. def move(self, x: float, y: float, *, steps: typing.Optional[int] = None) -> None:
  1129. """Mouse.move
  1130. Dispatches a `mousemove` event.
  1131. Parameters
  1132. ----------
  1133. x : float
  1134. X coordinate relative to the main frame's viewport in CSS pixels.
  1135. y : float
  1136. Y coordinate relative to the main frame's viewport in CSS pixels.
  1137. steps : Union[int, None]
  1138. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1139. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1140. """
  1141. return mapping.from_maybe_impl(
  1142. self._sync(self._impl_obj.move(x=x, y=y, steps=steps))
  1143. )
  1144. def down(
  1145. self,
  1146. *,
  1147. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1148. click_count: typing.Optional[int] = None,
  1149. ) -> None:
  1150. """Mouse.down
  1151. Dispatches a `mousedown` event.
  1152. Parameters
  1153. ----------
  1154. button : Union["left", "middle", "right", None]
  1155. Defaults to `left`.
  1156. click_count : Union[int, None]
  1157. defaults to 1. See [UIEvent.detail].
  1158. """
  1159. return mapping.from_maybe_impl(
  1160. self._sync(self._impl_obj.down(button=button, clickCount=click_count))
  1161. )
  1162. def up(
  1163. self,
  1164. *,
  1165. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1166. click_count: typing.Optional[int] = None,
  1167. ) -> None:
  1168. """Mouse.up
  1169. Dispatches a `mouseup` event.
  1170. Parameters
  1171. ----------
  1172. button : Union["left", "middle", "right", None]
  1173. Defaults to `left`.
  1174. click_count : Union[int, None]
  1175. defaults to 1. See [UIEvent.detail].
  1176. """
  1177. return mapping.from_maybe_impl(
  1178. self._sync(self._impl_obj.up(button=button, clickCount=click_count))
  1179. )
  1180. def click(
  1181. self,
  1182. x: float,
  1183. y: float,
  1184. *,
  1185. delay: typing.Optional[float] = None,
  1186. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1187. click_count: typing.Optional[int] = None,
  1188. ) -> None:
  1189. """Mouse.click
  1190. Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`.
  1191. Parameters
  1192. ----------
  1193. x : float
  1194. X coordinate relative to the main frame's viewport in CSS pixels.
  1195. y : float
  1196. Y coordinate relative to the main frame's viewport in CSS pixels.
  1197. delay : Union[float, None]
  1198. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1199. button : Union["left", "middle", "right", None]
  1200. Defaults to `left`.
  1201. click_count : Union[int, None]
  1202. defaults to 1. See [UIEvent.detail].
  1203. """
  1204. return mapping.from_maybe_impl(
  1205. self._sync(
  1206. self._impl_obj.click(
  1207. x=x, y=y, delay=delay, button=button, clickCount=click_count
  1208. )
  1209. )
  1210. )
  1211. def dblclick(
  1212. self,
  1213. x: float,
  1214. y: float,
  1215. *,
  1216. delay: typing.Optional[float] = None,
  1217. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1218. ) -> None:
  1219. """Mouse.dblclick
  1220. Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`, `mouse.down()` and
  1221. `mouse.up()`.
  1222. Parameters
  1223. ----------
  1224. x : float
  1225. X coordinate relative to the main frame's viewport in CSS pixels.
  1226. y : float
  1227. Y coordinate relative to the main frame's viewport in CSS pixels.
  1228. delay : Union[float, None]
  1229. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1230. button : Union["left", "middle", "right", None]
  1231. Defaults to `left`.
  1232. """
  1233. return mapping.from_maybe_impl(
  1234. self._sync(self._impl_obj.dblclick(x=x, y=y, delay=delay, button=button))
  1235. )
  1236. def wheel(self, delta_x: float, delta_y: float) -> None:
  1237. """Mouse.wheel
  1238. Dispatches a `wheel` event. This method is usually used to manually scroll the page. See
  1239. [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  1240. **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling
  1241. to finish before returning.
  1242. Parameters
  1243. ----------
  1244. delta_x : float
  1245. Pixels to scroll horizontally.
  1246. delta_y : float
  1247. Pixels to scroll vertically.
  1248. """
  1249. return mapping.from_maybe_impl(
  1250. self._sync(self._impl_obj.wheel(deltaX=delta_x, deltaY=delta_y))
  1251. )
  1252. mapping.register(MouseImpl, Mouse)
  1253. class Touchscreen(SyncBase):
  1254. def tap(self, x: float, y: float) -> None:
  1255. """Touchscreen.tap
  1256. Dispatches a `touchstart` and `touchend` event with a single touch at the position (`x`,`y`).
  1257. **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
  1258. Parameters
  1259. ----------
  1260. x : float
  1261. X coordinate relative to the main frame's viewport in CSS pixels.
  1262. y : float
  1263. Y coordinate relative to the main frame's viewport in CSS pixels.
  1264. """
  1265. return mapping.from_maybe_impl(self._sync(self._impl_obj.tap(x=x, y=y)))
  1266. mapping.register(TouchscreenImpl, Touchscreen)
  1267. class JSHandle(SyncBase):
  1268. def evaluate(
  1269. self, expression: str, arg: typing.Optional[typing.Any] = None
  1270. ) -> typing.Any:
  1271. """JSHandle.evaluate
  1272. Returns the return value of `expression`.
  1273. This method passes this handle as the first argument to `expression`.
  1274. If `expression` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
  1275. value.
  1276. **Usage**
  1277. ```py
  1278. tweet_handle = page.query_selector(\".tweet .retweets\")
  1279. assert tweet_handle.evaluate(\"node => node.innerText\") == \"10 retweets\"
  1280. ```
  1281. Parameters
  1282. ----------
  1283. expression : str
  1284. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  1285. function is automatically invoked.
  1286. arg : Union[Any, None]
  1287. Optional argument to pass to `expression`.
  1288. Returns
  1289. -------
  1290. Any
  1291. """
  1292. return mapping.from_maybe_impl(
  1293. self._sync(
  1294. self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
  1295. )
  1296. )
  1297. def evaluate_handle(
  1298. self, expression: str, arg: typing.Optional[typing.Any] = None
  1299. ) -> "JSHandle":
  1300. """JSHandle.evaluate_handle
  1301. Returns the return value of `expression` as a `JSHandle`.
  1302. This method passes this handle as the first argument to `expression`.
  1303. The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
  1304. returns `JSHandle`.
  1305. If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
  1306. wait for the promise to resolve and return its value.
  1307. See `page.evaluate_handle()` for more details.
  1308. Parameters
  1309. ----------
  1310. expression : str
  1311. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  1312. function is automatically invoked.
  1313. arg : Union[Any, None]
  1314. Optional argument to pass to `expression`.
  1315. Returns
  1316. -------
  1317. JSHandle
  1318. """
  1319. return mapping.from_impl(
  1320. self._sync(
  1321. self._impl_obj.evaluate_handle(
  1322. expression=expression, arg=mapping.to_impl(arg)
  1323. )
  1324. )
  1325. )
  1326. def get_property(self, property_name: str) -> "JSHandle":
  1327. """JSHandle.get_property
  1328. Fetches a single property from the referenced object.
  1329. Parameters
  1330. ----------
  1331. property_name : str
  1332. property to get
  1333. Returns
  1334. -------
  1335. JSHandle
  1336. """
  1337. return mapping.from_impl(
  1338. self._sync(self._impl_obj.get_property(propertyName=property_name))
  1339. )
  1340. def get_properties(self) -> typing.Dict[str, "JSHandle"]:
  1341. """JSHandle.get_properties
  1342. The method returns a map with **own property names** as keys and JSHandle instances for the property values.
  1343. **Usage**
  1344. ```py
  1345. handle = page.evaluate_handle(\"({ window, document })\")
  1346. properties = handle.get_properties()
  1347. window_handle = properties.get(\"window\")
  1348. document_handle = properties.get(\"document\")
  1349. handle.dispose()
  1350. ```
  1351. Returns
  1352. -------
  1353. Dict[str, JSHandle]
  1354. """
  1355. return mapping.from_impl_dict(self._sync(self._impl_obj.get_properties()))
  1356. def as_element(self) -> typing.Optional["ElementHandle"]:
  1357. """JSHandle.as_element
  1358. Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
  1359. Returns
  1360. -------
  1361. Union[ElementHandle, None]
  1362. """
  1363. return mapping.from_impl_nullable(self._impl_obj.as_element())
  1364. def dispose(self) -> None:
  1365. """JSHandle.dispose
  1366. The `jsHandle.dispose` method stops referencing the element handle.
  1367. """
  1368. return mapping.from_maybe_impl(self._sync(self._impl_obj.dispose()))
  1369. def json_value(self) -> typing.Any:
  1370. """JSHandle.json_value
  1371. Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
  1372. **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw
  1373. an error if the object has circular references.
  1374. Returns
  1375. -------
  1376. Any
  1377. """
  1378. return mapping.from_maybe_impl(self._sync(self._impl_obj.json_value()))
  1379. mapping.register(JSHandleImpl, JSHandle)
  1380. class ElementHandle(JSHandle):
  1381. def as_element(self) -> typing.Optional["ElementHandle"]:
  1382. """ElementHandle.as_element
  1383. Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
  1384. Returns
  1385. -------
  1386. Union[ElementHandle, None]
  1387. """
  1388. return mapping.from_impl_nullable(self._impl_obj.as_element())
  1389. def owner_frame(self) -> typing.Optional["Frame"]:
  1390. """ElementHandle.owner_frame
  1391. Returns the frame containing the given element.
  1392. Returns
  1393. -------
  1394. Union[Frame, None]
  1395. """
  1396. return mapping.from_impl_nullable(self._sync(self._impl_obj.owner_frame()))
  1397. def content_frame(self) -> typing.Optional["Frame"]:
  1398. """ElementHandle.content_frame
  1399. Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
  1400. Returns
  1401. -------
  1402. Union[Frame, None]
  1403. """
  1404. return mapping.from_impl_nullable(self._sync(self._impl_obj.content_frame()))
  1405. def get_attribute(self, name: str) -> typing.Optional[str]:
  1406. """ElementHandle.get_attribute
  1407. Returns element attribute value.
  1408. Parameters
  1409. ----------
  1410. name : str
  1411. Attribute name to get the value for.
  1412. Returns
  1413. -------
  1414. Union[str, None]
  1415. """
  1416. return mapping.from_maybe_impl(
  1417. self._sync(self._impl_obj.get_attribute(name=name))
  1418. )
  1419. def text_content(self) -> typing.Optional[str]:
  1420. """ElementHandle.text_content
  1421. Returns the `node.textContent`.
  1422. Returns
  1423. -------
  1424. Union[str, None]
  1425. """
  1426. return mapping.from_maybe_impl(self._sync(self._impl_obj.text_content()))
  1427. def inner_text(self) -> str:
  1428. """ElementHandle.inner_text
  1429. Returns the `element.innerText`.
  1430. Returns
  1431. -------
  1432. str
  1433. """
  1434. return mapping.from_maybe_impl(self._sync(self._impl_obj.inner_text()))
  1435. def inner_html(self) -> str:
  1436. """ElementHandle.inner_html
  1437. Returns the `element.innerHTML`.
  1438. Returns
  1439. -------
  1440. str
  1441. """
  1442. return mapping.from_maybe_impl(self._sync(self._impl_obj.inner_html()))
  1443. def is_checked(self) -> bool:
  1444. """ElementHandle.is_checked
  1445. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  1446. Returns
  1447. -------
  1448. bool
  1449. """
  1450. return mapping.from_maybe_impl(self._sync(self._impl_obj.is_checked()))
  1451. def is_disabled(self) -> bool:
  1452. """ElementHandle.is_disabled
  1453. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  1454. Returns
  1455. -------
  1456. bool
  1457. """
  1458. return mapping.from_maybe_impl(self._sync(self._impl_obj.is_disabled()))
  1459. def is_editable(self) -> bool:
  1460. """ElementHandle.is_editable
  1461. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  1462. Returns
  1463. -------
  1464. bool
  1465. """
  1466. return mapping.from_maybe_impl(self._sync(self._impl_obj.is_editable()))
  1467. def is_enabled(self) -> bool:
  1468. """ElementHandle.is_enabled
  1469. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  1470. Returns
  1471. -------
  1472. bool
  1473. """
  1474. return mapping.from_maybe_impl(self._sync(self._impl_obj.is_enabled()))
  1475. def is_hidden(self) -> bool:
  1476. """ElementHandle.is_hidden
  1477. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
  1478. Returns
  1479. -------
  1480. bool
  1481. """
  1482. return mapping.from_maybe_impl(self._sync(self._impl_obj.is_hidden()))
  1483. def is_visible(self) -> bool:
  1484. """ElementHandle.is_visible
  1485. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  1486. Returns
  1487. -------
  1488. bool
  1489. """
  1490. return mapping.from_maybe_impl(self._sync(self._impl_obj.is_visible()))
  1491. def dispatch_event(
  1492. self, type: str, event_init: typing.Optional[typing.Dict] = None
  1493. ) -> None:
  1494. """ElementHandle.dispatch_event
  1495. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  1496. `click` is dispatched. This is equivalent to calling
  1497. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  1498. **Usage**
  1499. ```py
  1500. element_handle.dispatch_event(\"click\")
  1501. ```
  1502. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  1503. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  1504. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  1505. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  1506. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  1507. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  1508. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  1509. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  1510. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  1511. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  1512. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  1513. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  1514. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  1515. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  1516. ```py
  1517. # note you can only create data_transfer in chromium and firefox
  1518. data_transfer = page.evaluate_handle(\"new DataTransfer()\")
  1519. element_handle.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
  1520. ```
  1521. Parameters
  1522. ----------
  1523. type : str
  1524. DOM event type: `"click"`, `"dragstart"`, etc.
  1525. event_init : Union[Dict, None]
  1526. Optional event-specific initialization properties.
  1527. """
  1528. return mapping.from_maybe_impl(
  1529. self._sync(
  1530. self._impl_obj.dispatch_event(
  1531. type=type, eventInit=mapping.to_impl(event_init)
  1532. )
  1533. )
  1534. )
  1535. def scroll_into_view_if_needed(
  1536. self, *, timeout: typing.Optional[float] = None
  1537. ) -> None:
  1538. """ElementHandle.scroll_into_view_if_needed
  1539. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
  1540. it is completely visible as defined by
  1541. [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
  1542. Throws when `elementHandle` does not point to an element
  1543. [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
  1544. See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  1545. Parameters
  1546. ----------
  1547. timeout : Union[float, None]
  1548. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1549. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1550. """
  1551. return mapping.from_maybe_impl(
  1552. self._sync(self._impl_obj.scroll_into_view_if_needed(timeout=timeout))
  1553. )
  1554. def hover(
  1555. self,
  1556. *,
  1557. modifiers: typing.Optional[
  1558. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1559. ] = None,
  1560. position: typing.Optional[Position] = None,
  1561. timeout: typing.Optional[float] = None,
  1562. no_wait_after: typing.Optional[bool] = None,
  1563. force: typing.Optional[bool] = None,
  1564. trial: typing.Optional[bool] = None,
  1565. ) -> None:
  1566. """ElementHandle.hover
  1567. This method hovers over the element by performing the following steps:
  1568. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1569. 1. Scroll the element into view if needed.
  1570. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  1571. If the element is detached from the DOM at any moment during the action, this method throws.
  1572. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1573. Passing zero timeout disables this.
  1574. Parameters
  1575. ----------
  1576. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1577. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1578. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1579. "Control" on Windows and Linux and to "Meta" on macOS.
  1580. position : Union[{x: float, y: float}, None]
  1581. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1582. the element.
  1583. timeout : Union[float, None]
  1584. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1585. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1586. no_wait_after : Union[bool, None]
  1587. This option has no effect.
  1588. Deprecated: This option has no effect.
  1589. force : Union[bool, None]
  1590. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1591. trial : Union[bool, None]
  1592. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1593. to `false`. Useful to wait until the element is ready for the action without performing it.
  1594. """
  1595. return mapping.from_maybe_impl(
  1596. self._sync(
  1597. self._impl_obj.hover(
  1598. modifiers=mapping.to_impl(modifiers),
  1599. position=position,
  1600. timeout=timeout,
  1601. noWaitAfter=no_wait_after,
  1602. force=force,
  1603. trial=trial,
  1604. )
  1605. )
  1606. )
  1607. def click(
  1608. self,
  1609. *,
  1610. modifiers: typing.Optional[
  1611. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1612. ] = None,
  1613. position: typing.Optional[Position] = None,
  1614. delay: typing.Optional[float] = None,
  1615. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1616. click_count: typing.Optional[int] = None,
  1617. timeout: typing.Optional[float] = None,
  1618. force: typing.Optional[bool] = None,
  1619. no_wait_after: typing.Optional[bool] = None,
  1620. trial: typing.Optional[bool] = None,
  1621. steps: typing.Optional[int] = None,
  1622. ) -> None:
  1623. """ElementHandle.click
  1624. This method clicks the element by performing the following steps:
  1625. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1626. 1. Scroll the element into view if needed.
  1627. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  1628. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  1629. If the element is detached from the DOM at any moment during the action, this method throws.
  1630. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1631. Passing zero timeout disables this.
  1632. Parameters
  1633. ----------
  1634. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1635. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1636. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1637. "Control" on Windows and Linux and to "Meta" on macOS.
  1638. position : Union[{x: float, y: float}, None]
  1639. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1640. the element.
  1641. delay : Union[float, None]
  1642. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1643. button : Union["left", "middle", "right", None]
  1644. Defaults to `left`.
  1645. click_count : Union[int, None]
  1646. defaults to 1. See [UIEvent.detail].
  1647. timeout : Union[float, None]
  1648. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1649. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1650. force : Union[bool, None]
  1651. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1652. no_wait_after : Union[bool, None]
  1653. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  1654. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  1655. navigating to inaccessible pages. Defaults to `false`.
  1656. Deprecated: This option will default to `true` in the future.
  1657. trial : Union[bool, None]
  1658. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1659. to `false`. Useful to wait until the element is ready for the action without performing it.
  1660. steps : Union[int, None]
  1661. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1662. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1663. """
  1664. return mapping.from_maybe_impl(
  1665. self._sync(
  1666. self._impl_obj.click(
  1667. modifiers=mapping.to_impl(modifiers),
  1668. position=position,
  1669. delay=delay,
  1670. button=button,
  1671. clickCount=click_count,
  1672. timeout=timeout,
  1673. force=force,
  1674. noWaitAfter=no_wait_after,
  1675. trial=trial,
  1676. steps=steps,
  1677. )
  1678. )
  1679. )
  1680. def dblclick(
  1681. self,
  1682. *,
  1683. modifiers: typing.Optional[
  1684. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1685. ] = None,
  1686. position: typing.Optional[Position] = None,
  1687. delay: typing.Optional[float] = None,
  1688. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1689. timeout: typing.Optional[float] = None,
  1690. force: typing.Optional[bool] = None,
  1691. no_wait_after: typing.Optional[bool] = None,
  1692. trial: typing.Optional[bool] = None,
  1693. steps: typing.Optional[int] = None,
  1694. ) -> None:
  1695. """ElementHandle.dblclick
  1696. This method double clicks the element by performing the following steps:
  1697. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1698. 1. Scroll the element into view if needed.
  1699. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  1700. If the element is detached from the DOM at any moment during the action, this method throws.
  1701. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1702. Passing zero timeout disables this.
  1703. **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
  1704. Parameters
  1705. ----------
  1706. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1707. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1708. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1709. "Control" on Windows and Linux and to "Meta" on macOS.
  1710. position : Union[{x: float, y: float}, None]
  1711. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1712. the element.
  1713. delay : Union[float, None]
  1714. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1715. button : Union["left", "middle", "right", None]
  1716. Defaults to `left`.
  1717. timeout : Union[float, None]
  1718. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1719. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1720. force : Union[bool, None]
  1721. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1722. no_wait_after : Union[bool, None]
  1723. This option has no effect.
  1724. Deprecated: This option has no effect.
  1725. trial : Union[bool, None]
  1726. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1727. to `false`. Useful to wait until the element is ready for the action without performing it.
  1728. steps : Union[int, None]
  1729. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1730. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1731. """
  1732. return mapping.from_maybe_impl(
  1733. self._sync(
  1734. self._impl_obj.dblclick(
  1735. modifiers=mapping.to_impl(modifiers),
  1736. position=position,
  1737. delay=delay,
  1738. button=button,
  1739. timeout=timeout,
  1740. force=force,
  1741. noWaitAfter=no_wait_after,
  1742. trial=trial,
  1743. steps=steps,
  1744. )
  1745. )
  1746. )
  1747. def select_option(
  1748. self,
  1749. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  1750. *,
  1751. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  1752. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  1753. element: typing.Optional[
  1754. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  1755. ] = None,
  1756. timeout: typing.Optional[float] = None,
  1757. force: typing.Optional[bool] = None,
  1758. no_wait_after: typing.Optional[bool] = None,
  1759. ) -> typing.List[str]:
  1760. """ElementHandle.select_option
  1761. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
  1762. the `<select>` element and selects these options.
  1763. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  1764. the `<label>` element that has an associated
  1765. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  1766. instead.
  1767. Returns the array of option values that have been successfully selected.
  1768. Triggers a `change` and `input` event once all the provided options have been selected.
  1769. **Usage**
  1770. ```py
  1771. # Single selection matching the value or label
  1772. handle.select_option(\"blue\")
  1773. # single selection matching both the label
  1774. handle.select_option(label=\"blue\")
  1775. # multiple selection
  1776. handle.select_option(value=[\"red\", \"green\", \"blue\"])
  1777. ```
  1778. Parameters
  1779. ----------
  1780. value : Union[Sequence[str], str, None]
  1781. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  1782. otherwise only the first option matching one of the passed options is selected. Optional.
  1783. index : Union[Sequence[int], int, None]
  1784. Options to select by index. Optional.
  1785. label : Union[Sequence[str], str, None]
  1786. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  1787. otherwise only the first option matching one of the passed options is selected. Optional.
  1788. element : Union[ElementHandle, Sequence[ElementHandle], None]
  1789. Option elements to select. Optional.
  1790. timeout : Union[float, None]
  1791. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1792. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1793. force : Union[bool, None]
  1794. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1795. no_wait_after : Union[bool, None]
  1796. This option has no effect.
  1797. Deprecated: This option has no effect.
  1798. Returns
  1799. -------
  1800. List[str]
  1801. """
  1802. return mapping.from_maybe_impl(
  1803. self._sync(
  1804. self._impl_obj.select_option(
  1805. value=mapping.to_impl(value),
  1806. index=mapping.to_impl(index),
  1807. label=mapping.to_impl(label),
  1808. element=mapping.to_impl(element),
  1809. timeout=timeout,
  1810. force=force,
  1811. noWaitAfter=no_wait_after,
  1812. )
  1813. )
  1814. )
  1815. def tap(
  1816. self,
  1817. *,
  1818. modifiers: typing.Optional[
  1819. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1820. ] = None,
  1821. position: typing.Optional[Position] = None,
  1822. timeout: typing.Optional[float] = None,
  1823. force: typing.Optional[bool] = None,
  1824. no_wait_after: typing.Optional[bool] = None,
  1825. trial: typing.Optional[bool] = None,
  1826. ) -> None:
  1827. """ElementHandle.tap
  1828. This method taps the element by performing the following steps:
  1829. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1830. 1. Scroll the element into view if needed.
  1831. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  1832. If the element is detached from the DOM at any moment during the action, this method throws.
  1833. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1834. Passing zero timeout disables this.
  1835. **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
  1836. Parameters
  1837. ----------
  1838. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1839. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1840. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1841. "Control" on Windows and Linux and to "Meta" on macOS.
  1842. position : Union[{x: float, y: float}, None]
  1843. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1844. the element.
  1845. timeout : Union[float, None]
  1846. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1847. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1848. force : Union[bool, None]
  1849. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1850. no_wait_after : Union[bool, None]
  1851. This option has no effect.
  1852. Deprecated: This option has no effect.
  1853. trial : Union[bool, None]
  1854. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1855. to `false`. Useful to wait until the element is ready for the action without performing it.
  1856. """
  1857. return mapping.from_maybe_impl(
  1858. self._sync(
  1859. self._impl_obj.tap(
  1860. modifiers=mapping.to_impl(modifiers),
  1861. position=position,
  1862. timeout=timeout,
  1863. force=force,
  1864. noWaitAfter=no_wait_after,
  1865. trial=trial,
  1866. )
  1867. )
  1868. )
  1869. def fill(
  1870. self,
  1871. value: str,
  1872. *,
  1873. timeout: typing.Optional[float] = None,
  1874. no_wait_after: typing.Optional[bool] = None,
  1875. force: typing.Optional[bool] = None,
  1876. ) -> None:
  1877. """ElementHandle.fill
  1878. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
  1879. `input` event after filling. Note that you can pass an empty string to clear the input field.
  1880. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  1881. error. However, if the element is inside the `<label>` element that has an associated
  1882. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  1883. instead.
  1884. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  1885. Parameters
  1886. ----------
  1887. value : str
  1888. Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
  1889. timeout : Union[float, None]
  1890. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1891. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1892. no_wait_after : Union[bool, None]
  1893. This option has no effect.
  1894. Deprecated: This option has no effect.
  1895. force : Union[bool, None]
  1896. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1897. """
  1898. return mapping.from_maybe_impl(
  1899. self._sync(
  1900. self._impl_obj.fill(
  1901. value=value, timeout=timeout, noWaitAfter=no_wait_after, force=force
  1902. )
  1903. )
  1904. )
  1905. def select_text(
  1906. self,
  1907. *,
  1908. force: typing.Optional[bool] = None,
  1909. timeout: typing.Optional[float] = None,
  1910. ) -> None:
  1911. """ElementHandle.select_text
  1912. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
  1913. text content.
  1914. If the element is inside the `<label>` element that has an associated
  1915. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
  1916. the control instead.
  1917. Parameters
  1918. ----------
  1919. force : Union[bool, None]
  1920. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1921. timeout : Union[float, None]
  1922. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1923. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1924. """
  1925. return mapping.from_maybe_impl(
  1926. self._sync(self._impl_obj.select_text(force=force, timeout=timeout))
  1927. )
  1928. def input_value(self, *, timeout: typing.Optional[float] = None) -> str:
  1929. """ElementHandle.input_value
  1930. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  1931. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  1932. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  1933. control.
  1934. Parameters
  1935. ----------
  1936. timeout : Union[float, None]
  1937. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1938. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1939. Returns
  1940. -------
  1941. str
  1942. """
  1943. return mapping.from_maybe_impl(
  1944. self._sync(self._impl_obj.input_value(timeout=timeout))
  1945. )
  1946. def set_input_files(
  1947. self,
  1948. files: typing.Union[
  1949. str,
  1950. pathlib.Path,
  1951. FilePayload,
  1952. typing.Sequence[typing.Union[str, pathlib.Path]],
  1953. typing.Sequence[FilePayload],
  1954. ],
  1955. *,
  1956. timeout: typing.Optional[float] = None,
  1957. no_wait_after: typing.Optional[bool] = None,
  1958. ) -> None:
  1959. """ElementHandle.set_input_files
  1960. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  1961. they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
  1962. with a `[webkitdirectory]` attribute, only a single directory path is supported.
  1963. This method expects `ElementHandle` to point to an
  1964. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  1965. the `<label>` element that has an associated
  1966. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  1967. Parameters
  1968. ----------
  1969. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  1970. timeout : Union[float, None]
  1971. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1972. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1973. no_wait_after : Union[bool, None]
  1974. This option has no effect.
  1975. Deprecated: This option has no effect.
  1976. """
  1977. return mapping.from_maybe_impl(
  1978. self._sync(
  1979. self._impl_obj.set_input_files(
  1980. files=mapping.to_impl(files),
  1981. timeout=timeout,
  1982. noWaitAfter=no_wait_after,
  1983. )
  1984. )
  1985. )
  1986. def focus(self) -> None:
  1987. """ElementHandle.focus
  1988. Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
  1989. """
  1990. return mapping.from_maybe_impl(self._sync(self._impl_obj.focus()))
  1991. def type(
  1992. self,
  1993. text: str,
  1994. *,
  1995. delay: typing.Optional[float] = None,
  1996. timeout: typing.Optional[float] = None,
  1997. no_wait_after: typing.Optional[bool] = None,
  1998. ) -> None:
  1999. """ElementHandle.type
  2000. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  2001. text.
  2002. To press a special key, like `Control` or `ArrowDown`, use `element_handle.press()`.
  2003. **Usage**
  2004. Parameters
  2005. ----------
  2006. text : str
  2007. A text to type into a focused element.
  2008. delay : Union[float, None]
  2009. Time to wait between key presses in milliseconds. Defaults to 0.
  2010. timeout : Union[float, None]
  2011. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2012. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2013. no_wait_after : Union[bool, None]
  2014. This option has no effect.
  2015. Deprecated: This option has no effect.
  2016. """
  2017. return mapping.from_maybe_impl(
  2018. self._sync(
  2019. self._impl_obj.type(
  2020. text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  2021. )
  2022. )
  2023. )
  2024. def press(
  2025. self,
  2026. key: str,
  2027. *,
  2028. delay: typing.Optional[float] = None,
  2029. timeout: typing.Optional[float] = None,
  2030. no_wait_after: typing.Optional[bool] = None,
  2031. ) -> None:
  2032. """ElementHandle.press
  2033. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  2034. `key` can specify the intended
  2035. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  2036. to generate the text for. A superset of the `key` values can be found
  2037. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  2038. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  2039. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  2040. etc.
  2041. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  2042. `ControlOrMeta`.
  2043. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  2044. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  2045. texts.
  2046. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  2047. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  2048. Parameters
  2049. ----------
  2050. key : str
  2051. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  2052. delay : Union[float, None]
  2053. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  2054. timeout : Union[float, None]
  2055. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2056. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2057. no_wait_after : Union[bool, None]
  2058. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  2059. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  2060. navigating to inaccessible pages. Defaults to `false`.
  2061. Deprecated: This option will default to `true` in the future.
  2062. """
  2063. return mapping.from_maybe_impl(
  2064. self._sync(
  2065. self._impl_obj.press(
  2066. key=key, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  2067. )
  2068. )
  2069. )
  2070. def set_checked(
  2071. self,
  2072. checked: bool,
  2073. *,
  2074. position: typing.Optional[Position] = None,
  2075. timeout: typing.Optional[float] = None,
  2076. force: typing.Optional[bool] = None,
  2077. no_wait_after: typing.Optional[bool] = None,
  2078. trial: typing.Optional[bool] = None,
  2079. ) -> None:
  2080. """ElementHandle.set_checked
  2081. This method checks or unchecks an element by performing the following steps:
  2082. 1. Ensure that element is a checkbox or a radio input. If not, this method throws.
  2083. 1. If the element already has the right checked state, this method returns immediately.
  2084. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  2085. the element is detached during the checks, the whole action is retried.
  2086. 1. Scroll the element into view if needed.
  2087. 1. Use `page.mouse` to click in the center of the element.
  2088. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  2089. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2090. Passing zero timeout disables this.
  2091. Parameters
  2092. ----------
  2093. checked : bool
  2094. Whether to check or uncheck the checkbox.
  2095. position : Union[{x: float, y: float}, None]
  2096. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2097. the element.
  2098. timeout : Union[float, None]
  2099. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2100. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2101. force : Union[bool, None]
  2102. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2103. no_wait_after : Union[bool, None]
  2104. This option has no effect.
  2105. Deprecated: This option has no effect.
  2106. trial : Union[bool, None]
  2107. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2108. to `false`. Useful to wait until the element is ready for the action without performing it.
  2109. """
  2110. return mapping.from_maybe_impl(
  2111. self._sync(
  2112. self._impl_obj.set_checked(
  2113. checked=checked,
  2114. position=position,
  2115. timeout=timeout,
  2116. force=force,
  2117. noWaitAfter=no_wait_after,
  2118. trial=trial,
  2119. )
  2120. )
  2121. )
  2122. def check(
  2123. self,
  2124. *,
  2125. position: typing.Optional[Position] = None,
  2126. timeout: typing.Optional[float] = None,
  2127. force: typing.Optional[bool] = None,
  2128. no_wait_after: typing.Optional[bool] = None,
  2129. trial: typing.Optional[bool] = None,
  2130. ) -> None:
  2131. """ElementHandle.check
  2132. This method checks the element by performing the following steps:
  2133. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  2134. checked, this method returns immediately.
  2135. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  2136. 1. Scroll the element into view if needed.
  2137. 1. Use `page.mouse` to click in the center of the element.
  2138. 1. Ensure that the element is now checked. If not, this method throws.
  2139. If the element is detached from the DOM at any moment during the action, this method throws.
  2140. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2141. Passing zero timeout disables this.
  2142. Parameters
  2143. ----------
  2144. position : Union[{x: float, y: float}, None]
  2145. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2146. the element.
  2147. timeout : Union[float, None]
  2148. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2149. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2150. force : Union[bool, None]
  2151. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2152. no_wait_after : Union[bool, None]
  2153. This option has no effect.
  2154. Deprecated: This option has no effect.
  2155. trial : Union[bool, None]
  2156. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2157. to `false`. Useful to wait until the element is ready for the action without performing it.
  2158. """
  2159. return mapping.from_maybe_impl(
  2160. self._sync(
  2161. self._impl_obj.check(
  2162. position=position,
  2163. timeout=timeout,
  2164. force=force,
  2165. noWaitAfter=no_wait_after,
  2166. trial=trial,
  2167. )
  2168. )
  2169. )
  2170. def uncheck(
  2171. self,
  2172. *,
  2173. position: typing.Optional[Position] = None,
  2174. timeout: typing.Optional[float] = None,
  2175. force: typing.Optional[bool] = None,
  2176. no_wait_after: typing.Optional[bool] = None,
  2177. trial: typing.Optional[bool] = None,
  2178. ) -> None:
  2179. """ElementHandle.uncheck
  2180. This method checks the element by performing the following steps:
  2181. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  2182. unchecked, this method returns immediately.
  2183. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  2184. 1. Scroll the element into view if needed.
  2185. 1. Use `page.mouse` to click in the center of the element.
  2186. 1. Ensure that the element is now unchecked. If not, this method throws.
  2187. If the element is detached from the DOM at any moment during the action, this method throws.
  2188. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2189. Passing zero timeout disables this.
  2190. Parameters
  2191. ----------
  2192. position : Union[{x: float, y: float}, None]
  2193. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2194. the element.
  2195. timeout : Union[float, None]
  2196. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2197. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2198. force : Union[bool, None]
  2199. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2200. no_wait_after : Union[bool, None]
  2201. This option has no effect.
  2202. Deprecated: This option has no effect.
  2203. trial : Union[bool, None]
  2204. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2205. to `false`. Useful to wait until the element is ready for the action without performing it.
  2206. """
  2207. return mapping.from_maybe_impl(
  2208. self._sync(
  2209. self._impl_obj.uncheck(
  2210. position=position,
  2211. timeout=timeout,
  2212. force=force,
  2213. noWaitAfter=no_wait_after,
  2214. trial=trial,
  2215. )
  2216. )
  2217. )
  2218. def bounding_box(self) -> typing.Optional[FloatRect]:
  2219. """ElementHandle.bounding_box
  2220. This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
  2221. calculated relative to the main frame viewport - which is usually the same as the browser window.
  2222. Scrolling affects the returned bounding box, similarly to
  2223. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2224. That means `x` and/or `y` may be negative.
  2225. Elements from child frames return the bounding box relative to the main frame, unlike the
  2226. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2227. Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
  2228. following snippet should click the center of the element.
  2229. **Usage**
  2230. ```py
  2231. box = element_handle.bounding_box()
  2232. page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
  2233. ```
  2234. Returns
  2235. -------
  2236. Union[{x: float, y: float, width: float, height: float}, None]
  2237. """
  2238. return mapping.from_impl_nullable(self._sync(self._impl_obj.bounding_box()))
  2239. def screenshot(
  2240. self,
  2241. *,
  2242. timeout: typing.Optional[float] = None,
  2243. type: typing.Optional[Literal["jpeg", "png"]] = None,
  2244. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  2245. quality: typing.Optional[int] = None,
  2246. omit_background: typing.Optional[bool] = None,
  2247. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  2248. caret: typing.Optional[Literal["hide", "initial"]] = None,
  2249. scale: typing.Optional[Literal["css", "device"]] = None,
  2250. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  2251. mask_color: typing.Optional[str] = None,
  2252. style: typing.Optional[str] = None,
  2253. ) -> bytes:
  2254. """ElementHandle.screenshot
  2255. This method captures a screenshot of the page, clipped to the size and position of this particular element. If the
  2256. element is covered by other elements, it will not be actually visible on the screenshot. If the element is a
  2257. scrollable container, only the currently scrolled content will be visible on the screenshot.
  2258. This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
  2259. a screenshot. If the element is detached from DOM, the method throws an error.
  2260. Returns the buffer with the captured screenshot.
  2261. Parameters
  2262. ----------
  2263. timeout : Union[float, None]
  2264. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2265. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2266. type : Union["jpeg", "png", None]
  2267. Specify screenshot type, defaults to `png`.
  2268. path : Union[pathlib.Path, str, None]
  2269. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  2270. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  2271. won't be saved to the disk.
  2272. quality : Union[int, None]
  2273. The quality of the image, between 0-100. Not applicable to `png` images.
  2274. omit_background : Union[bool, None]
  2275. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  2276. Defaults to `false`.
  2277. animations : Union["allow", "disabled", None]
  2278. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  2279. treatment depending on their duration:
  2280. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  2281. - infinite animations are canceled to initial state, and then played over after the screenshot.
  2282. Defaults to `"allow"` that leaves animations untouched.
  2283. caret : Union["hide", "initial", None]
  2284. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  2285. changed. Defaults to `"hide"`.
  2286. scale : Union["css", "device", None]
  2287. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  2288. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  2289. screenshots of high-dpi devices will be twice as large or even larger.
  2290. Defaults to `"device"`.
  2291. mask : Union[Sequence[Locator], None]
  2292. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  2293. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  2294. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  2295. that.
  2296. mask_color : Union[str, None]
  2297. Specify the color of the overlay box for masked elements, in
  2298. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  2299. style : Union[str, None]
  2300. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  2301. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  2302. the Shadow DOM and applies to the inner frames.
  2303. Returns
  2304. -------
  2305. bytes
  2306. """
  2307. return mapping.from_maybe_impl(
  2308. self._sync(
  2309. self._impl_obj.screenshot(
  2310. timeout=timeout,
  2311. type=type,
  2312. path=path,
  2313. quality=quality,
  2314. omitBackground=omit_background,
  2315. animations=animations,
  2316. caret=caret,
  2317. scale=scale,
  2318. mask=mapping.to_impl(mask),
  2319. maskColor=mask_color,
  2320. style=style,
  2321. )
  2322. )
  2323. )
  2324. def query_selector(self, selector: str) -> typing.Optional["ElementHandle"]:
  2325. """ElementHandle.query_selector
  2326. The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
  2327. the selector, returns `null`.
  2328. Parameters
  2329. ----------
  2330. selector : str
  2331. A selector to query for.
  2332. Returns
  2333. -------
  2334. Union[ElementHandle, None]
  2335. """
  2336. return mapping.from_impl_nullable(
  2337. self._sync(self._impl_obj.query_selector(selector=selector))
  2338. )
  2339. def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  2340. """ElementHandle.query_selector_all
  2341. The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
  2342. the selector, returns empty array.
  2343. Parameters
  2344. ----------
  2345. selector : str
  2346. A selector to query for.
  2347. Returns
  2348. -------
  2349. List[ElementHandle]
  2350. """
  2351. return mapping.from_impl_list(
  2352. self._sync(self._impl_obj.query_selector_all(selector=selector))
  2353. )
  2354. def eval_on_selector(
  2355. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  2356. ) -> typing.Any:
  2357. """ElementHandle.eval_on_selector
  2358. Returns the return value of `expression`.
  2359. The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
  2360. first argument to `expression`. If no elements match the selector, the method throws an error.
  2361. If `expression` returns a [Promise], then `element_handle.eval_on_selector()` would wait for the promise to
  2362. resolve and return its value.
  2363. **Usage**
  2364. ```py
  2365. tweet_handle = page.query_selector(\".tweet\")
  2366. assert tweet_handle.eval_on_selector(\".like\", \"node => node.innerText\") == \"100\"
  2367. assert tweet_handle.eval_on_selector(\".retweets\", \"node => node.innerText\") == \"10\"
  2368. ```
  2369. Parameters
  2370. ----------
  2371. selector : str
  2372. A selector to query for.
  2373. expression : str
  2374. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2375. function is automatically invoked.
  2376. arg : Union[Any, None]
  2377. Optional argument to pass to `expression`.
  2378. Returns
  2379. -------
  2380. Any
  2381. """
  2382. return mapping.from_maybe_impl(
  2383. self._sync(
  2384. self._impl_obj.eval_on_selector(
  2385. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  2386. )
  2387. )
  2388. )
  2389. def eval_on_selector_all(
  2390. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  2391. ) -> typing.Any:
  2392. """ElementHandle.eval_on_selector_all
  2393. Returns the return value of `expression`.
  2394. The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
  2395. of matched elements as a first argument to `expression`.
  2396. If `expression` returns a [Promise], then `element_handle.eval_on_selector_all()` would wait for the promise to
  2397. resolve and return its value.
  2398. **Usage**
  2399. ```html
  2400. <div class=\"feed\">
  2401. <div class=\"tweet\">Hello!</div>
  2402. <div class=\"tweet\">Hi!</div>
  2403. </div>
  2404. ```
  2405. ```py
  2406. feed_handle = page.query_selector(\".feed\")
  2407. assert feed_handle.eval_on_selector_all(\".tweet\", \"nodes => nodes.map(n => n.innerText)\") == [\"hello!\", \"hi!\"]
  2408. ```
  2409. Parameters
  2410. ----------
  2411. selector : str
  2412. A selector to query for.
  2413. expression : str
  2414. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2415. function is automatically invoked.
  2416. arg : Union[Any, None]
  2417. Optional argument to pass to `expression`.
  2418. Returns
  2419. -------
  2420. Any
  2421. """
  2422. return mapping.from_maybe_impl(
  2423. self._sync(
  2424. self._impl_obj.eval_on_selector_all(
  2425. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  2426. )
  2427. )
  2428. )
  2429. def wait_for_element_state(
  2430. self,
  2431. state: Literal[
  2432. "disabled", "editable", "enabled", "hidden", "stable", "visible"
  2433. ],
  2434. *,
  2435. timeout: typing.Optional[float] = None,
  2436. ) -> None:
  2437. """ElementHandle.wait_for_element_state
  2438. Returns when the element satisfies the `state`.
  2439. Depending on the `state` parameter, this method waits for one of the [actionability](https://playwright.dev/python/docs/actionability) checks to
  2440. pass. This method throws when the element is detached while waiting, unless waiting for the `\"hidden\"` state.
  2441. - `\"visible\"` Wait until the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  2442. - `\"hidden\"` Wait until the element is [not visible](https://playwright.dev/python/docs/actionability#visible) or not attached. Note that
  2443. waiting for hidden does not throw when the element detaches.
  2444. - `\"stable\"` Wait until the element is both [visible](https://playwright.dev/python/docs/actionability#visible) and
  2445. [stable](https://playwright.dev/python/docs/actionability#stable).
  2446. - `\"enabled\"` Wait until the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  2447. - `\"disabled\"` Wait until the element is [not enabled](https://playwright.dev/python/docs/actionability#enabled).
  2448. - `\"editable\"` Wait until the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  2449. If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
  2450. Parameters
  2451. ----------
  2452. state : Union["disabled", "editable", "enabled", "hidden", "stable", "visible"]
  2453. A state to wait for, see below for more details.
  2454. timeout : Union[float, None]
  2455. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2456. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2457. """
  2458. return mapping.from_maybe_impl(
  2459. self._sync(
  2460. self._impl_obj.wait_for_element_state(state=state, timeout=timeout)
  2461. )
  2462. )
  2463. def wait_for_selector(
  2464. self,
  2465. selector: str,
  2466. *,
  2467. state: typing.Optional[
  2468. Literal["attached", "detached", "hidden", "visible"]
  2469. ] = None,
  2470. timeout: typing.Optional[float] = None,
  2471. strict: typing.Optional[bool] = None,
  2472. ) -> typing.Optional["ElementHandle"]:
  2473. """ElementHandle.wait_for_selector
  2474. Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
  2475. `detached`.
  2476. Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
  2477. or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
  2478. method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
  2479. function will throw.
  2480. **Usage**
  2481. ```py
  2482. page.set_content(\"<div><span></span></div>\")
  2483. div = page.query_selector(\"div\")
  2484. # waiting for the \"span\" selector relative to the div.
  2485. span = div.wait_for_selector(\"span\", state=\"attached\")
  2486. ```
  2487. **NOTE** This method does not work across navigations, use `page.wait_for_selector()` instead.
  2488. Parameters
  2489. ----------
  2490. selector : str
  2491. A selector to query for.
  2492. state : Union["attached", "detached", "hidden", "visible", None]
  2493. Defaults to `'visible'`. Can be either:
  2494. - `'attached'` - wait for element to be present in DOM.
  2495. - `'detached'` - wait for element to not be present in DOM.
  2496. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  2497. without any content or with `display:none` has an empty bounding box and is not considered visible.
  2498. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  2499. `visibility:hidden`. This is opposite to the `'visible'` option.
  2500. timeout : Union[float, None]
  2501. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2502. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2503. strict : Union[bool, None]
  2504. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2505. element, the call throws an exception.
  2506. Returns
  2507. -------
  2508. Union[ElementHandle, None]
  2509. """
  2510. return mapping.from_impl_nullable(
  2511. self._sync(
  2512. self._impl_obj.wait_for_selector(
  2513. selector=selector, state=state, timeout=timeout, strict=strict
  2514. )
  2515. )
  2516. )
  2517. mapping.register(ElementHandleImpl, ElementHandle)
  2518. class FileChooser(SyncBase):
  2519. @property
  2520. def page(self) -> "Page":
  2521. """FileChooser.page
  2522. Returns page this file chooser belongs to.
  2523. Returns
  2524. -------
  2525. Page
  2526. """
  2527. return mapping.from_impl(self._impl_obj.page)
  2528. @property
  2529. def element(self) -> "ElementHandle":
  2530. """FileChooser.element
  2531. Returns input element associated with this file chooser.
  2532. Returns
  2533. -------
  2534. ElementHandle
  2535. """
  2536. return mapping.from_impl(self._impl_obj.element)
  2537. def is_multiple(self) -> bool:
  2538. """FileChooser.is_multiple
  2539. Returns whether this file chooser accepts multiple files.
  2540. Returns
  2541. -------
  2542. bool
  2543. """
  2544. return mapping.from_maybe_impl(self._impl_obj.is_multiple())
  2545. def set_files(
  2546. self,
  2547. files: typing.Union[
  2548. str,
  2549. pathlib.Path,
  2550. FilePayload,
  2551. typing.Sequence[typing.Union[str, pathlib.Path]],
  2552. typing.Sequence[FilePayload],
  2553. ],
  2554. *,
  2555. timeout: typing.Optional[float] = None,
  2556. no_wait_after: typing.Optional[bool] = None,
  2557. ) -> None:
  2558. """FileChooser.set_files
  2559. Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,
  2560. then they are resolved relative to the current working directory. For empty array, clears the selected files.
  2561. Parameters
  2562. ----------
  2563. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  2564. timeout : Union[float, None]
  2565. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2566. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2567. no_wait_after : Union[bool, None]
  2568. This option has no effect.
  2569. Deprecated: This option has no effect.
  2570. """
  2571. return mapping.from_maybe_impl(
  2572. self._sync(
  2573. self._impl_obj.set_files(
  2574. files=mapping.to_impl(files),
  2575. timeout=timeout,
  2576. noWaitAfter=no_wait_after,
  2577. )
  2578. )
  2579. )
  2580. mapping.register(FileChooserImpl, FileChooser)
  2581. class Frame(SyncBase):
  2582. @property
  2583. def page(self) -> "Page":
  2584. """Frame.page
  2585. Returns the page containing this frame.
  2586. Returns
  2587. -------
  2588. Page
  2589. """
  2590. return mapping.from_impl(self._impl_obj.page)
  2591. @property
  2592. def name(self) -> str:
  2593. """Frame.name
  2594. Returns frame's name attribute as specified in the tag.
  2595. If the name is empty, returns the id attribute instead.
  2596. **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed
  2597. later.
  2598. Returns
  2599. -------
  2600. str
  2601. """
  2602. return mapping.from_maybe_impl(self._impl_obj.name)
  2603. @property
  2604. def url(self) -> str:
  2605. """Frame.url
  2606. Returns frame's url.
  2607. Returns
  2608. -------
  2609. str
  2610. """
  2611. return mapping.from_maybe_impl(self._impl_obj.url)
  2612. @property
  2613. def parent_frame(self) -> typing.Optional["Frame"]:
  2614. """Frame.parent_frame
  2615. Parent frame, if any. Detached frames and main frames return `null`.
  2616. Returns
  2617. -------
  2618. Union[Frame, None]
  2619. """
  2620. return mapping.from_impl_nullable(self._impl_obj.parent_frame)
  2621. @property
  2622. def child_frames(self) -> typing.List["Frame"]:
  2623. """Frame.child_frames
  2624. Returns
  2625. -------
  2626. List[Frame]
  2627. """
  2628. return mapping.from_impl_list(self._impl_obj.child_frames)
  2629. def goto(
  2630. self,
  2631. url: str,
  2632. *,
  2633. timeout: typing.Optional[float] = None,
  2634. wait_until: typing.Optional[
  2635. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2636. ] = None,
  2637. referer: typing.Optional[str] = None,
  2638. ) -> typing.Optional["Response"]:
  2639. """Frame.goto
  2640. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  2641. the last redirect.
  2642. The method will throw an error if:
  2643. - there's an SSL error (e.g. in case of self-signed certificates).
  2644. - target URL is invalid.
  2645. - the `timeout` is exceeded during navigation.
  2646. - the remote server does not respond or is unreachable.
  2647. - the main resource failed to load.
  2648. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
  2649. \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
  2650. `response.status()`.
  2651. **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
  2652. to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
  2653. **NOTE** Headless mode doesn't support navigation to a PDF document. See the
  2654. [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
  2655. Parameters
  2656. ----------
  2657. url : str
  2658. URL to navigate frame to. The url should include scheme, e.g. `https://`.
  2659. timeout : Union[float, None]
  2660. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2661. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2662. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2663. `page.set_default_timeout()` methods.
  2664. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2665. When to consider operation succeeded, defaults to `load`. Events can be either:
  2666. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2667. - `'load'` - consider operation to be finished when the `load` event is fired.
  2668. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2669. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2670. - `'commit'` - consider operation to be finished when network response is received and the document started
  2671. loading.
  2672. referer : Union[str, None]
  2673. Referer header value. If provided it will take preference over the referer header value set by
  2674. `page.set_extra_http_headers()`.
  2675. Returns
  2676. -------
  2677. Union[Response, None]
  2678. """
  2679. return mapping.from_impl_nullable(
  2680. self._sync(
  2681. self._impl_obj.goto(
  2682. url=url, timeout=timeout, waitUntil=wait_until, referer=referer
  2683. )
  2684. )
  2685. )
  2686. def expect_navigation(
  2687. self,
  2688. *,
  2689. url: typing.Optional[
  2690. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  2691. ] = None,
  2692. wait_until: typing.Optional[
  2693. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2694. ] = None,
  2695. timeout: typing.Optional[float] = None,
  2696. ) -> EventContextManager["Response"]:
  2697. """Frame.expect_navigation
  2698. Waits for the frame navigation and returns the main resource response. In case of multiple redirects, the
  2699. navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
  2700. navigation due to History API usage, the navigation will resolve with `null`.
  2701. **Usage**
  2702. This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly
  2703. cause the frame to navigate. Consider this example:
  2704. ```py
  2705. with frame.expect_navigation():
  2706. frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  2707. # Resolves after navigation has finished
  2708. ```
  2709. **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
  2710. is considered a navigation.
  2711. Parameters
  2712. ----------
  2713. url : Union[Callable[[str], bool], Pattern[str], str, None]
  2714. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  2715. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  2716. equal to the string.
  2717. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2718. When to consider operation succeeded, defaults to `load`. Events can be either:
  2719. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2720. - `'load'` - consider operation to be finished when the `load` event is fired.
  2721. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2722. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2723. - `'commit'` - consider operation to be finished when network response is received and the document started
  2724. loading.
  2725. timeout : Union[float, None]
  2726. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2727. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2728. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2729. `page.set_default_timeout()` methods.
  2730. Returns
  2731. -------
  2732. EventContextManager[Response]
  2733. """
  2734. return EventContextManager(
  2735. self,
  2736. self._impl_obj.expect_navigation(
  2737. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  2738. ).future,
  2739. )
  2740. def wait_for_url(
  2741. self,
  2742. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  2743. *,
  2744. wait_until: typing.Optional[
  2745. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2746. ] = None,
  2747. timeout: typing.Optional[float] = None,
  2748. ) -> None:
  2749. """Frame.wait_for_url
  2750. Waits for the frame to navigate to the given URL.
  2751. **Usage**
  2752. ```py
  2753. frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  2754. frame.wait_for_url(\"**/target.html\")
  2755. ```
  2756. Parameters
  2757. ----------
  2758. url : Union[Callable[[str], bool], Pattern[str], str]
  2759. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  2760. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  2761. equal to the string.
  2762. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2763. When to consider operation succeeded, defaults to `load`. Events can be either:
  2764. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2765. - `'load'` - consider operation to be finished when the `load` event is fired.
  2766. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2767. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2768. - `'commit'` - consider operation to be finished when network response is received and the document started
  2769. loading.
  2770. timeout : Union[float, None]
  2771. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2772. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2773. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2774. `page.set_default_timeout()` methods.
  2775. """
  2776. return mapping.from_maybe_impl(
  2777. self._sync(
  2778. self._impl_obj.wait_for_url(
  2779. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  2780. )
  2781. )
  2782. )
  2783. def wait_for_load_state(
  2784. self,
  2785. state: typing.Optional[
  2786. Literal["domcontentloaded", "load", "networkidle"]
  2787. ] = None,
  2788. *,
  2789. timeout: typing.Optional[float] = None,
  2790. ) -> None:
  2791. """Frame.wait_for_load_state
  2792. Waits for the required load state to be reached.
  2793. This returns when the frame reaches a required load state, `load` by default. The navigation must have been
  2794. committed when this method is called. If current document has already reached the required state, resolves
  2795. immediately.
  2796. **NOTE** Most of the time, this method is not needed because Playwright
  2797. [auto-waits before every action](https://playwright.dev/python/docs/actionability).
  2798. **Usage**
  2799. ```py
  2800. frame.click(\"button\") # click triggers navigation.
  2801. frame.wait_for_load_state() # the promise resolves after \"load\" event.
  2802. ```
  2803. Parameters
  2804. ----------
  2805. state : Union["domcontentloaded", "load", "networkidle", None]
  2806. Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
  2807. document, the method resolves immediately. Can be one of:
  2808. - `'load'` - wait for the `load` event to be fired.
  2809. - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
  2810. - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
  2811. this method for testing, rely on web assertions to assess readiness instead.
  2812. timeout : Union[float, None]
  2813. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2814. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2815. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2816. `page.set_default_timeout()` methods.
  2817. """
  2818. return mapping.from_maybe_impl(
  2819. self._sync(self._impl_obj.wait_for_load_state(state=state, timeout=timeout))
  2820. )
  2821. def frame_element(self) -> "ElementHandle":
  2822. """Frame.frame_element
  2823. Returns the `frame` or `iframe` element handle which corresponds to this frame.
  2824. This is an inverse of `element_handle.content_frame()`. Note that returned handle actually belongs to the
  2825. parent frame.
  2826. This method throws an error if the frame has been detached before `frameElement()` returns.
  2827. **Usage**
  2828. ```py
  2829. frame_element = frame.frame_element()
  2830. content_frame = frame_element.content_frame()
  2831. assert frame == content_frame
  2832. ```
  2833. Returns
  2834. -------
  2835. ElementHandle
  2836. """
  2837. return mapping.from_impl(self._sync(self._impl_obj.frame_element()))
  2838. def evaluate(
  2839. self, expression: str, arg: typing.Optional[typing.Any] = None
  2840. ) -> typing.Any:
  2841. """Frame.evaluate
  2842. Returns the return value of `expression`.
  2843. If the function passed to the `frame.evaluate()` returns a [Promise], then `frame.evaluate()` would
  2844. wait for the promise to resolve and return its value.
  2845. If the function passed to the `frame.evaluate()` returns a non-[Serializable] value, then
  2846. `frame.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
  2847. are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  2848. **Usage**
  2849. ```py
  2850. result = frame.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
  2851. print(result) # prints \"56\"
  2852. ```
  2853. A string can also be passed in instead of a function.
  2854. ```py
  2855. print(frame.evaluate(\"1 + 2\")) # prints \"3\"
  2856. x = 10
  2857. print(frame.evaluate(f\"1 + {x}\")) # prints \"11\"
  2858. ```
  2859. `ElementHandle` instances can be passed as an argument to the `frame.evaluate()`:
  2860. ```py
  2861. body_handle = frame.evaluate(\"document.body\")
  2862. html = frame.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
  2863. body_handle.dispose()
  2864. ```
  2865. Parameters
  2866. ----------
  2867. expression : str
  2868. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2869. function is automatically invoked.
  2870. arg : Union[Any, None]
  2871. Optional argument to pass to `expression`.
  2872. Returns
  2873. -------
  2874. Any
  2875. """
  2876. return mapping.from_maybe_impl(
  2877. self._sync(
  2878. self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
  2879. )
  2880. )
  2881. def evaluate_handle(
  2882. self, expression: str, arg: typing.Optional[typing.Any] = None
  2883. ) -> "JSHandle":
  2884. """Frame.evaluate_handle
  2885. Returns the return value of `expression` as a `JSHandle`.
  2886. The only difference between `frame.evaluate()` and `frame.evaluate_handle()` is that
  2887. `frame.evaluate_handle()` returns `JSHandle`.
  2888. If the function, passed to the `frame.evaluate_handle()`, returns a [Promise], then
  2889. `frame.evaluate_handle()` would wait for the promise to resolve and return its value.
  2890. **Usage**
  2891. ```py
  2892. a_window_handle = frame.evaluate_handle(\"Promise.resolve(window)\")
  2893. a_window_handle # handle for the window object.
  2894. ```
  2895. A string can also be passed in instead of a function.
  2896. ```py
  2897. a_handle = page.evaluate_handle(\"document\") # handle for the \"document\"
  2898. ```
  2899. `JSHandle` instances can be passed as an argument to the `frame.evaluate_handle()`:
  2900. ```py
  2901. a_handle = page.evaluate_handle(\"document.body\")
  2902. result_handle = page.evaluate_handle(\"body => body.innerHTML\", a_handle)
  2903. print(result_handle.json_value())
  2904. result_handle.dispose()
  2905. ```
  2906. Parameters
  2907. ----------
  2908. expression : str
  2909. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2910. function is automatically invoked.
  2911. arg : Union[Any, None]
  2912. Optional argument to pass to `expression`.
  2913. Returns
  2914. -------
  2915. JSHandle
  2916. """
  2917. return mapping.from_impl(
  2918. self._sync(
  2919. self._impl_obj.evaluate_handle(
  2920. expression=expression, arg=mapping.to_impl(arg)
  2921. )
  2922. )
  2923. )
  2924. def query_selector(
  2925. self, selector: str, *, strict: typing.Optional[bool] = None
  2926. ) -> typing.Optional["ElementHandle"]:
  2927. """Frame.query_selector
  2928. Returns the ElementHandle pointing to the frame element.
  2929. **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects and web-first assertions instead.
  2930. The method finds an element matching the specified selector within the frame. If no elements match the selector,
  2931. returns `null`.
  2932. Parameters
  2933. ----------
  2934. selector : str
  2935. A selector to query for.
  2936. strict : Union[bool, None]
  2937. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2938. element, the call throws an exception.
  2939. Returns
  2940. -------
  2941. Union[ElementHandle, None]
  2942. """
  2943. return mapping.from_impl_nullable(
  2944. self._sync(self._impl_obj.query_selector(selector=selector, strict=strict))
  2945. )
  2946. def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  2947. """Frame.query_selector_all
  2948. Returns the ElementHandles pointing to the frame elements.
  2949. **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects instead.
  2950. The method finds all elements matching the specified selector within the frame. If no elements match the selector,
  2951. returns empty array.
  2952. Parameters
  2953. ----------
  2954. selector : str
  2955. A selector to query for.
  2956. Returns
  2957. -------
  2958. List[ElementHandle]
  2959. """
  2960. return mapping.from_impl_list(
  2961. self._sync(self._impl_obj.query_selector_all(selector=selector))
  2962. )
  2963. def wait_for_selector(
  2964. self,
  2965. selector: str,
  2966. *,
  2967. strict: typing.Optional[bool] = None,
  2968. timeout: typing.Optional[float] = None,
  2969. state: typing.Optional[
  2970. Literal["attached", "detached", "hidden", "visible"]
  2971. ] = None,
  2972. ) -> typing.Optional["ElementHandle"]:
  2973. """Frame.wait_for_selector
  2974. Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
  2975. `detached`.
  2976. **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
  2977. objects and web-first assertions make the code wait-for-selector-free.
  2978. Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
  2979. at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
  2980. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
  2981. **Usage**
  2982. This method works across navigations:
  2983. ```py
  2984. from playwright.sync_api import sync_playwright, Playwright
  2985. def run(playwright: Playwright):
  2986. chromium = playwright.chromium
  2987. browser = chromium.launch()
  2988. page = browser.new_page()
  2989. for current_url in [\"https://google.com\", \"https://bbc.com\"]:
  2990. page.goto(current_url, wait_until=\"domcontentloaded\")
  2991. element = page.main_frame.wait_for_selector(\"img\")
  2992. print(\"Loaded image: \" + str(element.get_attribute(\"src\")))
  2993. browser.close()
  2994. with sync_playwright() as playwright:
  2995. run(playwright)
  2996. ```
  2997. Parameters
  2998. ----------
  2999. selector : str
  3000. A selector to query for.
  3001. strict : Union[bool, None]
  3002. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3003. element, the call throws an exception.
  3004. timeout : Union[float, None]
  3005. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3006. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3007. state : Union["attached", "detached", "hidden", "visible", None]
  3008. Defaults to `'visible'`. Can be either:
  3009. - `'attached'` - wait for element to be present in DOM.
  3010. - `'detached'` - wait for element to not be present in DOM.
  3011. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  3012. without any content or with `display:none` has an empty bounding box and is not considered visible.
  3013. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  3014. `visibility:hidden`. This is opposite to the `'visible'` option.
  3015. Returns
  3016. -------
  3017. Union[ElementHandle, None]
  3018. """
  3019. return mapping.from_impl_nullable(
  3020. self._sync(
  3021. self._impl_obj.wait_for_selector(
  3022. selector=selector, strict=strict, timeout=timeout, state=state
  3023. )
  3024. )
  3025. )
  3026. def is_checked(
  3027. self,
  3028. selector: str,
  3029. *,
  3030. strict: typing.Optional[bool] = None,
  3031. timeout: typing.Optional[float] = None,
  3032. ) -> bool:
  3033. """Frame.is_checked
  3034. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  3035. Parameters
  3036. ----------
  3037. selector : str
  3038. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3039. used.
  3040. strict : Union[bool, None]
  3041. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3042. element, the call throws an exception.
  3043. timeout : Union[float, None]
  3044. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3045. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3046. Returns
  3047. -------
  3048. bool
  3049. """
  3050. return mapping.from_maybe_impl(
  3051. self._sync(
  3052. self._impl_obj.is_checked(
  3053. selector=selector, strict=strict, timeout=timeout
  3054. )
  3055. )
  3056. )
  3057. def is_disabled(
  3058. self,
  3059. selector: str,
  3060. *,
  3061. strict: typing.Optional[bool] = None,
  3062. timeout: typing.Optional[float] = None,
  3063. ) -> bool:
  3064. """Frame.is_disabled
  3065. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  3066. Parameters
  3067. ----------
  3068. selector : str
  3069. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3070. used.
  3071. strict : Union[bool, None]
  3072. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3073. element, the call throws an exception.
  3074. timeout : Union[float, None]
  3075. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3076. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3077. Returns
  3078. -------
  3079. bool
  3080. """
  3081. return mapping.from_maybe_impl(
  3082. self._sync(
  3083. self._impl_obj.is_disabled(
  3084. selector=selector, strict=strict, timeout=timeout
  3085. )
  3086. )
  3087. )
  3088. def is_editable(
  3089. self,
  3090. selector: str,
  3091. *,
  3092. strict: typing.Optional[bool] = None,
  3093. timeout: typing.Optional[float] = None,
  3094. ) -> bool:
  3095. """Frame.is_editable
  3096. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  3097. Parameters
  3098. ----------
  3099. selector : str
  3100. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3101. used.
  3102. strict : Union[bool, None]
  3103. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3104. element, the call throws an exception.
  3105. timeout : Union[float, None]
  3106. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3107. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3108. Returns
  3109. -------
  3110. bool
  3111. """
  3112. return mapping.from_maybe_impl(
  3113. self._sync(
  3114. self._impl_obj.is_editable(
  3115. selector=selector, strict=strict, timeout=timeout
  3116. )
  3117. )
  3118. )
  3119. def is_enabled(
  3120. self,
  3121. selector: str,
  3122. *,
  3123. strict: typing.Optional[bool] = None,
  3124. timeout: typing.Optional[float] = None,
  3125. ) -> bool:
  3126. """Frame.is_enabled
  3127. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  3128. Parameters
  3129. ----------
  3130. selector : str
  3131. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3132. used.
  3133. strict : Union[bool, None]
  3134. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3135. element, the call throws an exception.
  3136. timeout : Union[float, None]
  3137. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3138. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3139. Returns
  3140. -------
  3141. bool
  3142. """
  3143. return mapping.from_maybe_impl(
  3144. self._sync(
  3145. self._impl_obj.is_enabled(
  3146. selector=selector, strict=strict, timeout=timeout
  3147. )
  3148. )
  3149. )
  3150. def is_hidden(self, selector: str, *, strict: typing.Optional[bool] = None) -> bool:
  3151. """Frame.is_hidden
  3152. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
  3153. does not match any elements is considered hidden.
  3154. Parameters
  3155. ----------
  3156. selector : str
  3157. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3158. used.
  3159. strict : Union[bool, None]
  3160. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3161. element, the call throws an exception.
  3162. Returns
  3163. -------
  3164. bool
  3165. """
  3166. return mapping.from_maybe_impl(
  3167. self._sync(self._impl_obj.is_hidden(selector=selector, strict=strict))
  3168. )
  3169. def is_visible(
  3170. self, selector: str, *, strict: typing.Optional[bool] = None
  3171. ) -> bool:
  3172. """Frame.is_visible
  3173. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
  3174. is considered not visible.
  3175. Parameters
  3176. ----------
  3177. selector : str
  3178. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3179. used.
  3180. strict : Union[bool, None]
  3181. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3182. element, the call throws an exception.
  3183. Returns
  3184. -------
  3185. bool
  3186. """
  3187. return mapping.from_maybe_impl(
  3188. self._sync(self._impl_obj.is_visible(selector=selector, strict=strict))
  3189. )
  3190. def dispatch_event(
  3191. self,
  3192. selector: str,
  3193. type: str,
  3194. event_init: typing.Optional[typing.Dict] = None,
  3195. *,
  3196. strict: typing.Optional[bool] = None,
  3197. timeout: typing.Optional[float] = None,
  3198. ) -> None:
  3199. """Frame.dispatch_event
  3200. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  3201. `click` is dispatched. This is equivalent to calling
  3202. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  3203. **Usage**
  3204. ```py
  3205. frame.dispatch_event(\"button#submit\", \"click\")
  3206. ```
  3207. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  3208. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  3209. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  3210. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  3211. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  3212. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  3213. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  3214. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  3215. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  3216. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  3217. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  3218. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  3219. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  3220. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  3221. ```py
  3222. # note you can only create data_transfer in chromium and firefox
  3223. data_transfer = frame.evaluate_handle(\"new DataTransfer()\")
  3224. frame.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
  3225. ```
  3226. Parameters
  3227. ----------
  3228. selector : str
  3229. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3230. used.
  3231. type : str
  3232. DOM event type: `"click"`, `"dragstart"`, etc.
  3233. event_init : Union[Dict, None]
  3234. Optional event-specific initialization properties.
  3235. strict : Union[bool, None]
  3236. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3237. element, the call throws an exception.
  3238. timeout : Union[float, None]
  3239. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3240. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3241. """
  3242. return mapping.from_maybe_impl(
  3243. self._sync(
  3244. self._impl_obj.dispatch_event(
  3245. selector=selector,
  3246. type=type,
  3247. eventInit=mapping.to_impl(event_init),
  3248. strict=strict,
  3249. timeout=timeout,
  3250. )
  3251. )
  3252. )
  3253. def eval_on_selector(
  3254. self,
  3255. selector: str,
  3256. expression: str,
  3257. arg: typing.Optional[typing.Any] = None,
  3258. *,
  3259. strict: typing.Optional[bool] = None,
  3260. ) -> typing.Any:
  3261. """Frame.eval_on_selector
  3262. Returns the return value of `expression`.
  3263. The method finds an element matching the specified selector within the frame and passes it as a first argument to
  3264. `expression`. If no elements match the selector, the method throws an error.
  3265. If `expression` returns a [Promise], then `frame.eval_on_selector()` would wait for the promise to resolve
  3266. and return its value.
  3267. **Usage**
  3268. ```py
  3269. search_value = frame.eval_on_selector(\"#search\", \"el => el.value\")
  3270. preload_href = frame.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
  3271. html = frame.eval_on_selector(\".main-container\", \"(e, suffix) => e.outerHTML + suffix\", \"hello\")
  3272. ```
  3273. Parameters
  3274. ----------
  3275. selector : str
  3276. A selector to query for.
  3277. expression : str
  3278. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3279. function is automatically invoked.
  3280. arg : Union[Any, None]
  3281. Optional argument to pass to `expression`.
  3282. strict : Union[bool, None]
  3283. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3284. element, the call throws an exception.
  3285. Returns
  3286. -------
  3287. Any
  3288. """
  3289. return mapping.from_maybe_impl(
  3290. self._sync(
  3291. self._impl_obj.eval_on_selector(
  3292. selector=selector,
  3293. expression=expression,
  3294. arg=mapping.to_impl(arg),
  3295. strict=strict,
  3296. )
  3297. )
  3298. )
  3299. def eval_on_selector_all(
  3300. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  3301. ) -> typing.Any:
  3302. """Frame.eval_on_selector_all
  3303. Returns the return value of `expression`.
  3304. The method finds all elements matching the specified selector within the frame and passes an array of matched
  3305. elements as a first argument to `expression`.
  3306. If `expression` returns a [Promise], then `frame.eval_on_selector_all()` would wait for the promise to resolve
  3307. and return its value.
  3308. **Usage**
  3309. ```py
  3310. divs_counts = frame.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
  3311. ```
  3312. Parameters
  3313. ----------
  3314. selector : str
  3315. A selector to query for.
  3316. expression : str
  3317. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3318. function is automatically invoked.
  3319. arg : Union[Any, None]
  3320. Optional argument to pass to `expression`.
  3321. Returns
  3322. -------
  3323. Any
  3324. """
  3325. return mapping.from_maybe_impl(
  3326. self._sync(
  3327. self._impl_obj.eval_on_selector_all(
  3328. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  3329. )
  3330. )
  3331. )
  3332. def content(self) -> str:
  3333. """Frame.content
  3334. Gets the full HTML contents of the frame, including the doctype.
  3335. Returns
  3336. -------
  3337. str
  3338. """
  3339. return mapping.from_maybe_impl(self._sync(self._impl_obj.content()))
  3340. def set_content(
  3341. self,
  3342. html: str,
  3343. *,
  3344. timeout: typing.Optional[float] = None,
  3345. wait_until: typing.Optional[
  3346. Literal["commit", "domcontentloaded", "load", "networkidle"]
  3347. ] = None,
  3348. ) -> None:
  3349. """Frame.set_content
  3350. This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
  3351. inheriting all its specific characteristics and behaviors.
  3352. Parameters
  3353. ----------
  3354. html : str
  3355. HTML markup to assign to the page.
  3356. timeout : Union[float, None]
  3357. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  3358. be changed by using the `browser_context.set_default_navigation_timeout()`,
  3359. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  3360. `page.set_default_timeout()` methods.
  3361. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  3362. When to consider operation succeeded, defaults to `load`. Events can be either:
  3363. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  3364. - `'load'` - consider operation to be finished when the `load` event is fired.
  3365. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  3366. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  3367. - `'commit'` - consider operation to be finished when network response is received and the document started
  3368. loading.
  3369. """
  3370. return mapping.from_maybe_impl(
  3371. self._sync(
  3372. self._impl_obj.set_content(
  3373. html=html, timeout=timeout, waitUntil=wait_until
  3374. )
  3375. )
  3376. )
  3377. def is_detached(self) -> bool:
  3378. """Frame.is_detached
  3379. Returns `true` if the frame has been detached, or `false` otherwise.
  3380. Returns
  3381. -------
  3382. bool
  3383. """
  3384. return mapping.from_maybe_impl(self._impl_obj.is_detached())
  3385. def add_script_tag(
  3386. self,
  3387. *,
  3388. url: typing.Optional[str] = None,
  3389. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  3390. content: typing.Optional[str] = None,
  3391. type: typing.Optional[str] = None,
  3392. ) -> "ElementHandle":
  3393. """Frame.add_script_tag
  3394. Returns the added tag when the script's onload fires or when the script content was injected into frame.
  3395. Adds a `<script>` tag into the page with the desired url or content.
  3396. Parameters
  3397. ----------
  3398. url : Union[str, None]
  3399. URL of a script to be added.
  3400. path : Union[pathlib.Path, str, None]
  3401. Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
  3402. to the current working directory.
  3403. content : Union[str, None]
  3404. Raw JavaScript content to be injected into frame.
  3405. type : Union[str, None]
  3406. Script type. Use 'module' in order to load a JavaScript ES6 module. See
  3407. [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
  3408. Returns
  3409. -------
  3410. ElementHandle
  3411. """
  3412. return mapping.from_impl(
  3413. self._sync(
  3414. self._impl_obj.add_script_tag(
  3415. url=url, path=path, content=content, type=type
  3416. )
  3417. )
  3418. )
  3419. def add_style_tag(
  3420. self,
  3421. *,
  3422. url: typing.Optional[str] = None,
  3423. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  3424. content: typing.Optional[str] = None,
  3425. ) -> "ElementHandle":
  3426. """Frame.add_style_tag
  3427. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
  3428. Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
  3429. content.
  3430. Parameters
  3431. ----------
  3432. url : Union[str, None]
  3433. URL of the `<link>` tag.
  3434. path : Union[pathlib.Path, str, None]
  3435. Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
  3436. current working directory.
  3437. content : Union[str, None]
  3438. Raw CSS content to be injected into frame.
  3439. Returns
  3440. -------
  3441. ElementHandle
  3442. """
  3443. return mapping.from_impl(
  3444. self._sync(
  3445. self._impl_obj.add_style_tag(url=url, path=path, content=content)
  3446. )
  3447. )
  3448. def click(
  3449. self,
  3450. selector: str,
  3451. *,
  3452. modifiers: typing.Optional[
  3453. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3454. ] = None,
  3455. position: typing.Optional[Position] = None,
  3456. delay: typing.Optional[float] = None,
  3457. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  3458. click_count: typing.Optional[int] = None,
  3459. timeout: typing.Optional[float] = None,
  3460. force: typing.Optional[bool] = None,
  3461. no_wait_after: typing.Optional[bool] = None,
  3462. strict: typing.Optional[bool] = None,
  3463. trial: typing.Optional[bool] = None,
  3464. ) -> None:
  3465. """Frame.click
  3466. This method clicks an element matching `selector` by performing the following steps:
  3467. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3468. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3469. the element is detached during the checks, the whole action is retried.
  3470. 1. Scroll the element into view if needed.
  3471. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  3472. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  3473. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3474. Passing zero timeout disables this.
  3475. Parameters
  3476. ----------
  3477. selector : str
  3478. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3479. used.
  3480. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3481. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3482. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3483. "Control" on Windows and Linux and to "Meta" on macOS.
  3484. position : Union[{x: float, y: float}, None]
  3485. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3486. the element.
  3487. delay : Union[float, None]
  3488. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  3489. button : Union["left", "middle", "right", None]
  3490. Defaults to `left`.
  3491. click_count : Union[int, None]
  3492. defaults to 1. See [UIEvent.detail].
  3493. timeout : Union[float, None]
  3494. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3495. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3496. force : Union[bool, None]
  3497. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3498. no_wait_after : Union[bool, None]
  3499. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  3500. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  3501. navigating to inaccessible pages. Defaults to `false`.
  3502. Deprecated: This option will default to `true` in the future.
  3503. strict : Union[bool, None]
  3504. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3505. element, the call throws an exception.
  3506. trial : Union[bool, None]
  3507. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3508. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3509. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3510. are pressed.
  3511. """
  3512. return mapping.from_maybe_impl(
  3513. self._sync(
  3514. self._impl_obj.click(
  3515. selector=selector,
  3516. modifiers=mapping.to_impl(modifiers),
  3517. position=position,
  3518. delay=delay,
  3519. button=button,
  3520. clickCount=click_count,
  3521. timeout=timeout,
  3522. force=force,
  3523. noWaitAfter=no_wait_after,
  3524. strict=strict,
  3525. trial=trial,
  3526. )
  3527. )
  3528. )
  3529. def dblclick(
  3530. self,
  3531. selector: str,
  3532. *,
  3533. modifiers: typing.Optional[
  3534. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3535. ] = None,
  3536. position: typing.Optional[Position] = None,
  3537. delay: typing.Optional[float] = None,
  3538. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  3539. timeout: typing.Optional[float] = None,
  3540. force: typing.Optional[bool] = None,
  3541. no_wait_after: typing.Optional[bool] = None,
  3542. strict: typing.Optional[bool] = None,
  3543. trial: typing.Optional[bool] = None,
  3544. ) -> None:
  3545. """Frame.dblclick
  3546. This method double clicks an element matching `selector` by performing the following steps:
  3547. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3548. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3549. the element is detached during the checks, the whole action is retried.
  3550. 1. Scroll the element into view if needed.
  3551. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`. if
  3552. the first click of the `dblclick()` triggers a navigation event, this method will throw.
  3553. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3554. Passing zero timeout disables this.
  3555. **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
  3556. Parameters
  3557. ----------
  3558. selector : str
  3559. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3560. used.
  3561. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3562. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3563. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3564. "Control" on Windows and Linux and to "Meta" on macOS.
  3565. position : Union[{x: float, y: float}, None]
  3566. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3567. the element.
  3568. delay : Union[float, None]
  3569. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  3570. button : Union["left", "middle", "right", None]
  3571. Defaults to `left`.
  3572. timeout : Union[float, None]
  3573. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3574. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3575. force : Union[bool, None]
  3576. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3577. no_wait_after : Union[bool, None]
  3578. This option has no effect.
  3579. Deprecated: This option has no effect.
  3580. strict : Union[bool, None]
  3581. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3582. element, the call throws an exception.
  3583. trial : Union[bool, None]
  3584. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3585. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3586. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3587. are pressed.
  3588. """
  3589. return mapping.from_maybe_impl(
  3590. self._sync(
  3591. self._impl_obj.dblclick(
  3592. selector=selector,
  3593. modifiers=mapping.to_impl(modifiers),
  3594. position=position,
  3595. delay=delay,
  3596. button=button,
  3597. timeout=timeout,
  3598. force=force,
  3599. noWaitAfter=no_wait_after,
  3600. strict=strict,
  3601. trial=trial,
  3602. )
  3603. )
  3604. )
  3605. def tap(
  3606. self,
  3607. selector: str,
  3608. *,
  3609. modifiers: typing.Optional[
  3610. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3611. ] = None,
  3612. position: typing.Optional[Position] = None,
  3613. timeout: typing.Optional[float] = None,
  3614. force: typing.Optional[bool] = None,
  3615. no_wait_after: typing.Optional[bool] = None,
  3616. strict: typing.Optional[bool] = None,
  3617. trial: typing.Optional[bool] = None,
  3618. ) -> None:
  3619. """Frame.tap
  3620. This method taps an element matching `selector` by performing the following steps:
  3621. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3622. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3623. the element is detached during the checks, the whole action is retried.
  3624. 1. Scroll the element into view if needed.
  3625. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  3626. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3627. Passing zero timeout disables this.
  3628. **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
  3629. Parameters
  3630. ----------
  3631. selector : str
  3632. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3633. used.
  3634. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3635. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3636. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3637. "Control" on Windows and Linux and to "Meta" on macOS.
  3638. position : Union[{x: float, y: float}, None]
  3639. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3640. the element.
  3641. timeout : Union[float, None]
  3642. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3643. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3644. force : Union[bool, None]
  3645. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3646. no_wait_after : Union[bool, None]
  3647. This option has no effect.
  3648. Deprecated: This option has no effect.
  3649. strict : Union[bool, None]
  3650. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3651. element, the call throws an exception.
  3652. trial : Union[bool, None]
  3653. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3654. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3655. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3656. are pressed.
  3657. """
  3658. return mapping.from_maybe_impl(
  3659. self._sync(
  3660. self._impl_obj.tap(
  3661. selector=selector,
  3662. modifiers=mapping.to_impl(modifiers),
  3663. position=position,
  3664. timeout=timeout,
  3665. force=force,
  3666. noWaitAfter=no_wait_after,
  3667. strict=strict,
  3668. trial=trial,
  3669. )
  3670. )
  3671. )
  3672. def fill(
  3673. self,
  3674. selector: str,
  3675. value: str,
  3676. *,
  3677. timeout: typing.Optional[float] = None,
  3678. no_wait_after: typing.Optional[bool] = None,
  3679. strict: typing.Optional[bool] = None,
  3680. force: typing.Optional[bool] = None,
  3681. ) -> None:
  3682. """Frame.fill
  3683. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
  3684. focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
  3685. to clear the input field.
  3686. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  3687. error. However, if the element is inside the `<label>` element that has an associated
  3688. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  3689. instead.
  3690. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  3691. Parameters
  3692. ----------
  3693. selector : str
  3694. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3695. used.
  3696. value : str
  3697. Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
  3698. timeout : Union[float, None]
  3699. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3700. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3701. no_wait_after : Union[bool, None]
  3702. This option has no effect.
  3703. Deprecated: This option has no effect.
  3704. strict : Union[bool, None]
  3705. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3706. element, the call throws an exception.
  3707. force : Union[bool, None]
  3708. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3709. """
  3710. return mapping.from_maybe_impl(
  3711. self._sync(
  3712. self._impl_obj.fill(
  3713. selector=selector,
  3714. value=value,
  3715. timeout=timeout,
  3716. noWaitAfter=no_wait_after,
  3717. strict=strict,
  3718. force=force,
  3719. )
  3720. )
  3721. )
  3722. def locator(
  3723. self,
  3724. selector: str,
  3725. *,
  3726. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3727. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3728. has: typing.Optional["Locator"] = None,
  3729. has_not: typing.Optional["Locator"] = None,
  3730. ) -> "Locator":
  3731. """Frame.locator
  3732. The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
  3733. to the element immediately before performing an action, so a series of actions on the same locator can in fact be
  3734. performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
  3735. [Learn more about locators](https://playwright.dev/python/docs/locators).
  3736. [Learn more about locators](https://playwright.dev/python/docs/locators).
  3737. Parameters
  3738. ----------
  3739. selector : str
  3740. A selector to use when resolving DOM element.
  3741. has_text : Union[Pattern[str], str, None]
  3742. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  3743. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  3744. `<article><div>Playwright</div></article>`.
  3745. has_not_text : Union[Pattern[str], str, None]
  3746. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  3747. When passed a [string], matching is case-insensitive and searches for a substring.
  3748. has : Union[Locator, None]
  3749. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  3750. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  3751. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  3752. the document root. For example, you can find `content` that has `div` in
  3753. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  3754. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  3755. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  3756. has_not : Union[Locator, None]
  3757. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  3758. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  3759. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  3760. Returns
  3761. -------
  3762. Locator
  3763. """
  3764. return mapping.from_impl(
  3765. self._impl_obj.locator(
  3766. selector=selector,
  3767. hasText=has_text,
  3768. hasNotText=has_not_text,
  3769. has=has._impl_obj if has else None,
  3770. hasNot=has_not._impl_obj if has_not else None,
  3771. )
  3772. )
  3773. def get_by_alt_text(
  3774. self,
  3775. text: typing.Union[str, typing.Pattern[str]],
  3776. *,
  3777. exact: typing.Optional[bool] = None,
  3778. ) -> "Locator":
  3779. """Frame.get_by_alt_text
  3780. Allows locating elements by their alt text.
  3781. **Usage**
  3782. For example, this method will find the image by alt text \"Playwright logo\":
  3783. ```html
  3784. <img alt='Playwright logo'>
  3785. ```
  3786. ```py
  3787. page.get_by_alt_text(\"Playwright logo\").click()
  3788. ```
  3789. Parameters
  3790. ----------
  3791. text : Union[Pattern[str], str]
  3792. Text to locate the element for.
  3793. exact : Union[bool, None]
  3794. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3795. regular expression. Note that exact match still trims whitespace.
  3796. Returns
  3797. -------
  3798. Locator
  3799. """
  3800. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  3801. def get_by_label(
  3802. self,
  3803. text: typing.Union[str, typing.Pattern[str]],
  3804. *,
  3805. exact: typing.Optional[bool] = None,
  3806. ) -> "Locator":
  3807. """Frame.get_by_label
  3808. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  3809. `aria-label` attribute.
  3810. **Usage**
  3811. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  3812. ```html
  3813. <input aria-label=\"Username\">
  3814. <label for=\"password-input\">Password:</label>
  3815. <input id=\"password-input\">
  3816. ```
  3817. ```py
  3818. page.get_by_label(\"Username\").fill(\"john\")
  3819. page.get_by_label(\"Password\").fill(\"secret\")
  3820. ```
  3821. Parameters
  3822. ----------
  3823. text : Union[Pattern[str], str]
  3824. Text to locate the element for.
  3825. exact : Union[bool, None]
  3826. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3827. regular expression. Note that exact match still trims whitespace.
  3828. Returns
  3829. -------
  3830. Locator
  3831. """
  3832. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  3833. def get_by_placeholder(
  3834. self,
  3835. text: typing.Union[str, typing.Pattern[str]],
  3836. *,
  3837. exact: typing.Optional[bool] = None,
  3838. ) -> "Locator":
  3839. """Frame.get_by_placeholder
  3840. Allows locating input elements by the placeholder text.
  3841. **Usage**
  3842. For example, consider the following DOM structure.
  3843. ```html
  3844. <input type=\"email\" placeholder=\"name@example.com\" />
  3845. ```
  3846. You can fill the input after locating it by the placeholder text:
  3847. ```py
  3848. page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  3849. ```
  3850. Parameters
  3851. ----------
  3852. text : Union[Pattern[str], str]
  3853. Text to locate the element for.
  3854. exact : Union[bool, None]
  3855. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3856. regular expression. Note that exact match still trims whitespace.
  3857. Returns
  3858. -------
  3859. Locator
  3860. """
  3861. return mapping.from_impl(
  3862. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  3863. )
  3864. def get_by_role(
  3865. self,
  3866. role: Literal[
  3867. "alert",
  3868. "alertdialog",
  3869. "application",
  3870. "article",
  3871. "banner",
  3872. "blockquote",
  3873. "button",
  3874. "caption",
  3875. "cell",
  3876. "checkbox",
  3877. "code",
  3878. "columnheader",
  3879. "combobox",
  3880. "complementary",
  3881. "contentinfo",
  3882. "definition",
  3883. "deletion",
  3884. "dialog",
  3885. "directory",
  3886. "document",
  3887. "emphasis",
  3888. "feed",
  3889. "figure",
  3890. "form",
  3891. "generic",
  3892. "grid",
  3893. "gridcell",
  3894. "group",
  3895. "heading",
  3896. "img",
  3897. "insertion",
  3898. "link",
  3899. "list",
  3900. "listbox",
  3901. "listitem",
  3902. "log",
  3903. "main",
  3904. "marquee",
  3905. "math",
  3906. "menu",
  3907. "menubar",
  3908. "menuitem",
  3909. "menuitemcheckbox",
  3910. "menuitemradio",
  3911. "meter",
  3912. "navigation",
  3913. "none",
  3914. "note",
  3915. "option",
  3916. "paragraph",
  3917. "presentation",
  3918. "progressbar",
  3919. "radio",
  3920. "radiogroup",
  3921. "region",
  3922. "row",
  3923. "rowgroup",
  3924. "rowheader",
  3925. "scrollbar",
  3926. "search",
  3927. "searchbox",
  3928. "separator",
  3929. "slider",
  3930. "spinbutton",
  3931. "status",
  3932. "strong",
  3933. "subscript",
  3934. "superscript",
  3935. "switch",
  3936. "tab",
  3937. "table",
  3938. "tablist",
  3939. "tabpanel",
  3940. "term",
  3941. "textbox",
  3942. "time",
  3943. "timer",
  3944. "toolbar",
  3945. "tooltip",
  3946. "tree",
  3947. "treegrid",
  3948. "treeitem",
  3949. ],
  3950. *,
  3951. checked: typing.Optional[bool] = None,
  3952. disabled: typing.Optional[bool] = None,
  3953. expanded: typing.Optional[bool] = None,
  3954. include_hidden: typing.Optional[bool] = None,
  3955. level: typing.Optional[int] = None,
  3956. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3957. pressed: typing.Optional[bool] = None,
  3958. selected: typing.Optional[bool] = None,
  3959. exact: typing.Optional[bool] = None,
  3960. ) -> "Locator":
  3961. """Frame.get_by_role
  3962. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  3963. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  3964. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  3965. **Usage**
  3966. Consider the following DOM structure.
  3967. ```html
  3968. <h3>Sign up</h3>
  3969. <label>
  3970. <input type=\"checkbox\" /> Subscribe
  3971. </label>
  3972. <br/>
  3973. <button>Submit</button>
  3974. ```
  3975. You can locate each element by it's implicit role:
  3976. ```py
  3977. expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  3978. page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  3979. page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  3980. ```
  3981. **Details**
  3982. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  3983. about the ARIA guidelines.
  3984. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  3985. that is recognized by the role selector. You can find all the
  3986. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  3987. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  3988. Parameters
  3989. ----------
  3990. role : Union["alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"]
  3991. Required aria role.
  3992. checked : Union[bool, None]
  3993. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  3994. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  3995. disabled : Union[bool, None]
  3996. An attribute that is usually set by `aria-disabled` or `disabled`.
  3997. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  3998. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  3999. expanded : Union[bool, None]
  4000. An attribute that is usually set by `aria-expanded`.
  4001. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  4002. include_hidden : Union[bool, None]
  4003. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  4004. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  4005. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  4006. level : Union[int, None]
  4007. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  4008. for `<h1>-<h6>` elements.
  4009. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  4010. name : Union[Pattern[str], str, None]
  4011. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  4012. case-insensitive and searches for a substring, use `exact` to control this behavior.
  4013. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  4014. pressed : Union[bool, None]
  4015. An attribute that is usually set by `aria-pressed`.
  4016. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  4017. selected : Union[bool, None]
  4018. An attribute that is usually set by `aria-selected`.
  4019. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  4020. exact : Union[bool, None]
  4021. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  4022. regular expression. Note that exact match still trims whitespace.
  4023. Returns
  4024. -------
  4025. Locator
  4026. """
  4027. return mapping.from_impl(
  4028. self._impl_obj.get_by_role(
  4029. role=role,
  4030. checked=checked,
  4031. disabled=disabled,
  4032. expanded=expanded,
  4033. includeHidden=include_hidden,
  4034. level=level,
  4035. name=name,
  4036. pressed=pressed,
  4037. selected=selected,
  4038. exact=exact,
  4039. )
  4040. )
  4041. def get_by_test_id(
  4042. self, test_id: typing.Union[str, typing.Pattern[str]]
  4043. ) -> "Locator":
  4044. """Frame.get_by_test_id
  4045. Locate element by the test id.
  4046. **Usage**
  4047. Consider the following DOM structure.
  4048. ```html
  4049. <button data-testid=\"directions\">Itinéraire</button>
  4050. ```
  4051. You can locate the element by it's test id:
  4052. ```py
  4053. page.get_by_test_id(\"directions\").click()
  4054. ```
  4055. **Details**
  4056. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  4057. configure a different test id attribute if necessary.
  4058. Parameters
  4059. ----------
  4060. test_id : Union[Pattern[str], str]
  4061. Id to locate the element by.
  4062. Returns
  4063. -------
  4064. Locator
  4065. """
  4066. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  4067. def get_by_text(
  4068. self,
  4069. text: typing.Union[str, typing.Pattern[str]],
  4070. *,
  4071. exact: typing.Optional[bool] = None,
  4072. ) -> "Locator":
  4073. """Frame.get_by_text
  4074. Allows locating elements that contain given text.
  4075. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  4076. filter by the text content.
  4077. **Usage**
  4078. Consider the following DOM structure:
  4079. ```html
  4080. <div>Hello <span>world</span></div>
  4081. <div>Hello</div>
  4082. ```
  4083. You can locate by text substring, exact string, or a regular expression:
  4084. ```py
  4085. # Matches <span>
  4086. page.get_by_text(\"world\")
  4087. # Matches first <div>
  4088. page.get_by_text(\"Hello world\")
  4089. # Matches second <div>
  4090. page.get_by_text(\"Hello\", exact=True)
  4091. # Matches both <div>s
  4092. page.get_by_text(re.compile(\"Hello\"))
  4093. # Matches second <div>
  4094. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  4095. ```
  4096. **Details**
  4097. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  4098. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  4099. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  4100. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  4101. Parameters
  4102. ----------
  4103. text : Union[Pattern[str], str]
  4104. Text to locate the element for.
  4105. exact : Union[bool, None]
  4106. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4107. regular expression. Note that exact match still trims whitespace.
  4108. Returns
  4109. -------
  4110. Locator
  4111. """
  4112. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  4113. def get_by_title(
  4114. self,
  4115. text: typing.Union[str, typing.Pattern[str]],
  4116. *,
  4117. exact: typing.Optional[bool] = None,
  4118. ) -> "Locator":
  4119. """Frame.get_by_title
  4120. Allows locating elements by their title attribute.
  4121. **Usage**
  4122. Consider the following DOM structure.
  4123. ```html
  4124. <span title='Issues count'>25 issues</span>
  4125. ```
  4126. You can check the issues count after locating it by the title text:
  4127. ```py
  4128. expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  4129. ```
  4130. Parameters
  4131. ----------
  4132. text : Union[Pattern[str], str]
  4133. Text to locate the element for.
  4134. exact : Union[bool, None]
  4135. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4136. regular expression. Note that exact match still trims whitespace.
  4137. Returns
  4138. -------
  4139. Locator
  4140. """
  4141. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  4142. def frame_locator(self, selector: str) -> "FrameLocator":
  4143. """Frame.frame_locator
  4144. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  4145. in that iframe.
  4146. **Usage**
  4147. Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
  4148. id=\"my-frame\">`:
  4149. ```py
  4150. locator = frame.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
  4151. locator.click()
  4152. ```
  4153. Parameters
  4154. ----------
  4155. selector : str
  4156. A selector to use when resolving DOM element.
  4157. Returns
  4158. -------
  4159. FrameLocator
  4160. """
  4161. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  4162. def focus(
  4163. self,
  4164. selector: str,
  4165. *,
  4166. strict: typing.Optional[bool] = None,
  4167. timeout: typing.Optional[float] = None,
  4168. ) -> None:
  4169. """Frame.focus
  4170. This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
  4171. method waits until a matching element appears in the DOM.
  4172. Parameters
  4173. ----------
  4174. selector : str
  4175. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4176. used.
  4177. strict : Union[bool, None]
  4178. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4179. element, the call throws an exception.
  4180. timeout : Union[float, None]
  4181. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4182. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4183. """
  4184. return mapping.from_maybe_impl(
  4185. self._sync(
  4186. self._impl_obj.focus(selector=selector, strict=strict, timeout=timeout)
  4187. )
  4188. )
  4189. def text_content(
  4190. self,
  4191. selector: str,
  4192. *,
  4193. strict: typing.Optional[bool] = None,
  4194. timeout: typing.Optional[float] = None,
  4195. ) -> typing.Optional[str]:
  4196. """Frame.text_content
  4197. Returns `element.textContent`.
  4198. Parameters
  4199. ----------
  4200. selector : str
  4201. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4202. used.
  4203. strict : Union[bool, None]
  4204. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4205. element, the call throws an exception.
  4206. timeout : Union[float, None]
  4207. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4208. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4209. Returns
  4210. -------
  4211. Union[str, None]
  4212. """
  4213. return mapping.from_maybe_impl(
  4214. self._sync(
  4215. self._impl_obj.text_content(
  4216. selector=selector, strict=strict, timeout=timeout
  4217. )
  4218. )
  4219. )
  4220. def inner_text(
  4221. self,
  4222. selector: str,
  4223. *,
  4224. strict: typing.Optional[bool] = None,
  4225. timeout: typing.Optional[float] = None,
  4226. ) -> str:
  4227. """Frame.inner_text
  4228. Returns `element.innerText`.
  4229. Parameters
  4230. ----------
  4231. selector : str
  4232. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4233. used.
  4234. strict : Union[bool, None]
  4235. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4236. element, the call throws an exception.
  4237. timeout : Union[float, None]
  4238. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4239. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4240. Returns
  4241. -------
  4242. str
  4243. """
  4244. return mapping.from_maybe_impl(
  4245. self._sync(
  4246. self._impl_obj.inner_text(
  4247. selector=selector, strict=strict, timeout=timeout
  4248. )
  4249. )
  4250. )
  4251. def inner_html(
  4252. self,
  4253. selector: str,
  4254. *,
  4255. strict: typing.Optional[bool] = None,
  4256. timeout: typing.Optional[float] = None,
  4257. ) -> str:
  4258. """Frame.inner_html
  4259. Returns `element.innerHTML`.
  4260. Parameters
  4261. ----------
  4262. selector : str
  4263. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4264. used.
  4265. strict : Union[bool, None]
  4266. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4267. element, the call throws an exception.
  4268. timeout : Union[float, None]
  4269. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4270. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4271. Returns
  4272. -------
  4273. str
  4274. """
  4275. return mapping.from_maybe_impl(
  4276. self._sync(
  4277. self._impl_obj.inner_html(
  4278. selector=selector, strict=strict, timeout=timeout
  4279. )
  4280. )
  4281. )
  4282. def get_attribute(
  4283. self,
  4284. selector: str,
  4285. name: str,
  4286. *,
  4287. strict: typing.Optional[bool] = None,
  4288. timeout: typing.Optional[float] = None,
  4289. ) -> typing.Optional[str]:
  4290. """Frame.get_attribute
  4291. Returns element attribute value.
  4292. Parameters
  4293. ----------
  4294. selector : str
  4295. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4296. used.
  4297. name : str
  4298. Attribute name to get the value for.
  4299. strict : Union[bool, None]
  4300. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4301. element, the call throws an exception.
  4302. timeout : Union[float, None]
  4303. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4304. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4305. Returns
  4306. -------
  4307. Union[str, None]
  4308. """
  4309. return mapping.from_maybe_impl(
  4310. self._sync(
  4311. self._impl_obj.get_attribute(
  4312. selector=selector, name=name, strict=strict, timeout=timeout
  4313. )
  4314. )
  4315. )
  4316. def hover(
  4317. self,
  4318. selector: str,
  4319. *,
  4320. modifiers: typing.Optional[
  4321. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  4322. ] = None,
  4323. position: typing.Optional[Position] = None,
  4324. timeout: typing.Optional[float] = None,
  4325. no_wait_after: typing.Optional[bool] = None,
  4326. force: typing.Optional[bool] = None,
  4327. strict: typing.Optional[bool] = None,
  4328. trial: typing.Optional[bool] = None,
  4329. ) -> None:
  4330. """Frame.hover
  4331. This method hovers over an element matching `selector` by performing the following steps:
  4332. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4333. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4334. the element is detached during the checks, the whole action is retried.
  4335. 1. Scroll the element into view if needed.
  4336. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  4337. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4338. Passing zero timeout disables this.
  4339. Parameters
  4340. ----------
  4341. selector : str
  4342. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4343. used.
  4344. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  4345. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  4346. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  4347. "Control" on Windows and Linux and to "Meta" on macOS.
  4348. position : Union[{x: float, y: float}, None]
  4349. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4350. the element.
  4351. timeout : Union[float, None]
  4352. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4353. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4354. no_wait_after : Union[bool, None]
  4355. This option has no effect.
  4356. Deprecated: This option has no effect.
  4357. force : Union[bool, None]
  4358. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4359. strict : Union[bool, None]
  4360. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4361. element, the call throws an exception.
  4362. trial : Union[bool, None]
  4363. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4364. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  4365. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  4366. are pressed.
  4367. """
  4368. return mapping.from_maybe_impl(
  4369. self._sync(
  4370. self._impl_obj.hover(
  4371. selector=selector,
  4372. modifiers=mapping.to_impl(modifiers),
  4373. position=position,
  4374. timeout=timeout,
  4375. noWaitAfter=no_wait_after,
  4376. force=force,
  4377. strict=strict,
  4378. trial=trial,
  4379. )
  4380. )
  4381. )
  4382. def drag_and_drop(
  4383. self,
  4384. source: str,
  4385. target: str,
  4386. *,
  4387. source_position: typing.Optional[Position] = None,
  4388. target_position: typing.Optional[Position] = None,
  4389. force: typing.Optional[bool] = None,
  4390. no_wait_after: typing.Optional[bool] = None,
  4391. strict: typing.Optional[bool] = None,
  4392. timeout: typing.Optional[float] = None,
  4393. trial: typing.Optional[bool] = None,
  4394. steps: typing.Optional[int] = None,
  4395. ) -> None:
  4396. """Frame.drag_and_drop
  4397. Parameters
  4398. ----------
  4399. source : str
  4400. A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
  4401. be used.
  4402. target : str
  4403. A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
  4404. will be used.
  4405. source_position : Union[{x: float, y: float}, None]
  4406. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  4407. specified, some visible point of the element is used.
  4408. target_position : Union[{x: float, y: float}, None]
  4409. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  4410. specified, some visible point of the element is used.
  4411. force : Union[bool, None]
  4412. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4413. no_wait_after : Union[bool, None]
  4414. This option has no effect.
  4415. Deprecated: This option has no effect.
  4416. strict : Union[bool, None]
  4417. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4418. element, the call throws an exception.
  4419. timeout : Union[float, None]
  4420. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4421. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4422. trial : Union[bool, None]
  4423. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4424. to `false`. Useful to wait until the element is ready for the action without performing it.
  4425. steps : Union[int, None]
  4426. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  4427. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  4428. """
  4429. return mapping.from_maybe_impl(
  4430. self._sync(
  4431. self._impl_obj.drag_and_drop(
  4432. source=source,
  4433. target=target,
  4434. sourcePosition=source_position,
  4435. targetPosition=target_position,
  4436. force=force,
  4437. noWaitAfter=no_wait_after,
  4438. strict=strict,
  4439. timeout=timeout,
  4440. trial=trial,
  4441. steps=steps,
  4442. )
  4443. )
  4444. )
  4445. def select_option(
  4446. self,
  4447. selector: str,
  4448. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  4449. *,
  4450. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  4451. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  4452. element: typing.Optional[
  4453. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  4454. ] = None,
  4455. timeout: typing.Optional[float] = None,
  4456. no_wait_after: typing.Optional[bool] = None,
  4457. strict: typing.Optional[bool] = None,
  4458. force: typing.Optional[bool] = None,
  4459. ) -> typing.List[str]:
  4460. """Frame.select_option
  4461. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
  4462. until all specified options are present in the `<select>` element and selects these options.
  4463. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  4464. the `<label>` element that has an associated
  4465. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  4466. instead.
  4467. Returns the array of option values that have been successfully selected.
  4468. Triggers a `change` and `input` event once all the provided options have been selected.
  4469. **Usage**
  4470. ```py
  4471. # Single selection matching the value or label
  4472. frame.select_option(\"select#colors\", \"blue\")
  4473. # single selection matching both the label
  4474. frame.select_option(\"select#colors\", label=\"blue\")
  4475. # multiple selection
  4476. frame.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
  4477. ```
  4478. Parameters
  4479. ----------
  4480. selector : str
  4481. A selector to query for.
  4482. value : Union[Sequence[str], str, None]
  4483. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  4484. otherwise only the first option matching one of the passed options is selected. Optional.
  4485. index : Union[Sequence[int], int, None]
  4486. Options to select by index. Optional.
  4487. label : Union[Sequence[str], str, None]
  4488. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  4489. otherwise only the first option matching one of the passed options is selected. Optional.
  4490. element : Union[ElementHandle, Sequence[ElementHandle], None]
  4491. Option elements to select. Optional.
  4492. timeout : Union[float, None]
  4493. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4494. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4495. no_wait_after : Union[bool, None]
  4496. This option has no effect.
  4497. Deprecated: This option has no effect.
  4498. strict : Union[bool, None]
  4499. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4500. element, the call throws an exception.
  4501. force : Union[bool, None]
  4502. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4503. Returns
  4504. -------
  4505. List[str]
  4506. """
  4507. return mapping.from_maybe_impl(
  4508. self._sync(
  4509. self._impl_obj.select_option(
  4510. selector=selector,
  4511. value=mapping.to_impl(value),
  4512. index=mapping.to_impl(index),
  4513. label=mapping.to_impl(label),
  4514. element=mapping.to_impl(element),
  4515. timeout=timeout,
  4516. noWaitAfter=no_wait_after,
  4517. strict=strict,
  4518. force=force,
  4519. )
  4520. )
  4521. )
  4522. def input_value(
  4523. self,
  4524. selector: str,
  4525. *,
  4526. strict: typing.Optional[bool] = None,
  4527. timeout: typing.Optional[float] = None,
  4528. ) -> str:
  4529. """Frame.input_value
  4530. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  4531. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  4532. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  4533. control.
  4534. Parameters
  4535. ----------
  4536. selector : str
  4537. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4538. used.
  4539. strict : Union[bool, None]
  4540. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4541. element, the call throws an exception.
  4542. timeout : Union[float, None]
  4543. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4544. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4545. Returns
  4546. -------
  4547. str
  4548. """
  4549. return mapping.from_maybe_impl(
  4550. self._sync(
  4551. self._impl_obj.input_value(
  4552. selector=selector, strict=strict, timeout=timeout
  4553. )
  4554. )
  4555. )
  4556. def set_input_files(
  4557. self,
  4558. selector: str,
  4559. files: typing.Union[
  4560. str,
  4561. pathlib.Path,
  4562. FilePayload,
  4563. typing.Sequence[typing.Union[str, pathlib.Path]],
  4564. typing.Sequence[FilePayload],
  4565. ],
  4566. *,
  4567. strict: typing.Optional[bool] = None,
  4568. timeout: typing.Optional[float] = None,
  4569. no_wait_after: typing.Optional[bool] = None,
  4570. ) -> None:
  4571. """Frame.set_input_files
  4572. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  4573. they are resolved relative to the current working directory. For empty array, clears the selected files.
  4574. This method expects `selector` to point to an
  4575. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  4576. the `<label>` element that has an associated
  4577. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  4578. Parameters
  4579. ----------
  4580. selector : str
  4581. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4582. used.
  4583. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  4584. strict : Union[bool, None]
  4585. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4586. element, the call throws an exception.
  4587. timeout : Union[float, None]
  4588. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4589. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4590. no_wait_after : Union[bool, None]
  4591. This option has no effect.
  4592. Deprecated: This option has no effect.
  4593. """
  4594. return mapping.from_maybe_impl(
  4595. self._sync(
  4596. self._impl_obj.set_input_files(
  4597. selector=selector,
  4598. files=mapping.to_impl(files),
  4599. strict=strict,
  4600. timeout=timeout,
  4601. noWaitAfter=no_wait_after,
  4602. )
  4603. )
  4604. )
  4605. def type(
  4606. self,
  4607. selector: str,
  4608. text: str,
  4609. *,
  4610. delay: typing.Optional[float] = None,
  4611. strict: typing.Optional[bool] = None,
  4612. timeout: typing.Optional[float] = None,
  4613. no_wait_after: typing.Optional[bool] = None,
  4614. ) -> None:
  4615. """Frame.type
  4616. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used
  4617. to send fine-grained keyboard events. To fill values in form fields, use `frame.fill()`.
  4618. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  4619. **Usage**
  4620. Parameters
  4621. ----------
  4622. selector : str
  4623. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4624. used.
  4625. text : str
  4626. A text to type into a focused element.
  4627. delay : Union[float, None]
  4628. Time to wait between key presses in milliseconds. Defaults to 0.
  4629. strict : Union[bool, None]
  4630. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4631. element, the call throws an exception.
  4632. timeout : Union[float, None]
  4633. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4634. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4635. no_wait_after : Union[bool, None]
  4636. This option has no effect.
  4637. Deprecated: This option has no effect.
  4638. """
  4639. return mapping.from_maybe_impl(
  4640. self._sync(
  4641. self._impl_obj.type(
  4642. selector=selector,
  4643. text=text,
  4644. delay=delay,
  4645. strict=strict,
  4646. timeout=timeout,
  4647. noWaitAfter=no_wait_after,
  4648. )
  4649. )
  4650. )
  4651. def press(
  4652. self,
  4653. selector: str,
  4654. key: str,
  4655. *,
  4656. delay: typing.Optional[float] = None,
  4657. strict: typing.Optional[bool] = None,
  4658. timeout: typing.Optional[float] = None,
  4659. no_wait_after: typing.Optional[bool] = None,
  4660. ) -> None:
  4661. """Frame.press
  4662. `key` can specify the intended
  4663. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  4664. to generate the text for. A superset of the `key` values can be found
  4665. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  4666. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  4667. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  4668. etc.
  4669. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  4670. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  4671. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  4672. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  4673. texts.
  4674. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  4675. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  4676. Parameters
  4677. ----------
  4678. selector : str
  4679. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4680. used.
  4681. key : str
  4682. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  4683. delay : Union[float, None]
  4684. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  4685. strict : Union[bool, None]
  4686. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4687. element, the call throws an exception.
  4688. timeout : Union[float, None]
  4689. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4690. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4691. no_wait_after : Union[bool, None]
  4692. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  4693. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  4694. navigating to inaccessible pages. Defaults to `false`.
  4695. Deprecated: This option will default to `true` in the future.
  4696. """
  4697. return mapping.from_maybe_impl(
  4698. self._sync(
  4699. self._impl_obj.press(
  4700. selector=selector,
  4701. key=key,
  4702. delay=delay,
  4703. strict=strict,
  4704. timeout=timeout,
  4705. noWaitAfter=no_wait_after,
  4706. )
  4707. )
  4708. )
  4709. def check(
  4710. self,
  4711. selector: str,
  4712. *,
  4713. position: typing.Optional[Position] = None,
  4714. timeout: typing.Optional[float] = None,
  4715. force: typing.Optional[bool] = None,
  4716. no_wait_after: typing.Optional[bool] = None,
  4717. strict: typing.Optional[bool] = None,
  4718. trial: typing.Optional[bool] = None,
  4719. ) -> None:
  4720. """Frame.check
  4721. This method checks an element matching `selector` by performing the following steps:
  4722. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4723. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  4724. already checked, this method returns immediately.
  4725. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4726. the element is detached during the checks, the whole action is retried.
  4727. 1. Scroll the element into view if needed.
  4728. 1. Use `page.mouse` to click in the center of the element.
  4729. 1. Ensure that the element is now checked. If not, this method throws.
  4730. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4731. Passing zero timeout disables this.
  4732. Parameters
  4733. ----------
  4734. selector : str
  4735. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4736. used.
  4737. position : Union[{x: float, y: float}, None]
  4738. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4739. the element.
  4740. timeout : Union[float, None]
  4741. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4742. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4743. force : Union[bool, None]
  4744. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4745. no_wait_after : Union[bool, None]
  4746. This option has no effect.
  4747. Deprecated: This option has no effect.
  4748. strict : Union[bool, None]
  4749. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4750. element, the call throws an exception.
  4751. trial : Union[bool, None]
  4752. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4753. to `false`. Useful to wait until the element is ready for the action without performing it.
  4754. """
  4755. return mapping.from_maybe_impl(
  4756. self._sync(
  4757. self._impl_obj.check(
  4758. selector=selector,
  4759. position=position,
  4760. timeout=timeout,
  4761. force=force,
  4762. noWaitAfter=no_wait_after,
  4763. strict=strict,
  4764. trial=trial,
  4765. )
  4766. )
  4767. )
  4768. def uncheck(
  4769. self,
  4770. selector: str,
  4771. *,
  4772. position: typing.Optional[Position] = None,
  4773. timeout: typing.Optional[float] = None,
  4774. force: typing.Optional[bool] = None,
  4775. no_wait_after: typing.Optional[bool] = None,
  4776. strict: typing.Optional[bool] = None,
  4777. trial: typing.Optional[bool] = None,
  4778. ) -> None:
  4779. """Frame.uncheck
  4780. This method checks an element matching `selector` by performing the following steps:
  4781. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4782. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  4783. already unchecked, this method returns immediately.
  4784. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4785. the element is detached during the checks, the whole action is retried.
  4786. 1. Scroll the element into view if needed.
  4787. 1. Use `page.mouse` to click in the center of the element.
  4788. 1. Ensure that the element is now unchecked. If not, this method throws.
  4789. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4790. Passing zero timeout disables this.
  4791. Parameters
  4792. ----------
  4793. selector : str
  4794. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4795. used.
  4796. position : Union[{x: float, y: float}, None]
  4797. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4798. the element.
  4799. timeout : Union[float, None]
  4800. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4801. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4802. force : Union[bool, None]
  4803. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4804. no_wait_after : Union[bool, None]
  4805. This option has no effect.
  4806. Deprecated: This option has no effect.
  4807. strict : Union[bool, None]
  4808. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4809. element, the call throws an exception.
  4810. trial : Union[bool, None]
  4811. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4812. to `false`. Useful to wait until the element is ready for the action without performing it.
  4813. """
  4814. return mapping.from_maybe_impl(
  4815. self._sync(
  4816. self._impl_obj.uncheck(
  4817. selector=selector,
  4818. position=position,
  4819. timeout=timeout,
  4820. force=force,
  4821. noWaitAfter=no_wait_after,
  4822. strict=strict,
  4823. trial=trial,
  4824. )
  4825. )
  4826. )
  4827. def wait_for_timeout(self, timeout: float) -> None:
  4828. """Frame.wait_for_timeout
  4829. Waits for the given `timeout` in milliseconds.
  4830. Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
  4831. to be flaky. Use signals such as network events, selectors becoming visible and others instead.
  4832. Parameters
  4833. ----------
  4834. timeout : float
  4835. A timeout to wait for
  4836. """
  4837. return mapping.from_maybe_impl(
  4838. self._sync(self._impl_obj.wait_for_timeout(timeout=timeout))
  4839. )
  4840. def wait_for_function(
  4841. self,
  4842. expression: str,
  4843. *,
  4844. arg: typing.Optional[typing.Any] = None,
  4845. timeout: typing.Optional[float] = None,
  4846. polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
  4847. ) -> "JSHandle":
  4848. """Frame.wait_for_function
  4849. Returns when the `expression` returns a truthy value, returns that value.
  4850. **Usage**
  4851. The `frame.wait_for_function()` can be used to observe viewport size change:
  4852. ```py
  4853. from playwright.sync_api import sync_playwright, Playwright
  4854. def run(playwright: Playwright):
  4855. webkit = playwright.webkit
  4856. browser = webkit.launch()
  4857. page = browser.new_page()
  4858. page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
  4859. page.main_frame.wait_for_function(\"() => window.x > 0\")
  4860. browser.close()
  4861. with sync_playwright() as playwright:
  4862. run(playwright)
  4863. ```
  4864. To pass an argument to the predicate of `frame.waitForFunction` function:
  4865. ```py
  4866. selector = \".foo\"
  4867. frame.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
  4868. ```
  4869. Parameters
  4870. ----------
  4871. expression : str
  4872. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  4873. function is automatically invoked.
  4874. arg : Union[Any, None]
  4875. Optional argument to pass to `expression`.
  4876. timeout : Union[float, None]
  4877. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  4878. default value can be changed by using the `browser_context.set_default_timeout()` or
  4879. `page.set_default_timeout()` methods.
  4880. polling : Union["raf", float, None]
  4881. If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
  4882. is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
  4883. `raf`.
  4884. Returns
  4885. -------
  4886. JSHandle
  4887. """
  4888. return mapping.from_impl(
  4889. self._sync(
  4890. self._impl_obj.wait_for_function(
  4891. expression=expression,
  4892. arg=mapping.to_impl(arg),
  4893. timeout=timeout,
  4894. polling=polling,
  4895. )
  4896. )
  4897. )
  4898. def title(self) -> str:
  4899. """Frame.title
  4900. Returns the page title.
  4901. Returns
  4902. -------
  4903. str
  4904. """
  4905. return mapping.from_maybe_impl(self._sync(self._impl_obj.title()))
  4906. def set_checked(
  4907. self,
  4908. selector: str,
  4909. checked: bool,
  4910. *,
  4911. position: typing.Optional[Position] = None,
  4912. timeout: typing.Optional[float] = None,
  4913. force: typing.Optional[bool] = None,
  4914. no_wait_after: typing.Optional[bool] = None,
  4915. strict: typing.Optional[bool] = None,
  4916. trial: typing.Optional[bool] = None,
  4917. ) -> None:
  4918. """Frame.set_checked
  4919. This method checks or unchecks an element matching `selector` by performing the following steps:
  4920. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4921. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  4922. 1. If the element already has the right checked state, this method returns immediately.
  4923. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4924. the element is detached during the checks, the whole action is retried.
  4925. 1. Scroll the element into view if needed.
  4926. 1. Use `page.mouse` to click in the center of the element.
  4927. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  4928. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4929. Passing zero timeout disables this.
  4930. Parameters
  4931. ----------
  4932. selector : str
  4933. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4934. used.
  4935. checked : bool
  4936. Whether to check or uncheck the checkbox.
  4937. position : Union[{x: float, y: float}, None]
  4938. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4939. the element.
  4940. timeout : Union[float, None]
  4941. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4942. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4943. force : Union[bool, None]
  4944. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4945. no_wait_after : Union[bool, None]
  4946. This option has no effect.
  4947. Deprecated: This option has no effect.
  4948. strict : Union[bool, None]
  4949. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4950. element, the call throws an exception.
  4951. trial : Union[bool, None]
  4952. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4953. to `false`. Useful to wait until the element is ready for the action without performing it.
  4954. """
  4955. return mapping.from_maybe_impl(
  4956. self._sync(
  4957. self._impl_obj.set_checked(
  4958. selector=selector,
  4959. checked=checked,
  4960. position=position,
  4961. timeout=timeout,
  4962. force=force,
  4963. noWaitAfter=no_wait_after,
  4964. strict=strict,
  4965. trial=trial,
  4966. )
  4967. )
  4968. )
  4969. mapping.register(FrameImpl, Frame)
  4970. class FrameLocator(SyncBase):
  4971. @property
  4972. def first(self) -> "FrameLocator":
  4973. """FrameLocator.first
  4974. Returns locator to the first matching frame.
  4975. Returns
  4976. -------
  4977. FrameLocator
  4978. """
  4979. return mapping.from_impl(self._impl_obj.first)
  4980. @property
  4981. def last(self) -> "FrameLocator":
  4982. """FrameLocator.last
  4983. Returns locator to the last matching frame.
  4984. Returns
  4985. -------
  4986. FrameLocator
  4987. """
  4988. return mapping.from_impl(self._impl_obj.last)
  4989. @property
  4990. def owner(self) -> "Locator":
  4991. """FrameLocator.owner
  4992. Returns a `Locator` object pointing to the same `iframe` as this frame locator.
  4993. Useful when you have a `FrameLocator` object obtained somewhere, and later on would like to interact with the
  4994. `iframe` element.
  4995. For a reverse operation, use `locator.content_frame()`.
  4996. **Usage**
  4997. ```py
  4998. frame_locator = page.locator(\"iframe[name=\\\"embedded\\\"]\").content_frame
  4999. # ...
  5000. locator = frame_locator.owner
  5001. expect(locator).to_be_visible()
  5002. ```
  5003. Returns
  5004. -------
  5005. Locator
  5006. """
  5007. return mapping.from_impl(self._impl_obj.owner)
  5008. def locator(
  5009. self,
  5010. selector_or_locator: typing.Union["Locator", str],
  5011. *,
  5012. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5013. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5014. has: typing.Optional["Locator"] = None,
  5015. has_not: typing.Optional["Locator"] = None,
  5016. ) -> "Locator":
  5017. """FrameLocator.locator
  5018. The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
  5019. options, similar to `locator.filter()` method.
  5020. [Learn more about locators](https://playwright.dev/python/docs/locators).
  5021. Parameters
  5022. ----------
  5023. selector_or_locator : Union[Locator, str]
  5024. A selector or locator to use when resolving DOM element.
  5025. has_text : Union[Pattern[str], str, None]
  5026. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  5027. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  5028. `<article><div>Playwright</div></article>`.
  5029. has_not_text : Union[Pattern[str], str, None]
  5030. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  5031. When passed a [string], matching is case-insensitive and searches for a substring.
  5032. has : Union[Locator, None]
  5033. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  5034. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  5035. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  5036. the document root. For example, you can find `content` that has `div` in
  5037. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  5038. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  5039. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  5040. has_not : Union[Locator, None]
  5041. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  5042. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  5043. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  5044. Returns
  5045. -------
  5046. Locator
  5047. """
  5048. return mapping.from_impl(
  5049. self._impl_obj.locator(
  5050. selectorOrLocator=selector_or_locator,
  5051. hasText=has_text,
  5052. hasNotText=has_not_text,
  5053. has=has._impl_obj if has else None,
  5054. hasNot=has_not._impl_obj if has_not else None,
  5055. )
  5056. )
  5057. def get_by_alt_text(
  5058. self,
  5059. text: typing.Union[str, typing.Pattern[str]],
  5060. *,
  5061. exact: typing.Optional[bool] = None,
  5062. ) -> "Locator":
  5063. """FrameLocator.get_by_alt_text
  5064. Allows locating elements by their alt text.
  5065. **Usage**
  5066. For example, this method will find the image by alt text \"Playwright logo\":
  5067. ```html
  5068. <img alt='Playwright logo'>
  5069. ```
  5070. ```py
  5071. page.get_by_alt_text(\"Playwright logo\").click()
  5072. ```
  5073. Parameters
  5074. ----------
  5075. text : Union[Pattern[str], str]
  5076. Text to locate the element for.
  5077. exact : Union[bool, None]
  5078. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5079. regular expression. Note that exact match still trims whitespace.
  5080. Returns
  5081. -------
  5082. Locator
  5083. """
  5084. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  5085. def get_by_label(
  5086. self,
  5087. text: typing.Union[str, typing.Pattern[str]],
  5088. *,
  5089. exact: typing.Optional[bool] = None,
  5090. ) -> "Locator":
  5091. """FrameLocator.get_by_label
  5092. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  5093. `aria-label` attribute.
  5094. **Usage**
  5095. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  5096. ```html
  5097. <input aria-label=\"Username\">
  5098. <label for=\"password-input\">Password:</label>
  5099. <input id=\"password-input\">
  5100. ```
  5101. ```py
  5102. page.get_by_label(\"Username\").fill(\"john\")
  5103. page.get_by_label(\"Password\").fill(\"secret\")
  5104. ```
  5105. Parameters
  5106. ----------
  5107. text : Union[Pattern[str], str]
  5108. Text to locate the element for.
  5109. exact : Union[bool, None]
  5110. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5111. regular expression. Note that exact match still trims whitespace.
  5112. Returns
  5113. -------
  5114. Locator
  5115. """
  5116. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  5117. def get_by_placeholder(
  5118. self,
  5119. text: typing.Union[str, typing.Pattern[str]],
  5120. *,
  5121. exact: typing.Optional[bool] = None,
  5122. ) -> "Locator":
  5123. """FrameLocator.get_by_placeholder
  5124. Allows locating input elements by the placeholder text.
  5125. **Usage**
  5126. For example, consider the following DOM structure.
  5127. ```html
  5128. <input type=\"email\" placeholder=\"name@example.com\" />
  5129. ```
  5130. You can fill the input after locating it by the placeholder text:
  5131. ```py
  5132. page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  5133. ```
  5134. Parameters
  5135. ----------
  5136. text : Union[Pattern[str], str]
  5137. Text to locate the element for.
  5138. exact : Union[bool, None]
  5139. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5140. regular expression. Note that exact match still trims whitespace.
  5141. Returns
  5142. -------
  5143. Locator
  5144. """
  5145. return mapping.from_impl(
  5146. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  5147. )
  5148. def get_by_role(
  5149. self,
  5150. role: Literal[
  5151. "alert",
  5152. "alertdialog",
  5153. "application",
  5154. "article",
  5155. "banner",
  5156. "blockquote",
  5157. "button",
  5158. "caption",
  5159. "cell",
  5160. "checkbox",
  5161. "code",
  5162. "columnheader",
  5163. "combobox",
  5164. "complementary",
  5165. "contentinfo",
  5166. "definition",
  5167. "deletion",
  5168. "dialog",
  5169. "directory",
  5170. "document",
  5171. "emphasis",
  5172. "feed",
  5173. "figure",
  5174. "form",
  5175. "generic",
  5176. "grid",
  5177. "gridcell",
  5178. "group",
  5179. "heading",
  5180. "img",
  5181. "insertion",
  5182. "link",
  5183. "list",
  5184. "listbox",
  5185. "listitem",
  5186. "log",
  5187. "main",
  5188. "marquee",
  5189. "math",
  5190. "menu",
  5191. "menubar",
  5192. "menuitem",
  5193. "menuitemcheckbox",
  5194. "menuitemradio",
  5195. "meter",
  5196. "navigation",
  5197. "none",
  5198. "note",
  5199. "option",
  5200. "paragraph",
  5201. "presentation",
  5202. "progressbar",
  5203. "radio",
  5204. "radiogroup",
  5205. "region",
  5206. "row",
  5207. "rowgroup",
  5208. "rowheader",
  5209. "scrollbar",
  5210. "search",
  5211. "searchbox",
  5212. "separator",
  5213. "slider",
  5214. "spinbutton",
  5215. "status",
  5216. "strong",
  5217. "subscript",
  5218. "superscript",
  5219. "switch",
  5220. "tab",
  5221. "table",
  5222. "tablist",
  5223. "tabpanel",
  5224. "term",
  5225. "textbox",
  5226. "time",
  5227. "timer",
  5228. "toolbar",
  5229. "tooltip",
  5230. "tree",
  5231. "treegrid",
  5232. "treeitem",
  5233. ],
  5234. *,
  5235. checked: typing.Optional[bool] = None,
  5236. disabled: typing.Optional[bool] = None,
  5237. expanded: typing.Optional[bool] = None,
  5238. include_hidden: typing.Optional[bool] = None,
  5239. level: typing.Optional[int] = None,
  5240. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5241. pressed: typing.Optional[bool] = None,
  5242. selected: typing.Optional[bool] = None,
  5243. exact: typing.Optional[bool] = None,
  5244. ) -> "Locator":
  5245. """FrameLocator.get_by_role
  5246. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  5247. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  5248. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  5249. **Usage**
  5250. Consider the following DOM structure.
  5251. ```html
  5252. <h3>Sign up</h3>
  5253. <label>
  5254. <input type=\"checkbox\" /> Subscribe
  5255. </label>
  5256. <br/>
  5257. <button>Submit</button>
  5258. ```
  5259. You can locate each element by it's implicit role:
  5260. ```py
  5261. expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  5262. page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  5263. page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  5264. ```
  5265. **Details**
  5266. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  5267. about the ARIA guidelines.
  5268. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  5269. that is recognized by the role selector. You can find all the
  5270. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  5271. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  5272. Parameters
  5273. ----------
  5274. role : Union["alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"]
  5275. Required aria role.
  5276. checked : Union[bool, None]
  5277. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  5278. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  5279. disabled : Union[bool, None]
  5280. An attribute that is usually set by `aria-disabled` or `disabled`.
  5281. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  5282. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  5283. expanded : Union[bool, None]
  5284. An attribute that is usually set by `aria-expanded`.
  5285. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  5286. include_hidden : Union[bool, None]
  5287. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  5288. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  5289. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  5290. level : Union[int, None]
  5291. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  5292. for `<h1>-<h6>` elements.
  5293. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  5294. name : Union[Pattern[str], str, None]
  5295. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  5296. case-insensitive and searches for a substring, use `exact` to control this behavior.
  5297. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  5298. pressed : Union[bool, None]
  5299. An attribute that is usually set by `aria-pressed`.
  5300. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  5301. selected : Union[bool, None]
  5302. An attribute that is usually set by `aria-selected`.
  5303. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  5304. exact : Union[bool, None]
  5305. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  5306. regular expression. Note that exact match still trims whitespace.
  5307. Returns
  5308. -------
  5309. Locator
  5310. """
  5311. return mapping.from_impl(
  5312. self._impl_obj.get_by_role(
  5313. role=role,
  5314. checked=checked,
  5315. disabled=disabled,
  5316. expanded=expanded,
  5317. includeHidden=include_hidden,
  5318. level=level,
  5319. name=name,
  5320. pressed=pressed,
  5321. selected=selected,
  5322. exact=exact,
  5323. )
  5324. )
  5325. def get_by_test_id(
  5326. self, test_id: typing.Union[str, typing.Pattern[str]]
  5327. ) -> "Locator":
  5328. """FrameLocator.get_by_test_id
  5329. Locate element by the test id.
  5330. **Usage**
  5331. Consider the following DOM structure.
  5332. ```html
  5333. <button data-testid=\"directions\">Itinéraire</button>
  5334. ```
  5335. You can locate the element by it's test id:
  5336. ```py
  5337. page.get_by_test_id(\"directions\").click()
  5338. ```
  5339. **Details**
  5340. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  5341. configure a different test id attribute if necessary.
  5342. Parameters
  5343. ----------
  5344. test_id : Union[Pattern[str], str]
  5345. Id to locate the element by.
  5346. Returns
  5347. -------
  5348. Locator
  5349. """
  5350. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  5351. def get_by_text(
  5352. self,
  5353. text: typing.Union[str, typing.Pattern[str]],
  5354. *,
  5355. exact: typing.Optional[bool] = None,
  5356. ) -> "Locator":
  5357. """FrameLocator.get_by_text
  5358. Allows locating elements that contain given text.
  5359. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  5360. filter by the text content.
  5361. **Usage**
  5362. Consider the following DOM structure:
  5363. ```html
  5364. <div>Hello <span>world</span></div>
  5365. <div>Hello</div>
  5366. ```
  5367. You can locate by text substring, exact string, or a regular expression:
  5368. ```py
  5369. # Matches <span>
  5370. page.get_by_text(\"world\")
  5371. # Matches first <div>
  5372. page.get_by_text(\"Hello world\")
  5373. # Matches second <div>
  5374. page.get_by_text(\"Hello\", exact=True)
  5375. # Matches both <div>s
  5376. page.get_by_text(re.compile(\"Hello\"))
  5377. # Matches second <div>
  5378. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  5379. ```
  5380. **Details**
  5381. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  5382. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  5383. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  5384. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  5385. Parameters
  5386. ----------
  5387. text : Union[Pattern[str], str]
  5388. Text to locate the element for.
  5389. exact : Union[bool, None]
  5390. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5391. regular expression. Note that exact match still trims whitespace.
  5392. Returns
  5393. -------
  5394. Locator
  5395. """
  5396. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  5397. def get_by_title(
  5398. self,
  5399. text: typing.Union[str, typing.Pattern[str]],
  5400. *,
  5401. exact: typing.Optional[bool] = None,
  5402. ) -> "Locator":
  5403. """FrameLocator.get_by_title
  5404. Allows locating elements by their title attribute.
  5405. **Usage**
  5406. Consider the following DOM structure.
  5407. ```html
  5408. <span title='Issues count'>25 issues</span>
  5409. ```
  5410. You can check the issues count after locating it by the title text:
  5411. ```py
  5412. expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  5413. ```
  5414. Parameters
  5415. ----------
  5416. text : Union[Pattern[str], str]
  5417. Text to locate the element for.
  5418. exact : Union[bool, None]
  5419. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5420. regular expression. Note that exact match still trims whitespace.
  5421. Returns
  5422. -------
  5423. Locator
  5424. """
  5425. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  5426. def frame_locator(self, selector: str) -> "FrameLocator":
  5427. """FrameLocator.frame_locator
  5428. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  5429. in that iframe.
  5430. Parameters
  5431. ----------
  5432. selector : str
  5433. A selector to use when resolving DOM element.
  5434. Returns
  5435. -------
  5436. FrameLocator
  5437. """
  5438. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  5439. def nth(self, index: int) -> "FrameLocator":
  5440. """FrameLocator.nth
  5441. Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.
  5442. Parameters
  5443. ----------
  5444. index : int
  5445. Returns
  5446. -------
  5447. FrameLocator
  5448. """
  5449. return mapping.from_impl(self._impl_obj.nth(index=index))
  5450. mapping.register(FrameLocatorImpl, FrameLocator)
  5451. class Worker(SyncBase):
  5452. @typing.overload
  5453. def on(
  5454. self, event: Literal["close"], f: typing.Callable[["Worker"], "None"]
  5455. ) -> None:
  5456. """
  5457. Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
  5458. terminated."""
  5459. @typing.overload
  5460. def on(
  5461. self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
  5462. ) -> None:
  5463. """
  5464. Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
  5465. """
  5466. def on(self, event: str, f: typing.Callable[..., None]) -> None:
  5467. return super().on(event=event, f=f)
  5468. @typing.overload
  5469. def once(
  5470. self, event: Literal["close"], f: typing.Callable[["Worker"], "None"]
  5471. ) -> None:
  5472. """
  5473. Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
  5474. terminated."""
  5475. @typing.overload
  5476. def once(
  5477. self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
  5478. ) -> None:
  5479. """
  5480. Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
  5481. """
  5482. def once(self, event: str, f: typing.Callable[..., None]) -> None:
  5483. return super().once(event=event, f=f)
  5484. @property
  5485. def url(self) -> str:
  5486. """Worker.url
  5487. Returns
  5488. -------
  5489. str
  5490. """
  5491. return mapping.from_maybe_impl(self._impl_obj.url)
  5492. def evaluate(
  5493. self, expression: str, arg: typing.Optional[typing.Any] = None
  5494. ) -> typing.Any:
  5495. """Worker.evaluate
  5496. Returns the return value of `expression`.
  5497. If the function passed to the `worker.evaluate()` returns a [Promise], then `worker.evaluate()`
  5498. would wait for the promise to resolve and return its value.
  5499. If the function passed to the `worker.evaluate()` returns a non-[Serializable] value, then
  5500. `worker.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
  5501. are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  5502. Parameters
  5503. ----------
  5504. expression : str
  5505. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  5506. function is automatically invoked.
  5507. arg : Union[Any, None]
  5508. Optional argument to pass to `expression`.
  5509. Returns
  5510. -------
  5511. Any
  5512. """
  5513. return mapping.from_maybe_impl(
  5514. self._sync(
  5515. self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
  5516. )
  5517. )
  5518. def evaluate_handle(
  5519. self, expression: str, arg: typing.Optional[typing.Any] = None
  5520. ) -> "JSHandle":
  5521. """Worker.evaluate_handle
  5522. Returns the return value of `expression` as a `JSHandle`.
  5523. The only difference between `worker.evaluate()` and `worker.evaluate_handle()` is that
  5524. `worker.evaluate_handle()` returns `JSHandle`.
  5525. If the function passed to the `worker.evaluate_handle()` returns a [Promise], then
  5526. `worker.evaluate_handle()` would wait for the promise to resolve and return its value.
  5527. Parameters
  5528. ----------
  5529. expression : str
  5530. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  5531. function is automatically invoked.
  5532. arg : Union[Any, None]
  5533. Optional argument to pass to `expression`.
  5534. Returns
  5535. -------
  5536. JSHandle
  5537. """
  5538. return mapping.from_impl(
  5539. self._sync(
  5540. self._impl_obj.evaluate_handle(
  5541. expression=expression, arg=mapping.to_impl(arg)
  5542. )
  5543. )
  5544. )
  5545. def expect_event(
  5546. self,
  5547. event: str,
  5548. predicate: typing.Optional[typing.Callable] = None,
  5549. *,
  5550. timeout: typing.Optional[float] = None,
  5551. ) -> EventContextManager:
  5552. """Worker.expect_event
  5553. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  5554. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
  5555. **Usage**
  5556. ```py
  5557. with worker.expect_event(\"console\") as event_info:
  5558. worker.evaluate(\"console.log(42)\")
  5559. message = event_info.value
  5560. ```
  5561. Parameters
  5562. ----------
  5563. event : str
  5564. Event name, same one typically passed into `*.on(event)`.
  5565. predicate : Union[Callable, None]
  5566. Receives the event data and resolves to truthy value when the waiting should resolve.
  5567. timeout : Union[float, None]
  5568. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  5569. default value can be changed by using the `browser_context.set_default_timeout()`.
  5570. Returns
  5571. -------
  5572. EventContextManager
  5573. """
  5574. return EventContextManager(
  5575. self,
  5576. self._impl_obj.expect_event(
  5577. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  5578. ).future,
  5579. )
  5580. mapping.register(WorkerImpl, Worker)
  5581. class Selectors(SyncBase):
  5582. def register(
  5583. self,
  5584. name: str,
  5585. script: typing.Optional[str] = None,
  5586. *,
  5587. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  5588. content_script: typing.Optional[bool] = None,
  5589. ) -> None:
  5590. """Selectors.register
  5591. Selectors must be registered before creating the page.
  5592. **Usage**
  5593. An example of registering selector engine that queries elements based on a tag name:
  5594. ```py
  5595. from playwright.sync_api import sync_playwright, Playwright
  5596. def run(playwright: Playwright):
  5597. tag_selector = \"\"\"
  5598. {
  5599. // Returns the first element matching given selector in the root's subtree.
  5600. query(root, selector) {
  5601. return root.querySelector(selector);
  5602. },
  5603. // Returns all elements matching given selector in the root's subtree.
  5604. queryAll(root, selector) {
  5605. return Array.from(root.querySelectorAll(selector));
  5606. }
  5607. }\"\"\"
  5608. # Register the engine. Selectors will be prefixed with \"tag=\".
  5609. playwright.selectors.register(\"tag\", tag_selector)
  5610. browser = playwright.chromium.launch()
  5611. page = browser.new_page()
  5612. page.set_content('<div><button>Click me</button></div>')
  5613. # Use the selector prefixed with its name.
  5614. button = page.locator('tag=button')
  5615. # Combine it with built-in locators.
  5616. page.locator('tag=div').get_by_text('Click me').click()
  5617. # Can use it in any methods supporting selectors.
  5618. button_count = page.locator('tag=button').count()
  5619. print(button_count)
  5620. browser.close()
  5621. with sync_playwright() as playwright:
  5622. run(playwright)
  5623. ```
  5624. Parameters
  5625. ----------
  5626. name : str
  5627. Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only
  5628. contain `[a-zA-Z0-9_]` characters.
  5629. script : Union[str, None]
  5630. Raw script content.
  5631. path : Union[pathlib.Path, str, None]
  5632. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  5633. directory.
  5634. content_script : Union[bool, None]
  5635. Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same
  5636. DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content
  5637. script is not guaranteed when this engine is used together with other registered engines.
  5638. """
  5639. return mapping.from_maybe_impl(
  5640. self._sync(
  5641. self._impl_obj.register(
  5642. name=name, script=script, path=path, contentScript=content_script
  5643. )
  5644. )
  5645. )
  5646. def set_test_id_attribute(self, attribute_name: str) -> None:
  5647. """Selectors.set_test_id_attribute
  5648. Defines custom attribute name to be used in `page.get_by_test_id()`. `data-testid` is used by default.
  5649. Parameters
  5650. ----------
  5651. attribute_name : str
  5652. Test id attribute name.
  5653. """
  5654. return mapping.from_maybe_impl(
  5655. self._impl_obj.set_test_id_attribute(attributeName=attribute_name)
  5656. )
  5657. mapping.register(SelectorsImpl, Selectors)
  5658. class Clock(SyncBase):
  5659. def install(
  5660. self,
  5661. *,
  5662. time: typing.Optional[typing.Union[float, str, datetime.datetime]] = None,
  5663. ) -> None:
  5664. """Clock.install
  5665. Install fake implementations for the following time-related functions:
  5666. - `Date`
  5667. - `setTimeout`
  5668. - `clearTimeout`
  5669. - `setInterval`
  5670. - `clearInterval`
  5671. - `requestAnimationFrame`
  5672. - `cancelAnimationFrame`
  5673. - `requestIdleCallback`
  5674. - `cancelIdleCallback`
  5675. - `performance`
  5676. Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,
  5677. and control the behavior of time-dependent functions. See `clock.run_for()` and
  5678. `clock.fast_forward()` for more information.
  5679. Parameters
  5680. ----------
  5681. time : Union[datetime.datetime, float, str, None]
  5682. Time to initialize with, current system time by default.
  5683. """
  5684. return mapping.from_maybe_impl(self._sync(self._impl_obj.install(time=time)))
  5685. def fast_forward(self, ticks: typing.Union[int, str]) -> None:
  5686. """Clock.fast_forward
  5687. Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user
  5688. closing the laptop lid for a while and reopening it later, after given time.
  5689. **Usage**
  5690. ```py
  5691. page.clock.fast_forward(1000)
  5692. page.clock.fast_forward(\"30:00\")
  5693. ```
  5694. Parameters
  5695. ----------
  5696. ticks : Union[int, str]
  5697. Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
  5698. "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
  5699. """
  5700. return mapping.from_maybe_impl(
  5701. self._sync(self._impl_obj.fast_forward(ticks=ticks))
  5702. )
  5703. def pause_at(self, time: typing.Union[float, str, datetime.datetime]) -> None:
  5704. """Clock.pause_at
  5705. Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired
  5706. unless `clock.run_for()`, `clock.fast_forward()`, `clock.pause_at()` or
  5707. `clock.resume()` is called.
  5708. Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it
  5709. at the specified time and pausing.
  5710. **Usage**
  5711. ```py
  5712. page.clock.pause_at(datetime.datetime(2020, 2, 2))
  5713. page.clock.pause_at(\"2020-02-02\")
  5714. ```
  5715. For best results, install the clock before navigating the page and set it to a time slightly before the intended
  5716. test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.
  5717. Once the page has fully loaded, you can safely use `clock.pause_at()` to pause the clock.
  5718. ```py
  5719. # Initialize clock with some time before the test time and let the page load
  5720. # naturally. `Date.now` will progress as the timers fire.
  5721. page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0))
  5722. page.goto(\"http://localhost:3333\")
  5723. page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0))
  5724. ```
  5725. Parameters
  5726. ----------
  5727. time : Union[datetime.datetime, float, str]
  5728. Time to pause at.
  5729. """
  5730. return mapping.from_maybe_impl(self._sync(self._impl_obj.pause_at(time=time)))
  5731. def resume(self) -> None:
  5732. """Clock.resume
  5733. Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.
  5734. """
  5735. return mapping.from_maybe_impl(self._sync(self._impl_obj.resume()))
  5736. def run_for(self, ticks: typing.Union[int, str]) -> None:
  5737. """Clock.run_for
  5738. Advance the clock, firing all the time-related callbacks.
  5739. **Usage**
  5740. ```py
  5741. page.clock.run_for(1000);
  5742. page.clock.run_for(\"30:00\")
  5743. ```
  5744. Parameters
  5745. ----------
  5746. ticks : Union[int, str]
  5747. Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
  5748. "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
  5749. """
  5750. return mapping.from_maybe_impl(self._sync(self._impl_obj.run_for(ticks=ticks)))
  5751. def set_fixed_time(self, time: typing.Union[float, str, datetime.datetime]) -> None:
  5752. """Clock.set_fixed_time
  5753. Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.
  5754. Use this method for simple scenarios where you only need to test with a predefined time. For more advanced
  5755. scenarios, use `clock.install()` instead. Read docs on [clock emulation](https://playwright.dev/python/docs/clock) to learn more.
  5756. **Usage**
  5757. ```py
  5758. page.clock.set_fixed_time(datetime.datetime.now())
  5759. page.clock.set_fixed_time(datetime.datetime(2020, 2, 2))
  5760. page.clock.set_fixed_time(\"2020-02-02\")
  5761. ```
  5762. Parameters
  5763. ----------
  5764. time : Union[datetime.datetime, float, str]
  5765. Time to be set.
  5766. """
  5767. return mapping.from_maybe_impl(
  5768. self._sync(self._impl_obj.set_fixed_time(time=time))
  5769. )
  5770. def set_system_time(
  5771. self, time: typing.Union[float, str, datetime.datetime]
  5772. ) -> None:
  5773. """Clock.set_system_time
  5774. Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for
  5775. example switching from summer to winter time, or changing time zones.
  5776. **Usage**
  5777. ```py
  5778. page.clock.set_system_time(datetime.datetime.now())
  5779. page.clock.set_system_time(datetime.datetime(2020, 2, 2))
  5780. page.clock.set_system_time(\"2020-02-02\")
  5781. ```
  5782. Parameters
  5783. ----------
  5784. time : Union[datetime.datetime, float, str]
  5785. Time to be set.
  5786. """
  5787. return mapping.from_maybe_impl(
  5788. self._sync(self._impl_obj.set_system_time(time=time))
  5789. )
  5790. mapping.register(ClockImpl, Clock)
  5791. class ConsoleMessage(SyncBase):
  5792. @property
  5793. def type(
  5794. self,
  5795. ) -> typing.Union[
  5796. Literal["assert"],
  5797. Literal["clear"],
  5798. Literal["count"],
  5799. Literal["debug"],
  5800. Literal["dir"],
  5801. Literal["dirxml"],
  5802. Literal["endGroup"],
  5803. Literal["error"],
  5804. Literal["info"],
  5805. Literal["log"],
  5806. Literal["profile"],
  5807. Literal["profileEnd"],
  5808. Literal["startGroup"],
  5809. Literal["startGroupCollapsed"],
  5810. Literal["table"],
  5811. Literal["time"],
  5812. Literal["timeEnd"],
  5813. Literal["trace"],
  5814. Literal["warning"],
  5815. ]:
  5816. """ConsoleMessage.type
  5817. Returns
  5818. -------
  5819. Union["assert", "clear", "count", "debug", "dir", "dirxml", "endGroup", "error", "info", "log", "profile", "profileEnd", "startGroup", "startGroupCollapsed", "table", "time", "timeEnd", "trace", "warning"]
  5820. """
  5821. return mapping.from_maybe_impl(self._impl_obj.type)
  5822. @property
  5823. def text(self) -> str:
  5824. """ConsoleMessage.text
  5825. The text of the console message.
  5826. Returns
  5827. -------
  5828. str
  5829. """
  5830. return mapping.from_maybe_impl(self._impl_obj.text)
  5831. @property
  5832. def args(self) -> typing.List["JSHandle"]:
  5833. """ConsoleMessage.args
  5834. List of arguments passed to a `console` function call. See also `page.on('console')`.
  5835. Returns
  5836. -------
  5837. List[JSHandle]
  5838. """
  5839. return mapping.from_impl_list(self._impl_obj.args)
  5840. @property
  5841. def location(self) -> SourceLocation:
  5842. """ConsoleMessage.location
  5843. Returns
  5844. -------
  5845. {url: str, lineNumber: int, columnNumber: int}
  5846. """
  5847. return mapping.from_impl(self._impl_obj.location)
  5848. @property
  5849. def page(self) -> typing.Optional["Page"]:
  5850. """ConsoleMessage.page
  5851. The page that produced this console message, if any.
  5852. Returns
  5853. -------
  5854. Union[Page, None]
  5855. """
  5856. return mapping.from_impl_nullable(self._impl_obj.page)
  5857. @property
  5858. def worker(self) -> typing.Optional["Worker"]:
  5859. """ConsoleMessage.worker
  5860. The web worker or service worker that produced this console message, if any. Note that console messages from web
  5861. workers also have non-null `console_message.page()`.
  5862. Returns
  5863. -------
  5864. Union[Worker, None]
  5865. """
  5866. return mapping.from_impl_nullable(self._impl_obj.worker)
  5867. mapping.register(ConsoleMessageImpl, ConsoleMessage)
  5868. class Dialog(SyncBase):
  5869. @property
  5870. def type(self) -> str:
  5871. """Dialog.type
  5872. Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
  5873. Returns
  5874. -------
  5875. str
  5876. """
  5877. return mapping.from_maybe_impl(self._impl_obj.type)
  5878. @property
  5879. def message(self) -> str:
  5880. """Dialog.message
  5881. A message displayed in the dialog.
  5882. Returns
  5883. -------
  5884. str
  5885. """
  5886. return mapping.from_maybe_impl(self._impl_obj.message)
  5887. @property
  5888. def default_value(self) -> str:
  5889. """Dialog.default_value
  5890. If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
  5891. Returns
  5892. -------
  5893. str
  5894. """
  5895. return mapping.from_maybe_impl(self._impl_obj.default_value)
  5896. @property
  5897. def page(self) -> typing.Optional["Page"]:
  5898. """Dialog.page
  5899. The page that initiated this dialog, if available.
  5900. Returns
  5901. -------
  5902. Union[Page, None]
  5903. """
  5904. return mapping.from_impl_nullable(self._impl_obj.page)
  5905. def accept(self, prompt_text: typing.Optional[str] = None) -> None:
  5906. """Dialog.accept
  5907. Returns when the dialog has been accepted.
  5908. Parameters
  5909. ----------
  5910. prompt_text : Union[str, None]
  5911. A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.
  5912. """
  5913. return mapping.from_maybe_impl(
  5914. self._sync(self._impl_obj.accept(promptText=prompt_text))
  5915. )
  5916. def dismiss(self) -> None:
  5917. """Dialog.dismiss
  5918. Returns when the dialog has been dismissed.
  5919. """
  5920. return mapping.from_maybe_impl(self._sync(self._impl_obj.dismiss()))
  5921. mapping.register(DialogImpl, Dialog)
  5922. class Download(SyncBase):
  5923. @property
  5924. def page(self) -> "Page":
  5925. """Download.page
  5926. Get the page that the download belongs to.
  5927. Returns
  5928. -------
  5929. Page
  5930. """
  5931. return mapping.from_impl(self._impl_obj.page)
  5932. @property
  5933. def url(self) -> str:
  5934. """Download.url
  5935. Returns downloaded url.
  5936. Returns
  5937. -------
  5938. str
  5939. """
  5940. return mapping.from_maybe_impl(self._impl_obj.url)
  5941. @property
  5942. def suggested_filename(self) -> str:
  5943. """Download.suggested_filename
  5944. Returns suggested filename for this download. It is typically computed by the browser from the
  5945. [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response
  5946. header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).
  5947. Different browsers can use different logic for computing it.
  5948. Returns
  5949. -------
  5950. str
  5951. """
  5952. return mapping.from_maybe_impl(self._impl_obj.suggested_filename)
  5953. def delete(self) -> None:
  5954. """Download.delete
  5955. Deletes the downloaded file. Will wait for the download to finish if necessary.
  5956. """
  5957. return mapping.from_maybe_impl(self._sync(self._impl_obj.delete()))
  5958. def failure(self) -> typing.Optional[str]:
  5959. """Download.failure
  5960. Returns download error if any. Will wait for the download to finish if necessary.
  5961. Returns
  5962. -------
  5963. Union[str, None]
  5964. """
  5965. return mapping.from_maybe_impl(self._sync(self._impl_obj.failure()))
  5966. def path(self) -> pathlib.Path:
  5967. """Download.path
  5968. Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method
  5969. will wait for the download to finish if necessary. The method throws when connected remotely.
  5970. Note that the download's file name is a random GUID, use `download.suggested_filename()` to get suggested
  5971. file name.
  5972. Returns
  5973. -------
  5974. pathlib.Path
  5975. """
  5976. return mapping.from_maybe_impl(self._sync(self._impl_obj.path()))
  5977. def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
  5978. """Download.save_as
  5979. Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.
  5980. Will wait for the download to finish if necessary.
  5981. **Usage**
  5982. ```py
  5983. download.save_as(\"/path/to/save/at/\" + download.suggested_filename)
  5984. ```
  5985. Parameters
  5986. ----------
  5987. path : Union[pathlib.Path, str]
  5988. Path where the download should be copied.
  5989. """
  5990. return mapping.from_maybe_impl(self._sync(self._impl_obj.save_as(path=path)))
  5991. def cancel(self) -> None:
  5992. """Download.cancel
  5993. Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,
  5994. `download.failure()` would resolve to `'canceled'`.
  5995. """
  5996. return mapping.from_maybe_impl(self._sync(self._impl_obj.cancel()))
  5997. mapping.register(DownloadImpl, Download)
  5998. class Video(SyncBase):
  5999. def path(self) -> pathlib.Path:
  6000. """Video.path
  6001. Returns the file system path this video will be recorded to. The video is guaranteed to be written to the
  6002. filesystem upon closing the browser context. This method throws when connected remotely.
  6003. Returns
  6004. -------
  6005. pathlib.Path
  6006. """
  6007. return mapping.from_maybe_impl(self._sync(self._impl_obj.path()))
  6008. def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
  6009. """Video.save_as
  6010. Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or
  6011. after the page has closed. This method waits until the page is closed and the video is fully saved.
  6012. Parameters
  6013. ----------
  6014. path : Union[pathlib.Path, str]
  6015. Path where the video should be saved.
  6016. """
  6017. return mapping.from_maybe_impl(self._sync(self._impl_obj.save_as(path=path)))
  6018. def delete(self) -> None:
  6019. """Video.delete
  6020. Deletes the video file. Will wait for the video to finish if necessary.
  6021. """
  6022. return mapping.from_maybe_impl(self._sync(self._impl_obj.delete()))
  6023. mapping.register(VideoImpl, Video)
  6024. class Page(SyncContextManager):
  6025. @typing.overload
  6026. def on(self, event: Literal["close"], f: typing.Callable[["Page"], "None"]) -> None:
  6027. """
  6028. Emitted when the page closes."""
  6029. @typing.overload
  6030. def on(
  6031. self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
  6032. ) -> None:
  6033. """
  6034. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  6035. The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
  6036. **Usage**
  6037. ```py
  6038. def print_args(msg):
  6039. for arg in msg.args:
  6040. print(arg.json_value())
  6041. page.on(\"console\", print_args)
  6042. page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  6043. ```"""
  6044. @typing.overload
  6045. def on(self, event: Literal["crash"], f: typing.Callable[["Page"], "None"]) -> None:
  6046. """
  6047. Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
  6048. crashes, ongoing and subsequent operations will throw.
  6049. The most common way to deal with crashes is to catch an exception:
  6050. ```py
  6051. try:
  6052. # crash might happen during a click.
  6053. page.click(\"button\")
  6054. # or while waiting for an event.
  6055. page.wait_for_event(\"popup\")
  6056. except Error as e:
  6057. pass
  6058. # when the page crashes, exception message contains \"crash\".
  6059. ```"""
  6060. @typing.overload
  6061. def on(
  6062. self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
  6063. ) -> None:
  6064. """
  6065. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  6066. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  6067. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  6068. and actions like click will never finish.
  6069. **Usage**
  6070. ```python
  6071. page.on(\"dialog\", lambda dialog: dialog.accept())
  6072. ```
  6073. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  6074. automatically dismissed."""
  6075. @typing.overload
  6076. def on(
  6077. self, event: Literal["domcontentloaded"], f: typing.Callable[["Page"], "None"]
  6078. ) -> None:
  6079. """
  6080. Emitted when the JavaScript
  6081. [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
  6082. """
  6083. @typing.overload
  6084. def on(
  6085. self, event: Literal["download"], f: typing.Callable[["Download"], "None"]
  6086. ) -> None:
  6087. """
  6088. Emitted when attachment download started. User can access basic file operations on downloaded content via the
  6089. passed `Download` instance."""
  6090. @typing.overload
  6091. def on(
  6092. self, event: Literal["filechooser"], f: typing.Callable[["FileChooser"], "None"]
  6093. ) -> None:
  6094. """
  6095. Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
  6096. respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
  6097. ```py
  6098. page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
  6099. ```"""
  6100. @typing.overload
  6101. def on(
  6102. self, event: Literal["frameattached"], f: typing.Callable[["Frame"], "None"]
  6103. ) -> None:
  6104. """
  6105. Emitted when a frame is attached."""
  6106. @typing.overload
  6107. def on(
  6108. self, event: Literal["framedetached"], f: typing.Callable[["Frame"], "None"]
  6109. ) -> None:
  6110. """
  6111. Emitted when a frame is detached."""
  6112. @typing.overload
  6113. def on(
  6114. self, event: Literal["framenavigated"], f: typing.Callable[["Frame"], "None"]
  6115. ) -> None:
  6116. """
  6117. Emitted when a frame is navigated to a new url."""
  6118. @typing.overload
  6119. def on(self, event: Literal["load"], f: typing.Callable[["Page"], "None"]) -> None:
  6120. """
  6121. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
  6122. """
  6123. @typing.overload
  6124. def on(
  6125. self, event: Literal["pageerror"], f: typing.Callable[["Error"], "None"]
  6126. ) -> None:
  6127. """
  6128. Emitted when an uncaught exception happens within the page.
  6129. ```py
  6130. # Log all uncaught errors to the terminal
  6131. page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
  6132. # Navigate to a page with an exception.
  6133. page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
  6134. ```"""
  6135. @typing.overload
  6136. def on(self, event: Literal["popup"], f: typing.Callable[["Page"], "None"]) -> None:
  6137. """
  6138. Emitted when the page opens a new tab or window. This event is emitted in addition to the
  6139. `browser_context.on('page')`, but only for popups relevant to this page.
  6140. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  6141. popup with `window.open('http://example.com')`, this event will fire when the network request to
  6142. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  6143. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  6144. instead of similar methods on the `Page`.
  6145. ```py
  6146. with page.expect_event(\"popup\") as page_info:
  6147. page.get_by_text(\"open the popup\").click()
  6148. popup = page_info.value
  6149. print(popup.evaluate(\"location.href\"))
  6150. ```
  6151. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  6152. need it in most cases)."""
  6153. @typing.overload
  6154. def on(
  6155. self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
  6156. ) -> None:
  6157. """
  6158. Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
  6159. see `page.route()` or `browser_context.route()`."""
  6160. @typing.overload
  6161. def on(
  6162. self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
  6163. ) -> None:
  6164. """
  6165. Emitted when a request fails, for example by timing out.
  6166. ```python
  6167. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
  6168. ```
  6169. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  6170. will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
  6171. only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
  6172. net::ERR_FAILED."""
  6173. @typing.overload
  6174. def on(
  6175. self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
  6176. ) -> None:
  6177. """
  6178. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  6179. sequence of events is `request`, `response` and `requestfinished`."""
  6180. @typing.overload
  6181. def on(
  6182. self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
  6183. ) -> None:
  6184. """
  6185. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  6186. events is `request`, `response` and `requestfinished`."""
  6187. @typing.overload
  6188. def on(
  6189. self, event: Literal["websocket"], f: typing.Callable[["WebSocket"], "None"]
  6190. ) -> None:
  6191. """
  6192. Emitted when `WebSocket` request is sent."""
  6193. @typing.overload
  6194. def on(
  6195. self, event: Literal["worker"], f: typing.Callable[["Worker"], "None"]
  6196. ) -> None:
  6197. """
  6198. Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
  6199. by the page."""
  6200. def on(self, event: str, f: typing.Callable[..., None]) -> None:
  6201. return super().on(event=event, f=f)
  6202. @typing.overload
  6203. def once(
  6204. self, event: Literal["close"], f: typing.Callable[["Page"], "None"]
  6205. ) -> None:
  6206. """
  6207. Emitted when the page closes."""
  6208. @typing.overload
  6209. def once(
  6210. self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
  6211. ) -> None:
  6212. """
  6213. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  6214. The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
  6215. **Usage**
  6216. ```py
  6217. def print_args(msg):
  6218. for arg in msg.args:
  6219. print(arg.json_value())
  6220. page.on(\"console\", print_args)
  6221. page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  6222. ```"""
  6223. @typing.overload
  6224. def once(
  6225. self, event: Literal["crash"], f: typing.Callable[["Page"], "None"]
  6226. ) -> None:
  6227. """
  6228. Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
  6229. crashes, ongoing and subsequent operations will throw.
  6230. The most common way to deal with crashes is to catch an exception:
  6231. ```py
  6232. try:
  6233. # crash might happen during a click.
  6234. page.click(\"button\")
  6235. # or while waiting for an event.
  6236. page.wait_for_event(\"popup\")
  6237. except Error as e:
  6238. pass
  6239. # when the page crashes, exception message contains \"crash\".
  6240. ```"""
  6241. @typing.overload
  6242. def once(
  6243. self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
  6244. ) -> None:
  6245. """
  6246. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  6247. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  6248. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  6249. and actions like click will never finish.
  6250. **Usage**
  6251. ```python
  6252. page.on(\"dialog\", lambda dialog: dialog.accept())
  6253. ```
  6254. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  6255. automatically dismissed."""
  6256. @typing.overload
  6257. def once(
  6258. self, event: Literal["domcontentloaded"], f: typing.Callable[["Page"], "None"]
  6259. ) -> None:
  6260. """
  6261. Emitted when the JavaScript
  6262. [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
  6263. """
  6264. @typing.overload
  6265. def once(
  6266. self, event: Literal["download"], f: typing.Callable[["Download"], "None"]
  6267. ) -> None:
  6268. """
  6269. Emitted when attachment download started. User can access basic file operations on downloaded content via the
  6270. passed `Download` instance."""
  6271. @typing.overload
  6272. def once(
  6273. self, event: Literal["filechooser"], f: typing.Callable[["FileChooser"], "None"]
  6274. ) -> None:
  6275. """
  6276. Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
  6277. respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
  6278. ```py
  6279. page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
  6280. ```"""
  6281. @typing.overload
  6282. def once(
  6283. self, event: Literal["frameattached"], f: typing.Callable[["Frame"], "None"]
  6284. ) -> None:
  6285. """
  6286. Emitted when a frame is attached."""
  6287. @typing.overload
  6288. def once(
  6289. self, event: Literal["framedetached"], f: typing.Callable[["Frame"], "None"]
  6290. ) -> None:
  6291. """
  6292. Emitted when a frame is detached."""
  6293. @typing.overload
  6294. def once(
  6295. self, event: Literal["framenavigated"], f: typing.Callable[["Frame"], "None"]
  6296. ) -> None:
  6297. """
  6298. Emitted when a frame is navigated to a new url."""
  6299. @typing.overload
  6300. def once(
  6301. self, event: Literal["load"], f: typing.Callable[["Page"], "None"]
  6302. ) -> None:
  6303. """
  6304. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
  6305. """
  6306. @typing.overload
  6307. def once(
  6308. self, event: Literal["pageerror"], f: typing.Callable[["Error"], "None"]
  6309. ) -> None:
  6310. """
  6311. Emitted when an uncaught exception happens within the page.
  6312. ```py
  6313. # Log all uncaught errors to the terminal
  6314. page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
  6315. # Navigate to a page with an exception.
  6316. page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
  6317. ```"""
  6318. @typing.overload
  6319. def once(
  6320. self, event: Literal["popup"], f: typing.Callable[["Page"], "None"]
  6321. ) -> None:
  6322. """
  6323. Emitted when the page opens a new tab or window. This event is emitted in addition to the
  6324. `browser_context.on('page')`, but only for popups relevant to this page.
  6325. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  6326. popup with `window.open('http://example.com')`, this event will fire when the network request to
  6327. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  6328. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  6329. instead of similar methods on the `Page`.
  6330. ```py
  6331. with page.expect_event(\"popup\") as page_info:
  6332. page.get_by_text(\"open the popup\").click()
  6333. popup = page_info.value
  6334. print(popup.evaluate(\"location.href\"))
  6335. ```
  6336. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  6337. need it in most cases)."""
  6338. @typing.overload
  6339. def once(
  6340. self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
  6341. ) -> None:
  6342. """
  6343. Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
  6344. see `page.route()` or `browser_context.route()`."""
  6345. @typing.overload
  6346. def once(
  6347. self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
  6348. ) -> None:
  6349. """
  6350. Emitted when a request fails, for example by timing out.
  6351. ```python
  6352. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
  6353. ```
  6354. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  6355. will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
  6356. only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
  6357. net::ERR_FAILED."""
  6358. @typing.overload
  6359. def once(
  6360. self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
  6361. ) -> None:
  6362. """
  6363. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  6364. sequence of events is `request`, `response` and `requestfinished`."""
  6365. @typing.overload
  6366. def once(
  6367. self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
  6368. ) -> None:
  6369. """
  6370. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  6371. events is `request`, `response` and `requestfinished`."""
  6372. @typing.overload
  6373. def once(
  6374. self, event: Literal["websocket"], f: typing.Callable[["WebSocket"], "None"]
  6375. ) -> None:
  6376. """
  6377. Emitted when `WebSocket` request is sent."""
  6378. @typing.overload
  6379. def once(
  6380. self, event: Literal["worker"], f: typing.Callable[["Worker"], "None"]
  6381. ) -> None:
  6382. """
  6383. Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
  6384. by the page."""
  6385. def once(self, event: str, f: typing.Callable[..., None]) -> None:
  6386. return super().once(event=event, f=f)
  6387. @property
  6388. def keyboard(self) -> "Keyboard":
  6389. """Page.keyboard
  6390. Returns
  6391. -------
  6392. Keyboard
  6393. """
  6394. return mapping.from_impl(self._impl_obj.keyboard)
  6395. @property
  6396. def mouse(self) -> "Mouse":
  6397. """Page.mouse
  6398. Returns
  6399. -------
  6400. Mouse
  6401. """
  6402. return mapping.from_impl(self._impl_obj.mouse)
  6403. @property
  6404. def touchscreen(self) -> "Touchscreen":
  6405. """Page.touchscreen
  6406. Returns
  6407. -------
  6408. Touchscreen
  6409. """
  6410. return mapping.from_impl(self._impl_obj.touchscreen)
  6411. @property
  6412. def context(self) -> "BrowserContext":
  6413. """Page.context
  6414. Get the browser context that the page belongs to.
  6415. Returns
  6416. -------
  6417. BrowserContext
  6418. """
  6419. return mapping.from_impl(self._impl_obj.context)
  6420. @property
  6421. def clock(self) -> "Clock":
  6422. """Page.clock
  6423. Playwright has ability to mock clock and passage of time.
  6424. Returns
  6425. -------
  6426. Clock
  6427. """
  6428. return mapping.from_impl(self._impl_obj.clock)
  6429. @property
  6430. def main_frame(self) -> "Frame":
  6431. """Page.main_frame
  6432. The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
  6433. Returns
  6434. -------
  6435. Frame
  6436. """
  6437. return mapping.from_impl(self._impl_obj.main_frame)
  6438. @property
  6439. def frames(self) -> typing.List["Frame"]:
  6440. """Page.frames
  6441. An array of all frames attached to the page.
  6442. Returns
  6443. -------
  6444. List[Frame]
  6445. """
  6446. return mapping.from_impl_list(self._impl_obj.frames)
  6447. @property
  6448. def url(self) -> str:
  6449. """Page.url
  6450. Returns
  6451. -------
  6452. str
  6453. """
  6454. return mapping.from_maybe_impl(self._impl_obj.url)
  6455. @property
  6456. def viewport_size(self) -> typing.Optional[ViewportSize]:
  6457. """Page.viewport_size
  6458. Returns
  6459. -------
  6460. Union[{width: int, height: int}, None]
  6461. """
  6462. return mapping.from_impl_nullable(self._impl_obj.viewport_size)
  6463. @property
  6464. def workers(self) -> typing.List["Worker"]:
  6465. """Page.workers
  6466. This method returns all of the dedicated
  6467. [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
  6468. **NOTE** This does not contain ServiceWorkers
  6469. Returns
  6470. -------
  6471. List[Worker]
  6472. """
  6473. return mapping.from_impl_list(self._impl_obj.workers)
  6474. @property
  6475. def request(self) -> "APIRequestContext":
  6476. """Page.request
  6477. API testing helper associated with this page. This method returns the same instance as
  6478. `browser_context.request` on the page's context. See `browser_context.request` for more
  6479. details.
  6480. Returns
  6481. -------
  6482. APIRequestContext
  6483. """
  6484. return mapping.from_impl(self._impl_obj.request)
  6485. @property
  6486. def video(self) -> typing.Optional["Video"]:
  6487. """Page.video
  6488. Video object associated with this page.
  6489. Returns
  6490. -------
  6491. Union[Video, None]
  6492. """
  6493. return mapping.from_impl_nullable(self._impl_obj.video)
  6494. def opener(self) -> typing.Optional["Page"]:
  6495. """Page.opener
  6496. Returns the opener for popup pages and `null` for others. If the opener has been closed already the returns `null`.
  6497. Returns
  6498. -------
  6499. Union[Page, None]
  6500. """
  6501. return mapping.from_impl_nullable(self._sync(self._impl_obj.opener()))
  6502. def frame(
  6503. self,
  6504. name: typing.Optional[str] = None,
  6505. *,
  6506. url: typing.Optional[
  6507. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  6508. ] = None,
  6509. ) -> typing.Optional["Frame"]:
  6510. """Page.frame
  6511. Returns frame matching the specified criteria. Either `name` or `url` must be specified.
  6512. **Usage**
  6513. ```py
  6514. frame = page.frame(url=r\".*domain.*\")
  6515. ```
  6516. Parameters
  6517. ----------
  6518. name : Union[str, None]
  6519. Frame name specified in the `iframe`'s `name` attribute. Optional.
  6520. url : Union[Callable[[str], bool], Pattern[str], str, None]
  6521. A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object. Optional.
  6522. Returns
  6523. -------
  6524. Union[Frame, None]
  6525. """
  6526. return mapping.from_impl_nullable(
  6527. self._impl_obj.frame(name=name, url=self._wrap_handler(url))
  6528. )
  6529. def set_default_navigation_timeout(self, timeout: float) -> None:
  6530. """Page.set_default_navigation_timeout
  6531. This setting will change the default maximum navigation time for the following methods and related shortcuts:
  6532. - `page.go_back()`
  6533. - `page.go_forward()`
  6534. - `page.goto()`
  6535. - `page.reload()`
  6536. - `page.set_content()`
  6537. - `page.expect_navigation()`
  6538. - `page.wait_for_url()`
  6539. **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`,
  6540. `browser_context.set_default_timeout()` and `browser_context.set_default_navigation_timeout()`.
  6541. Parameters
  6542. ----------
  6543. timeout : float
  6544. Maximum navigation time in milliseconds
  6545. """
  6546. return mapping.from_maybe_impl(
  6547. self._impl_obj.set_default_navigation_timeout(timeout=timeout)
  6548. )
  6549. def set_default_timeout(self, timeout: float) -> None:
  6550. """Page.set_default_timeout
  6551. This setting will change the default maximum time for all the methods accepting `timeout` option.
  6552. **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`.
  6553. Parameters
  6554. ----------
  6555. timeout : float
  6556. Maximum time in milliseconds. Pass `0` to disable timeout.
  6557. """
  6558. return mapping.from_maybe_impl(
  6559. self._impl_obj.set_default_timeout(timeout=timeout)
  6560. )
  6561. def query_selector(
  6562. self, selector: str, *, strict: typing.Optional[bool] = None
  6563. ) -> typing.Optional["ElementHandle"]:
  6564. """Page.query_selector
  6565. The method finds an element matching the specified selector within the page. If no elements match the selector, the
  6566. return value resolves to `null`. To wait for an element on the page, use `locator.wait_for()`.
  6567. Parameters
  6568. ----------
  6569. selector : str
  6570. A selector to query for.
  6571. strict : Union[bool, None]
  6572. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6573. element, the call throws an exception.
  6574. Returns
  6575. -------
  6576. Union[ElementHandle, None]
  6577. """
  6578. return mapping.from_impl_nullable(
  6579. self._sync(self._impl_obj.query_selector(selector=selector, strict=strict))
  6580. )
  6581. def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  6582. """Page.query_selector_all
  6583. The method finds all elements matching the specified selector within the page. If no elements match the selector,
  6584. the return value resolves to `[]`.
  6585. Parameters
  6586. ----------
  6587. selector : str
  6588. A selector to query for.
  6589. Returns
  6590. -------
  6591. List[ElementHandle]
  6592. """
  6593. return mapping.from_impl_list(
  6594. self._sync(self._impl_obj.query_selector_all(selector=selector))
  6595. )
  6596. def wait_for_selector(
  6597. self,
  6598. selector: str,
  6599. *,
  6600. timeout: typing.Optional[float] = None,
  6601. state: typing.Optional[
  6602. Literal["attached", "detached", "hidden", "visible"]
  6603. ] = None,
  6604. strict: typing.Optional[bool] = None,
  6605. ) -> typing.Optional["ElementHandle"]:
  6606. """Page.wait_for_selector
  6607. Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
  6608. `detached`.
  6609. **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
  6610. objects and web-first assertions makes the code wait-for-selector-free.
  6611. Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
  6612. at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
  6613. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
  6614. **Usage**
  6615. This method works across navigations:
  6616. ```py
  6617. from playwright.sync_api import sync_playwright, Playwright
  6618. def run(playwright: Playwright):
  6619. chromium = playwright.chromium
  6620. browser = chromium.launch()
  6621. page = browser.new_page()
  6622. for current_url in [\"https://google.com\", \"https://bbc.com\"]:
  6623. page.goto(current_url, wait_until=\"domcontentloaded\")
  6624. element = page.wait_for_selector(\"img\")
  6625. print(\"Loaded image: \" + str(element.get_attribute(\"src\")))
  6626. browser.close()
  6627. with sync_playwright() as playwright:
  6628. run(playwright)
  6629. ```
  6630. Parameters
  6631. ----------
  6632. selector : str
  6633. A selector to query for.
  6634. timeout : Union[float, None]
  6635. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6636. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6637. state : Union["attached", "detached", "hidden", "visible", None]
  6638. Defaults to `'visible'`. Can be either:
  6639. - `'attached'` - wait for element to be present in DOM.
  6640. - `'detached'` - wait for element to not be present in DOM.
  6641. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  6642. without any content or with `display:none` has an empty bounding box and is not considered visible.
  6643. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  6644. `visibility:hidden`. This is opposite to the `'visible'` option.
  6645. strict : Union[bool, None]
  6646. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6647. element, the call throws an exception.
  6648. Returns
  6649. -------
  6650. Union[ElementHandle, None]
  6651. """
  6652. return mapping.from_impl_nullable(
  6653. self._sync(
  6654. self._impl_obj.wait_for_selector(
  6655. selector=selector, timeout=timeout, state=state, strict=strict
  6656. )
  6657. )
  6658. )
  6659. def is_checked(
  6660. self,
  6661. selector: str,
  6662. *,
  6663. strict: typing.Optional[bool] = None,
  6664. timeout: typing.Optional[float] = None,
  6665. ) -> bool:
  6666. """Page.is_checked
  6667. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  6668. Parameters
  6669. ----------
  6670. selector : str
  6671. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6672. used.
  6673. strict : Union[bool, None]
  6674. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6675. element, the call throws an exception.
  6676. timeout : Union[float, None]
  6677. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6678. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6679. Returns
  6680. -------
  6681. bool
  6682. """
  6683. return mapping.from_maybe_impl(
  6684. self._sync(
  6685. self._impl_obj.is_checked(
  6686. selector=selector, strict=strict, timeout=timeout
  6687. )
  6688. )
  6689. )
  6690. def is_disabled(
  6691. self,
  6692. selector: str,
  6693. *,
  6694. strict: typing.Optional[bool] = None,
  6695. timeout: typing.Optional[float] = None,
  6696. ) -> bool:
  6697. """Page.is_disabled
  6698. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  6699. Parameters
  6700. ----------
  6701. selector : str
  6702. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6703. used.
  6704. strict : Union[bool, None]
  6705. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6706. element, the call throws an exception.
  6707. timeout : Union[float, None]
  6708. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6709. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6710. Returns
  6711. -------
  6712. bool
  6713. """
  6714. return mapping.from_maybe_impl(
  6715. self._sync(
  6716. self._impl_obj.is_disabled(
  6717. selector=selector, strict=strict, timeout=timeout
  6718. )
  6719. )
  6720. )
  6721. def is_editable(
  6722. self,
  6723. selector: str,
  6724. *,
  6725. strict: typing.Optional[bool] = None,
  6726. timeout: typing.Optional[float] = None,
  6727. ) -> bool:
  6728. """Page.is_editable
  6729. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  6730. Parameters
  6731. ----------
  6732. selector : str
  6733. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6734. used.
  6735. strict : Union[bool, None]
  6736. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6737. element, the call throws an exception.
  6738. timeout : Union[float, None]
  6739. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6740. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6741. Returns
  6742. -------
  6743. bool
  6744. """
  6745. return mapping.from_maybe_impl(
  6746. self._sync(
  6747. self._impl_obj.is_editable(
  6748. selector=selector, strict=strict, timeout=timeout
  6749. )
  6750. )
  6751. )
  6752. def is_enabled(
  6753. self,
  6754. selector: str,
  6755. *,
  6756. strict: typing.Optional[bool] = None,
  6757. timeout: typing.Optional[float] = None,
  6758. ) -> bool:
  6759. """Page.is_enabled
  6760. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  6761. Parameters
  6762. ----------
  6763. selector : str
  6764. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6765. used.
  6766. strict : Union[bool, None]
  6767. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6768. element, the call throws an exception.
  6769. timeout : Union[float, None]
  6770. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6771. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6772. Returns
  6773. -------
  6774. bool
  6775. """
  6776. return mapping.from_maybe_impl(
  6777. self._sync(
  6778. self._impl_obj.is_enabled(
  6779. selector=selector, strict=strict, timeout=timeout
  6780. )
  6781. )
  6782. )
  6783. def is_hidden(
  6784. self,
  6785. selector: str,
  6786. *,
  6787. strict: typing.Optional[bool] = None,
  6788. timeout: typing.Optional[float] = None,
  6789. ) -> bool:
  6790. """Page.is_hidden
  6791. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
  6792. does not match any elements is considered hidden.
  6793. Parameters
  6794. ----------
  6795. selector : str
  6796. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6797. used.
  6798. strict : Union[bool, None]
  6799. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6800. element, the call throws an exception.
  6801. timeout : Union[float, None]
  6802. Deprecated: This option is ignored. `page.is_hidden()` does not wait for the↵element to become hidden and returns immediately.
  6803. Returns
  6804. -------
  6805. bool
  6806. """
  6807. return mapping.from_maybe_impl(
  6808. self._sync(
  6809. self._impl_obj.is_hidden(
  6810. selector=selector, strict=strict, timeout=timeout
  6811. )
  6812. )
  6813. )
  6814. def is_visible(
  6815. self,
  6816. selector: str,
  6817. *,
  6818. strict: typing.Optional[bool] = None,
  6819. timeout: typing.Optional[float] = None,
  6820. ) -> bool:
  6821. """Page.is_visible
  6822. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
  6823. is considered not visible.
  6824. Parameters
  6825. ----------
  6826. selector : str
  6827. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6828. used.
  6829. strict : Union[bool, None]
  6830. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6831. element, the call throws an exception.
  6832. timeout : Union[float, None]
  6833. Deprecated: This option is ignored. `page.is_visible()` does not wait↵for the element to become visible and returns immediately.
  6834. Returns
  6835. -------
  6836. bool
  6837. """
  6838. return mapping.from_maybe_impl(
  6839. self._sync(
  6840. self._impl_obj.is_visible(
  6841. selector=selector, strict=strict, timeout=timeout
  6842. )
  6843. )
  6844. )
  6845. def dispatch_event(
  6846. self,
  6847. selector: str,
  6848. type: str,
  6849. event_init: typing.Optional[typing.Dict] = None,
  6850. *,
  6851. timeout: typing.Optional[float] = None,
  6852. strict: typing.Optional[bool] = None,
  6853. ) -> None:
  6854. """Page.dispatch_event
  6855. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  6856. `click` is dispatched. This is equivalent to calling
  6857. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  6858. **Usage**
  6859. ```py
  6860. page.dispatch_event(\"button#submit\", \"click\")
  6861. ```
  6862. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  6863. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  6864. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  6865. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  6866. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  6867. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  6868. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  6869. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  6870. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  6871. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  6872. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  6873. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  6874. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  6875. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  6876. ```py
  6877. # note you can only create data_transfer in chromium and firefox
  6878. data_transfer = page.evaluate_handle(\"new DataTransfer()\")
  6879. page.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
  6880. ```
  6881. Parameters
  6882. ----------
  6883. selector : str
  6884. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6885. used.
  6886. type : str
  6887. DOM event type: `"click"`, `"dragstart"`, etc.
  6888. event_init : Union[Dict, None]
  6889. Optional event-specific initialization properties.
  6890. timeout : Union[float, None]
  6891. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6892. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6893. strict : Union[bool, None]
  6894. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6895. element, the call throws an exception.
  6896. """
  6897. return mapping.from_maybe_impl(
  6898. self._sync(
  6899. self._impl_obj.dispatch_event(
  6900. selector=selector,
  6901. type=type,
  6902. eventInit=mapping.to_impl(event_init),
  6903. timeout=timeout,
  6904. strict=strict,
  6905. )
  6906. )
  6907. )
  6908. def evaluate(
  6909. self, expression: str, arg: typing.Optional[typing.Any] = None
  6910. ) -> typing.Any:
  6911. """Page.evaluate
  6912. Returns the value of the `expression` invocation.
  6913. If the function passed to the `page.evaluate()` returns a [Promise], then `page.evaluate()` would
  6914. wait for the promise to resolve and return its value.
  6915. If the function passed to the `page.evaluate()` returns a non-[Serializable] value, then
  6916. `page.evaluate()` resolves to `undefined`. Playwright also supports transferring some additional values
  6917. that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  6918. **Usage**
  6919. Passing argument to `expression`:
  6920. ```py
  6921. result = page.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
  6922. print(result) # prints \"56\"
  6923. ```
  6924. A string can also be passed in instead of a function:
  6925. ```py
  6926. print(page.evaluate(\"1 + 2\")) # prints \"3\"
  6927. x = 10
  6928. print(page.evaluate(f\"1 + {x}\")) # prints \"11\"
  6929. ```
  6930. `ElementHandle` instances can be passed as an argument to the `page.evaluate()`:
  6931. ```py
  6932. body_handle = page.evaluate(\"document.body\")
  6933. html = page.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
  6934. body_handle.dispose()
  6935. ```
  6936. Parameters
  6937. ----------
  6938. expression : str
  6939. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  6940. function is automatically invoked.
  6941. arg : Union[Any, None]
  6942. Optional argument to pass to `expression`.
  6943. Returns
  6944. -------
  6945. Any
  6946. """
  6947. return mapping.from_maybe_impl(
  6948. self._sync(
  6949. self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
  6950. )
  6951. )
  6952. def evaluate_handle(
  6953. self, expression: str, arg: typing.Optional[typing.Any] = None
  6954. ) -> "JSHandle":
  6955. """Page.evaluate_handle
  6956. Returns the value of the `expression` invocation as a `JSHandle`.
  6957. The only difference between `page.evaluate()` and `page.evaluate_handle()` is that
  6958. `page.evaluate_handle()` returns `JSHandle`.
  6959. If the function passed to the `page.evaluate_handle()` returns a [Promise], then
  6960. `page.evaluate_handle()` would wait for the promise to resolve and return its value.
  6961. **Usage**
  6962. ```py
  6963. a_window_handle = page.evaluate_handle(\"Promise.resolve(window)\")
  6964. a_window_handle # handle for the window object.
  6965. ```
  6966. A string can also be passed in instead of a function:
  6967. ```py
  6968. a_handle = page.evaluate_handle(\"document\") # handle for the \"document\"
  6969. ```
  6970. `JSHandle` instances can be passed as an argument to the `page.evaluate_handle()`:
  6971. ```py
  6972. a_handle = page.evaluate_handle(\"document.body\")
  6973. result_handle = page.evaluate_handle(\"body => body.innerHTML\", a_handle)
  6974. print(result_handle.json_value())
  6975. result_handle.dispose()
  6976. ```
  6977. Parameters
  6978. ----------
  6979. expression : str
  6980. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  6981. function is automatically invoked.
  6982. arg : Union[Any, None]
  6983. Optional argument to pass to `expression`.
  6984. Returns
  6985. -------
  6986. JSHandle
  6987. """
  6988. return mapping.from_impl(
  6989. self._sync(
  6990. self._impl_obj.evaluate_handle(
  6991. expression=expression, arg=mapping.to_impl(arg)
  6992. )
  6993. )
  6994. )
  6995. def eval_on_selector(
  6996. self,
  6997. selector: str,
  6998. expression: str,
  6999. arg: typing.Optional[typing.Any] = None,
  7000. *,
  7001. strict: typing.Optional[bool] = None,
  7002. ) -> typing.Any:
  7003. """Page.eval_on_selector
  7004. The method finds an element matching the specified selector within the page and passes it as a first argument to
  7005. `expression`. If no elements match the selector, the method throws an error. Returns the value of `expression`.
  7006. If `expression` returns a [Promise], then `page.eval_on_selector()` would wait for the promise to resolve and
  7007. return its value.
  7008. **Usage**
  7009. ```py
  7010. search_value = page.eval_on_selector(\"#search\", \"el => el.value\")
  7011. preload_href = page.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
  7012. html = page.eval_on_selector(\".main-container\", \"(e, suffix) => e.outer_html + suffix\", \"hello\")
  7013. ```
  7014. Parameters
  7015. ----------
  7016. selector : str
  7017. A selector to query for.
  7018. expression : str
  7019. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7020. function is automatically invoked.
  7021. arg : Union[Any, None]
  7022. Optional argument to pass to `expression`.
  7023. strict : Union[bool, None]
  7024. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7025. element, the call throws an exception.
  7026. Returns
  7027. -------
  7028. Any
  7029. """
  7030. return mapping.from_maybe_impl(
  7031. self._sync(
  7032. self._impl_obj.eval_on_selector(
  7033. selector=selector,
  7034. expression=expression,
  7035. arg=mapping.to_impl(arg),
  7036. strict=strict,
  7037. )
  7038. )
  7039. )
  7040. def eval_on_selector_all(
  7041. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  7042. ) -> typing.Any:
  7043. """Page.eval_on_selector_all
  7044. The method finds all elements matching the specified selector within the page and passes an array of matched
  7045. elements as a first argument to `expression`. Returns the result of `expression` invocation.
  7046. If `expression` returns a [Promise], then `page.eval_on_selector_all()` would wait for the promise to resolve
  7047. and return its value.
  7048. **Usage**
  7049. ```py
  7050. div_counts = page.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
  7051. ```
  7052. Parameters
  7053. ----------
  7054. selector : str
  7055. A selector to query for.
  7056. expression : str
  7057. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7058. function is automatically invoked.
  7059. arg : Union[Any, None]
  7060. Optional argument to pass to `expression`.
  7061. Returns
  7062. -------
  7063. Any
  7064. """
  7065. return mapping.from_maybe_impl(
  7066. self._sync(
  7067. self._impl_obj.eval_on_selector_all(
  7068. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  7069. )
  7070. )
  7071. )
  7072. def add_script_tag(
  7073. self,
  7074. *,
  7075. url: typing.Optional[str] = None,
  7076. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7077. content: typing.Optional[str] = None,
  7078. type: typing.Optional[str] = None,
  7079. ) -> "ElementHandle":
  7080. """Page.add_script_tag
  7081. Adds a `<script>` tag into the page with the desired url or content. Returns the added tag when the script's onload
  7082. fires or when the script content was injected into frame.
  7083. Parameters
  7084. ----------
  7085. url : Union[str, None]
  7086. URL of a script to be added.
  7087. path : Union[pathlib.Path, str, None]
  7088. Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
  7089. to the current working directory.
  7090. content : Union[str, None]
  7091. Raw JavaScript content to be injected into frame.
  7092. type : Union[str, None]
  7093. Script type. Use 'module' in order to load a JavaScript ES6 module. See
  7094. [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
  7095. Returns
  7096. -------
  7097. ElementHandle
  7098. """
  7099. return mapping.from_impl(
  7100. self._sync(
  7101. self._impl_obj.add_script_tag(
  7102. url=url, path=path, content=content, type=type
  7103. )
  7104. )
  7105. )
  7106. def add_style_tag(
  7107. self,
  7108. *,
  7109. url: typing.Optional[str] = None,
  7110. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7111. content: typing.Optional[str] = None,
  7112. ) -> "ElementHandle":
  7113. """Page.add_style_tag
  7114. Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
  7115. content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
  7116. Parameters
  7117. ----------
  7118. url : Union[str, None]
  7119. URL of the `<link>` tag.
  7120. path : Union[pathlib.Path, str, None]
  7121. Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
  7122. current working directory.
  7123. content : Union[str, None]
  7124. Raw CSS content to be injected into frame.
  7125. Returns
  7126. -------
  7127. ElementHandle
  7128. """
  7129. return mapping.from_impl(
  7130. self._sync(
  7131. self._impl_obj.add_style_tag(url=url, path=path, content=content)
  7132. )
  7133. )
  7134. def expose_function(self, name: str, callback: typing.Callable) -> None:
  7135. """Page.expose_function
  7136. The method adds a function called `name` on the `window` object of every frame in the page. When called, the
  7137. function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  7138. If the `callback` returns a [Promise], it will be awaited.
  7139. See `browser_context.expose_function()` for context-wide exposed function.
  7140. **NOTE** Functions installed via `page.expose_function()` survive navigations.
  7141. **Usage**
  7142. An example of adding a `sha256` function to the page:
  7143. ```py
  7144. import hashlib
  7145. from playwright.sync_api import sync_playwright, Playwright
  7146. def sha256(text):
  7147. m = hashlib.sha256()
  7148. m.update(bytes(text, \"utf8\"))
  7149. return m.hexdigest()
  7150. def run(playwright: Playwright):
  7151. webkit = playwright.webkit
  7152. browser = webkit.launch(headless=False)
  7153. page = browser.new_page()
  7154. page.expose_function(\"sha256\", sha256)
  7155. page.set_content(\"\"\"
  7156. <script>
  7157. async function onClick() {
  7158. document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  7159. }
  7160. </script>
  7161. <button onclick=\"onClick()\">Click me</button>
  7162. <div></div>
  7163. \"\"\")
  7164. page.click(\"button\")
  7165. with sync_playwright() as playwright:
  7166. run(playwright)
  7167. ```
  7168. Parameters
  7169. ----------
  7170. name : str
  7171. Name of the function on the window object
  7172. callback : Callable
  7173. Callback function which will be called in Playwright's context.
  7174. """
  7175. return mapping.from_maybe_impl(
  7176. self._sync(
  7177. self._impl_obj.expose_function(
  7178. name=name, callback=self._wrap_handler(callback)
  7179. )
  7180. )
  7181. )
  7182. def expose_binding(
  7183. self,
  7184. name: str,
  7185. callback: typing.Callable,
  7186. *,
  7187. handle: typing.Optional[bool] = None,
  7188. ) -> None:
  7189. """Page.expose_binding
  7190. The method adds a function called `name` on the `window` object of every frame in this page. When called, the
  7191. function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the
  7192. `callback` returns a [Promise], it will be awaited.
  7193. The first argument of the `callback` function contains information about the caller: `{ browserContext:
  7194. BrowserContext, page: Page, frame: Frame }`.
  7195. See `browser_context.expose_binding()` for the context-wide version.
  7196. **NOTE** Functions installed via `page.expose_binding()` survive navigations.
  7197. **Usage**
  7198. An example of exposing page URL to all frames in a page:
  7199. ```py
  7200. from playwright.sync_api import sync_playwright, Playwright
  7201. def run(playwright: Playwright):
  7202. webkit = playwright.webkit
  7203. browser = webkit.launch(headless=False)
  7204. context = browser.new_context()
  7205. page = context.new_page()
  7206. page.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
  7207. page.set_content(\"\"\"
  7208. <script>
  7209. async function onClick() {
  7210. document.querySelector('div').textContent = await window.pageURL();
  7211. }
  7212. </script>
  7213. <button onclick=\"onClick()\">Click me</button>
  7214. <div></div>
  7215. \"\"\")
  7216. page.click(\"button\")
  7217. with sync_playwright() as playwright:
  7218. run(playwright)
  7219. ```
  7220. Parameters
  7221. ----------
  7222. name : str
  7223. Name of the function on the window object.
  7224. callback : Callable
  7225. Callback function that will be called in the Playwright's context.
  7226. handle : Union[bool, None]
  7227. Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
  7228. supported. When passing by value, multiple arguments are supported.
  7229. Deprecated: This option will be removed in the future.
  7230. """
  7231. return mapping.from_maybe_impl(
  7232. self._sync(
  7233. self._impl_obj.expose_binding(
  7234. name=name, callback=self._wrap_handler(callback), handle=handle
  7235. )
  7236. )
  7237. )
  7238. def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
  7239. """Page.set_extra_http_headers
  7240. The extra HTTP headers will be sent with every request the page initiates.
  7241. **NOTE** `page.set_extra_http_headers()` does not guarantee the order of headers in the outgoing requests.
  7242. Parameters
  7243. ----------
  7244. headers : Dict[str, str]
  7245. An object containing additional HTTP headers to be sent with every request. All header values must be strings.
  7246. """
  7247. return mapping.from_maybe_impl(
  7248. self._sync(
  7249. self._impl_obj.set_extra_http_headers(headers=mapping.to_impl(headers))
  7250. )
  7251. )
  7252. def content(self) -> str:
  7253. """Page.content
  7254. Gets the full HTML contents of the page, including the doctype.
  7255. Returns
  7256. -------
  7257. str
  7258. """
  7259. return mapping.from_maybe_impl(self._sync(self._impl_obj.content()))
  7260. def set_content(
  7261. self,
  7262. html: str,
  7263. *,
  7264. timeout: typing.Optional[float] = None,
  7265. wait_until: typing.Optional[
  7266. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7267. ] = None,
  7268. ) -> None:
  7269. """Page.set_content
  7270. This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
  7271. inheriting all its specific characteristics and behaviors.
  7272. Parameters
  7273. ----------
  7274. html : str
  7275. HTML markup to assign to the page.
  7276. timeout : Union[float, None]
  7277. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7278. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7279. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7280. `page.set_default_timeout()` methods.
  7281. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7282. When to consider operation succeeded, defaults to `load`. Events can be either:
  7283. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7284. - `'load'` - consider operation to be finished when the `load` event is fired.
  7285. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7286. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7287. - `'commit'` - consider operation to be finished when network response is received and the document started
  7288. loading.
  7289. """
  7290. return mapping.from_maybe_impl(
  7291. self._sync(
  7292. self._impl_obj.set_content(
  7293. html=html, timeout=timeout, waitUntil=wait_until
  7294. )
  7295. )
  7296. )
  7297. def goto(
  7298. self,
  7299. url: str,
  7300. *,
  7301. timeout: typing.Optional[float] = None,
  7302. wait_until: typing.Optional[
  7303. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7304. ] = None,
  7305. referer: typing.Optional[str] = None,
  7306. ) -> typing.Optional["Response"]:
  7307. """Page.goto
  7308. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first
  7309. non-redirect response.
  7310. The method will throw an error if:
  7311. - there's an SSL error (e.g. in case of self-signed certificates).
  7312. - target URL is invalid.
  7313. - the `timeout` is exceeded during navigation.
  7314. - the remote server does not respond or is unreachable.
  7315. - the main resource failed to load.
  7316. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
  7317. \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
  7318. `response.status()`.
  7319. **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
  7320. to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
  7321. **NOTE** Headless mode doesn't support navigation to a PDF document. See the
  7322. [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
  7323. Parameters
  7324. ----------
  7325. url : str
  7326. URL to navigate page to. The url should include scheme, e.g. `https://`. When a `baseURL` via the context options
  7327. was provided and the passed URL is a path, it gets merged via the
  7328. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  7329. timeout : Union[float, None]
  7330. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7331. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7332. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7333. `page.set_default_timeout()` methods.
  7334. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7335. When to consider operation succeeded, defaults to `load`. Events can be either:
  7336. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7337. - `'load'` - consider operation to be finished when the `load` event is fired.
  7338. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7339. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7340. - `'commit'` - consider operation to be finished when network response is received and the document started
  7341. loading.
  7342. referer : Union[str, None]
  7343. Referer header value. If provided it will take preference over the referer header value set by
  7344. `page.set_extra_http_headers()`.
  7345. Returns
  7346. -------
  7347. Union[Response, None]
  7348. """
  7349. return mapping.from_impl_nullable(
  7350. self._sync(
  7351. self._impl_obj.goto(
  7352. url=url, timeout=timeout, waitUntil=wait_until, referer=referer
  7353. )
  7354. )
  7355. )
  7356. def reload(
  7357. self,
  7358. *,
  7359. timeout: typing.Optional[float] = None,
  7360. wait_until: typing.Optional[
  7361. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7362. ] = None,
  7363. ) -> typing.Optional["Response"]:
  7364. """Page.reload
  7365. This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the
  7366. main resource response. In case of multiple redirects, the navigation will resolve with the response of the last
  7367. redirect.
  7368. Parameters
  7369. ----------
  7370. timeout : Union[float, None]
  7371. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7372. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7373. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7374. `page.set_default_timeout()` methods.
  7375. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7376. When to consider operation succeeded, defaults to `load`. Events can be either:
  7377. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7378. - `'load'` - consider operation to be finished when the `load` event is fired.
  7379. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7380. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7381. - `'commit'` - consider operation to be finished when network response is received and the document started
  7382. loading.
  7383. Returns
  7384. -------
  7385. Union[Response, None]
  7386. """
  7387. return mapping.from_impl_nullable(
  7388. self._sync(self._impl_obj.reload(timeout=timeout, waitUntil=wait_until))
  7389. )
  7390. def wait_for_load_state(
  7391. self,
  7392. state: typing.Optional[
  7393. Literal["domcontentloaded", "load", "networkidle"]
  7394. ] = None,
  7395. *,
  7396. timeout: typing.Optional[float] = None,
  7397. ) -> None:
  7398. """Page.wait_for_load_state
  7399. Returns when the required load state has been reached.
  7400. This resolves when the page reaches a required load state, `load` by default. The navigation must have been
  7401. committed when this method is called. If current document has already reached the required state, resolves
  7402. immediately.
  7403. **NOTE** Most of the time, this method is not needed because Playwright
  7404. [auto-waits before every action](https://playwright.dev/python/docs/actionability).
  7405. **Usage**
  7406. ```py
  7407. page.get_by_role(\"button\").click() # click triggers navigation.
  7408. page.wait_for_load_state() # the promise resolves after \"load\" event.
  7409. ```
  7410. ```py
  7411. with page.expect_popup() as page_info:
  7412. page.get_by_role(\"button\").click() # click triggers a popup.
  7413. popup = page_info.value
  7414. # Wait for the \"DOMContentLoaded\" event.
  7415. popup.wait_for_load_state(\"domcontentloaded\")
  7416. print(popup.title()) # popup is ready to use.
  7417. ```
  7418. Parameters
  7419. ----------
  7420. state : Union["domcontentloaded", "load", "networkidle", None]
  7421. Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
  7422. document, the method resolves immediately. Can be one of:
  7423. - `'load'` - wait for the `load` event to be fired.
  7424. - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
  7425. - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
  7426. this method for testing, rely on web assertions to assess readiness instead.
  7427. timeout : Union[float, None]
  7428. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7429. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7430. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7431. `page.set_default_timeout()` methods.
  7432. """
  7433. return mapping.from_maybe_impl(
  7434. self._sync(self._impl_obj.wait_for_load_state(state=state, timeout=timeout))
  7435. )
  7436. def wait_for_url(
  7437. self,
  7438. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7439. *,
  7440. wait_until: typing.Optional[
  7441. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7442. ] = None,
  7443. timeout: typing.Optional[float] = None,
  7444. ) -> None:
  7445. """Page.wait_for_url
  7446. Waits for the main frame to navigate to the given URL.
  7447. **Usage**
  7448. ```py
  7449. page.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  7450. page.wait_for_url(\"**/target.html\")
  7451. ```
  7452. Parameters
  7453. ----------
  7454. url : Union[Callable[[str], bool], Pattern[str], str]
  7455. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  7456. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  7457. equal to the string.
  7458. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7459. When to consider operation succeeded, defaults to `load`. Events can be either:
  7460. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7461. - `'load'` - consider operation to be finished when the `load` event is fired.
  7462. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7463. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7464. - `'commit'` - consider operation to be finished when network response is received and the document started
  7465. loading.
  7466. timeout : Union[float, None]
  7467. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7468. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7469. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7470. `page.set_default_timeout()` methods.
  7471. """
  7472. return mapping.from_maybe_impl(
  7473. self._sync(
  7474. self._impl_obj.wait_for_url(
  7475. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  7476. )
  7477. )
  7478. )
  7479. def wait_for_event(
  7480. self,
  7481. event: str,
  7482. predicate: typing.Optional[typing.Callable] = None,
  7483. *,
  7484. timeout: typing.Optional[float] = None,
  7485. ) -> typing.Any:
  7486. """Page.wait_for_event
  7487. **NOTE** In most cases, you should use `page.expect_event()`.
  7488. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  7489. and waits for `predicate(event)` to return a truthy value. Will throw an error if the page is closed before the
  7490. `event` is fired.
  7491. Parameters
  7492. ----------
  7493. event : str
  7494. Event name, same one typically passed into `*.on(event)`.
  7495. predicate : Union[Callable, None]
  7496. Receives the event data and resolves to truthy value when the waiting should resolve.
  7497. timeout : Union[float, None]
  7498. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  7499. default value can be changed by using the `browser_context.set_default_timeout()`.
  7500. Returns
  7501. -------
  7502. Any
  7503. """
  7504. return mapping.from_maybe_impl(
  7505. self._sync(
  7506. self._impl_obj.wait_for_event(
  7507. event=event,
  7508. predicate=self._wrap_handler(predicate),
  7509. timeout=timeout,
  7510. )
  7511. )
  7512. )
  7513. def go_back(
  7514. self,
  7515. *,
  7516. timeout: typing.Optional[float] = None,
  7517. wait_until: typing.Optional[
  7518. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7519. ] = None,
  7520. ) -> typing.Optional["Response"]:
  7521. """Page.go_back
  7522. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  7523. the last redirect. If cannot go back, returns `null`.
  7524. Navigate to the previous page in history.
  7525. Parameters
  7526. ----------
  7527. timeout : Union[float, None]
  7528. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7529. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7530. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7531. `page.set_default_timeout()` methods.
  7532. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7533. When to consider operation succeeded, defaults to `load`. Events can be either:
  7534. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7535. - `'load'` - consider operation to be finished when the `load` event is fired.
  7536. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7537. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7538. - `'commit'` - consider operation to be finished when network response is received and the document started
  7539. loading.
  7540. Returns
  7541. -------
  7542. Union[Response, None]
  7543. """
  7544. return mapping.from_impl_nullable(
  7545. self._sync(self._impl_obj.go_back(timeout=timeout, waitUntil=wait_until))
  7546. )
  7547. def go_forward(
  7548. self,
  7549. *,
  7550. timeout: typing.Optional[float] = None,
  7551. wait_until: typing.Optional[
  7552. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7553. ] = None,
  7554. ) -> typing.Optional["Response"]:
  7555. """Page.go_forward
  7556. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  7557. the last redirect. If cannot go forward, returns `null`.
  7558. Navigate to the next page in history.
  7559. Parameters
  7560. ----------
  7561. timeout : Union[float, None]
  7562. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7563. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7564. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7565. `page.set_default_timeout()` methods.
  7566. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7567. When to consider operation succeeded, defaults to `load`. Events can be either:
  7568. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7569. - `'load'` - consider operation to be finished when the `load` event is fired.
  7570. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7571. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7572. - `'commit'` - consider operation to be finished when network response is received and the document started
  7573. loading.
  7574. Returns
  7575. -------
  7576. Union[Response, None]
  7577. """
  7578. return mapping.from_impl_nullable(
  7579. self._sync(self._impl_obj.go_forward(timeout=timeout, waitUntil=wait_until))
  7580. )
  7581. def request_gc(self) -> None:
  7582. """Page.request_gc
  7583. Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will
  7584. be collected.
  7585. This is useful to help detect memory leaks. For example, if your page has a large object `'suspect'` that might be
  7586. leaked, you can check that it does not leak by using a
  7587. [`WeakRef`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef).
  7588. ```py
  7589. # 1. In your page, save a WeakRef for the \"suspect\".
  7590. page.evaluate(\"globalThis.suspectWeakRef = new WeakRef(suspect)\")
  7591. # 2. Request garbage collection.
  7592. page.request_gc()
  7593. # 3. Check that weak ref does not deref to the original object.
  7594. assert page.evaluate(\"!globalThis.suspectWeakRef.deref()\")
  7595. ```
  7596. """
  7597. return mapping.from_maybe_impl(self._sync(self._impl_obj.request_gc()))
  7598. def emulate_media(
  7599. self,
  7600. *,
  7601. media: typing.Optional[Literal["null", "print", "screen"]] = None,
  7602. color_scheme: typing.Optional[
  7603. Literal["dark", "light", "no-preference", "null"]
  7604. ] = None,
  7605. reduced_motion: typing.Optional[
  7606. Literal["no-preference", "null", "reduce"]
  7607. ] = None,
  7608. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  7609. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  7610. ) -> None:
  7611. """Page.emulate_media
  7612. This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media
  7613. feature, using the `colorScheme` argument.
  7614. **Usage**
  7615. ```py
  7616. page.evaluate(\"matchMedia('screen').matches\")
  7617. # → True
  7618. page.evaluate(\"matchMedia('print').matches\")
  7619. # → False
  7620. page.emulate_media(media=\"print\")
  7621. page.evaluate(\"matchMedia('screen').matches\")
  7622. # → False
  7623. page.evaluate(\"matchMedia('print').matches\")
  7624. # → True
  7625. page.emulate_media()
  7626. page.evaluate(\"matchMedia('screen').matches\")
  7627. # → True
  7628. page.evaluate(\"matchMedia('print').matches\")
  7629. # → False
  7630. ```
  7631. ```py
  7632. page.emulate_media(color_scheme=\"dark\")
  7633. page.evaluate(\"matchMedia('(prefers-color-scheme: dark)').matches\")
  7634. # → True
  7635. page.evaluate(\"matchMedia('(prefers-color-scheme: light)').matches\")
  7636. # → False
  7637. ```
  7638. Parameters
  7639. ----------
  7640. media : Union["null", "print", "screen", None]
  7641. Changes the CSS media type of the page. The only allowed values are `'Screen'`, `'Print'` and `'Null'`. Passing
  7642. `'Null'` disables CSS media emulation.
  7643. color_scheme : Union["dark", "light", "no-preference", "null", None]
  7644. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  7645. media feature, supported values are `'light'` and `'dark'`. Passing `'Null'` disables color scheme emulation.
  7646. `'no-preference'` is deprecated.
  7647. reduced_motion : Union["no-preference", "null", "reduce", None]
  7648. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. Passing
  7649. `null` disables reduced motion emulation.
  7650. forced_colors : Union["active", "none", "null", None]
  7651. contrast : Union["more", "no-preference", "null", None]
  7652. """
  7653. return mapping.from_maybe_impl(
  7654. self._sync(
  7655. self._impl_obj.emulate_media(
  7656. media=media,
  7657. colorScheme=color_scheme,
  7658. reducedMotion=reduced_motion,
  7659. forcedColors=forced_colors,
  7660. contrast=contrast,
  7661. )
  7662. )
  7663. )
  7664. def set_viewport_size(self, viewport_size: ViewportSize) -> None:
  7665. """Page.set_viewport_size
  7666. In the case of multiple pages in a single browser, each page can have its own viewport size. However,
  7667. `browser.new_context()` allows to set viewport size (and more) for all pages in the context at once.
  7668. `page.set_viewport_size()` will resize the page. A lot of websites don't expect phones to change size, so you
  7669. should set the viewport size before navigating to the page. `page.set_viewport_size()` will also reset
  7670. `screen` size, use `browser.new_context()` with `screen` and `viewport` parameters if you need better
  7671. control of these properties.
  7672. **Usage**
  7673. ```py
  7674. page = browser.new_page()
  7675. page.set_viewport_size({\"width\": 640, \"height\": 480})
  7676. page.goto(\"https://example.com\")
  7677. ```
  7678. Parameters
  7679. ----------
  7680. viewport_size : {width: int, height: int}
  7681. """
  7682. return mapping.from_maybe_impl(
  7683. self._sync(self._impl_obj.set_viewport_size(viewportSize=viewport_size))
  7684. )
  7685. def bring_to_front(self) -> None:
  7686. """Page.bring_to_front
  7687. Brings page to front (activates tab).
  7688. """
  7689. return mapping.from_maybe_impl(self._sync(self._impl_obj.bring_to_front()))
  7690. def add_init_script(
  7691. self,
  7692. script: typing.Optional[str] = None,
  7693. *,
  7694. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7695. ) -> None:
  7696. """Page.add_init_script
  7697. Adds a script which would be evaluated in one of the following scenarios:
  7698. - Whenever the page is navigated.
  7699. - Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the
  7700. newly attached frame.
  7701. The script is evaluated after the document was created but before any of its scripts were run. This is useful to
  7702. amend the JavaScript environment, e.g. to seed `Math.random`.
  7703. **Usage**
  7704. An example of overriding `Math.random` before the page loads:
  7705. ```py
  7706. # in your playwright script, assuming the preload.js file is in same directory
  7707. page.add_init_script(path=\"./preload.js\")
  7708. ```
  7709. **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
  7710. `page.add_init_script()` is not defined.
  7711. Parameters
  7712. ----------
  7713. script : Union[str, None]
  7714. Script to be evaluated in all pages in the browser context. Optional.
  7715. path : Union[pathlib.Path, str, None]
  7716. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  7717. directory. Optional.
  7718. """
  7719. return mapping.from_maybe_impl(
  7720. self._sync(self._impl_obj.add_init_script(script=script, path=path))
  7721. )
  7722. def route(
  7723. self,
  7724. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7725. handler: typing.Union[
  7726. typing.Callable[["Route"], typing.Any],
  7727. typing.Callable[["Route", "Request"], typing.Any],
  7728. ],
  7729. *,
  7730. times: typing.Optional[int] = None,
  7731. ) -> None:
  7732. """Page.route
  7733. Routing provides the capability to modify network requests that are made by a page.
  7734. Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or
  7735. aborted.
  7736. **NOTE** The handler will only be called for the first url if the response is a redirect.
  7737. **NOTE** `page.route()` will not intercept requests intercepted by Service Worker. See
  7738. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  7739. using request interception by setting `serviceWorkers` to `'block'`.
  7740. **NOTE** `page.route()` will not intercept the first request of a popup page. Use
  7741. `browser_context.route()` instead.
  7742. **Usage**
  7743. An example of a naive handler that aborts all image requests:
  7744. ```py
  7745. page = browser.new_page()
  7746. page.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
  7747. page.goto(\"https://example.com\")
  7748. browser.close()
  7749. ```
  7750. or the same snippet using a regex pattern instead:
  7751. ```py
  7752. page = browser.new_page()
  7753. page.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
  7754. page.goto(\"https://example.com\")
  7755. browser.close()
  7756. ```
  7757. It is possible to examine the request to decide the route action. For example, mocking all requests that contain
  7758. some post data, and leaving all other requests as is:
  7759. ```py
  7760. def handle_route(route: Route):
  7761. if (\"my-string\" in route.request.post_data):
  7762. route.fulfill(body=\"mocked-data\")
  7763. else:
  7764. route.continue_()
  7765. page.route(\"/api/**\", handle_route)
  7766. ```
  7767. Page routes take precedence over browser context routes (set up with `browser_context.route()`) when request
  7768. matches both handlers.
  7769. To remove a route with its handler you can use `page.unroute()`.
  7770. **NOTE** Enabling routing disables http cache.
  7771. Parameters
  7772. ----------
  7773. url : Union[Callable[[str], bool], Pattern[str], str]
  7774. A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
  7775. the context options and the provided URL is a string that does not start with `*`, it is resolved using the
  7776. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  7777. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
  7778. handler function to route the request.
  7779. times : Union[int, None]
  7780. How often a route should be used. By default it will be used every time.
  7781. """
  7782. return mapping.from_maybe_impl(
  7783. self._sync(
  7784. self._impl_obj.route(
  7785. url=self._wrap_handler(url),
  7786. handler=self._wrap_handler(handler),
  7787. times=times,
  7788. )
  7789. )
  7790. )
  7791. def unroute(
  7792. self,
  7793. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7794. handler: typing.Optional[
  7795. typing.Union[
  7796. typing.Callable[["Route"], typing.Any],
  7797. typing.Callable[["Route", "Request"], typing.Any],
  7798. ]
  7799. ] = None,
  7800. ) -> None:
  7801. """Page.unroute
  7802. Removes a route created with `page.route()`. When `handler` is not specified, removes all routes for the
  7803. `url`.
  7804. Parameters
  7805. ----------
  7806. url : Union[Callable[[str], bool], Pattern[str], str]
  7807. A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
  7808. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
  7809. Optional handler function to route the request.
  7810. """
  7811. return mapping.from_maybe_impl(
  7812. self._sync(
  7813. self._impl_obj.unroute(
  7814. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  7815. )
  7816. )
  7817. )
  7818. def route_web_socket(
  7819. self,
  7820. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7821. handler: typing.Callable[["WebSocketRoute"], typing.Any],
  7822. ) -> None:
  7823. """Page.route_web_socket
  7824. This method allows to modify websocket connections that are made by the page.
  7825. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
  7826. method before navigating the page.
  7827. **Usage**
  7828. Below is an example of a simple mock that responds to a single message. See `WebSocketRoute` for more details and
  7829. examples.
  7830. ```py
  7831. def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  7832. if message == \"request\":
  7833. ws.send(\"response\")
  7834. def handler(ws: WebSocketRoute):
  7835. ws.on_message(lambda message: message_handler(ws, message))
  7836. page.route_web_socket(\"/ws\", handler)
  7837. ```
  7838. Parameters
  7839. ----------
  7840. url : Union[Callable[[str], bool], Pattern[str], str]
  7841. Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
  7842. `baseURL` context option.
  7843. handler : Callable[[WebSocketRoute], Any]
  7844. Handler function to route the WebSocket.
  7845. """
  7846. return mapping.from_maybe_impl(
  7847. self._sync(
  7848. self._impl_obj.route_web_socket(
  7849. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  7850. )
  7851. )
  7852. )
  7853. def unroute_all(
  7854. self,
  7855. *,
  7856. behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
  7857. ) -> None:
  7858. """Page.unroute_all
  7859. Removes all routes created with `page.route()` and `page.route_from_har()`.
  7860. Parameters
  7861. ----------
  7862. behavior : Union["default", "ignoreErrors", "wait", None]
  7863. Specifies whether to wait for already running handlers and what to do if they throw errors:
  7864. - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
  7865. result in unhandled error
  7866. - `'wait'` - wait for current handler calls (if any) to finish
  7867. - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
  7868. after unrouting are silently caught
  7869. """
  7870. return mapping.from_maybe_impl(
  7871. self._sync(self._impl_obj.unroute_all(behavior=behavior))
  7872. )
  7873. def route_from_har(
  7874. self,
  7875. har: typing.Union[pathlib.Path, str],
  7876. *,
  7877. url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  7878. not_found: typing.Optional[Literal["abort", "fallback"]] = None,
  7879. update: typing.Optional[bool] = None,
  7880. update_content: typing.Optional[Literal["attach", "embed"]] = None,
  7881. update_mode: typing.Optional[Literal["full", "minimal"]] = None,
  7882. ) -> None:
  7883. """Page.route_from_har
  7884. If specified the network requests that are made in the page will be served from the HAR file. Read more about
  7885. [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
  7886. Playwright will not serve requests intercepted by Service Worker from the HAR file. See
  7887. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  7888. using request interception by setting `serviceWorkers` to `'block'`.
  7889. Parameters
  7890. ----------
  7891. har : Union[pathlib.Path, str]
  7892. Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
  7893. relative path, then it is resolved relative to the current working directory.
  7894. url : Union[Pattern[str], str, None]
  7895. A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
  7896. pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
  7897. not_found : Union["abort", "fallback", None]
  7898. - If set to 'abort' any request not found in the HAR file will be aborted.
  7899. - If set to 'fallback' missing requests will be sent to the network.
  7900. Defaults to abort.
  7901. update : Union[bool, None]
  7902. If specified, updates the given HAR with the actual network information instead of serving from file. The file is
  7903. written to disk when `browser_context.close()` is called.
  7904. update_content : Union["attach", "embed", None]
  7905. Optional setting to control resource content management. If `attach` is specified, resources are persisted as
  7906. separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
  7907. update_mode : Union["full", "minimal", None]
  7908. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  7909. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
  7910. `minimal`.
  7911. """
  7912. return mapping.from_maybe_impl(
  7913. self._sync(
  7914. self._impl_obj.route_from_har(
  7915. har=har,
  7916. url=url,
  7917. notFound=not_found,
  7918. update=update,
  7919. updateContent=update_content,
  7920. updateMode=update_mode,
  7921. )
  7922. )
  7923. )
  7924. def screenshot(
  7925. self,
  7926. *,
  7927. timeout: typing.Optional[float] = None,
  7928. type: typing.Optional[Literal["jpeg", "png"]] = None,
  7929. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7930. quality: typing.Optional[int] = None,
  7931. omit_background: typing.Optional[bool] = None,
  7932. full_page: typing.Optional[bool] = None,
  7933. clip: typing.Optional[FloatRect] = None,
  7934. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  7935. caret: typing.Optional[Literal["hide", "initial"]] = None,
  7936. scale: typing.Optional[Literal["css", "device"]] = None,
  7937. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  7938. mask_color: typing.Optional[str] = None,
  7939. style: typing.Optional[str] = None,
  7940. ) -> bytes:
  7941. """Page.screenshot
  7942. Returns the buffer with the captured screenshot.
  7943. Parameters
  7944. ----------
  7945. timeout : Union[float, None]
  7946. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7947. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7948. type : Union["jpeg", "png", None]
  7949. Specify screenshot type, defaults to `png`.
  7950. path : Union[pathlib.Path, str, None]
  7951. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  7952. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  7953. won't be saved to the disk.
  7954. quality : Union[int, None]
  7955. The quality of the image, between 0-100. Not applicable to `png` images.
  7956. omit_background : Union[bool, None]
  7957. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  7958. Defaults to `false`.
  7959. full_page : Union[bool, None]
  7960. When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to
  7961. `false`.
  7962. clip : Union[{x: float, y: float, width: float, height: float}, None]
  7963. An object which specifies clipping of the resulting image.
  7964. animations : Union["allow", "disabled", None]
  7965. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  7966. treatment depending on their duration:
  7967. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  7968. - infinite animations are canceled to initial state, and then played over after the screenshot.
  7969. Defaults to `"allow"` that leaves animations untouched.
  7970. caret : Union["hide", "initial", None]
  7971. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  7972. changed. Defaults to `"hide"`.
  7973. scale : Union["css", "device", None]
  7974. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  7975. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  7976. screenshots of high-dpi devices will be twice as large or even larger.
  7977. Defaults to `"device"`.
  7978. mask : Union[Sequence[Locator], None]
  7979. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  7980. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  7981. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  7982. that.
  7983. mask_color : Union[str, None]
  7984. Specify the color of the overlay box for masked elements, in
  7985. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  7986. style : Union[str, None]
  7987. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  7988. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  7989. the Shadow DOM and applies to the inner frames.
  7990. Returns
  7991. -------
  7992. bytes
  7993. """
  7994. return mapping.from_maybe_impl(
  7995. self._sync(
  7996. self._impl_obj.screenshot(
  7997. timeout=timeout,
  7998. type=type,
  7999. path=path,
  8000. quality=quality,
  8001. omitBackground=omit_background,
  8002. fullPage=full_page,
  8003. clip=clip,
  8004. animations=animations,
  8005. caret=caret,
  8006. scale=scale,
  8007. mask=mapping.to_impl(mask),
  8008. maskColor=mask_color,
  8009. style=style,
  8010. )
  8011. )
  8012. )
  8013. def title(self) -> str:
  8014. """Page.title
  8015. Returns the page's title.
  8016. Returns
  8017. -------
  8018. str
  8019. """
  8020. return mapping.from_maybe_impl(self._sync(self._impl_obj.title()))
  8021. def close(
  8022. self,
  8023. *,
  8024. run_before_unload: typing.Optional[bool] = None,
  8025. reason: typing.Optional[str] = None,
  8026. ) -> None:
  8027. """Page.close
  8028. If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If
  8029. `runBeforeUnload` is `true` the method will run unload handlers, but will **not** wait for the page to close.
  8030. By default, `page.close()` **does not** run `beforeunload` handlers.
  8031. **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned and should be handled
  8032. manually via `page.on('dialog')` event.
  8033. Parameters
  8034. ----------
  8035. run_before_unload : Union[bool, None]
  8036. Defaults to `false`. Whether to run the
  8037. [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) page handlers.
  8038. reason : Union[str, None]
  8039. The reason to be reported to the operations interrupted by the page closure.
  8040. """
  8041. return mapping.from_maybe_impl(
  8042. self._sync(
  8043. self._impl_obj.close(runBeforeUnload=run_before_unload, reason=reason)
  8044. )
  8045. )
  8046. def is_closed(self) -> bool:
  8047. """Page.is_closed
  8048. Indicates that the page has been closed.
  8049. Returns
  8050. -------
  8051. bool
  8052. """
  8053. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  8054. def click(
  8055. self,
  8056. selector: str,
  8057. *,
  8058. modifiers: typing.Optional[
  8059. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8060. ] = None,
  8061. position: typing.Optional[Position] = None,
  8062. delay: typing.Optional[float] = None,
  8063. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  8064. click_count: typing.Optional[int] = None,
  8065. timeout: typing.Optional[float] = None,
  8066. force: typing.Optional[bool] = None,
  8067. no_wait_after: typing.Optional[bool] = None,
  8068. trial: typing.Optional[bool] = None,
  8069. strict: typing.Optional[bool] = None,
  8070. ) -> None:
  8071. """Page.click
  8072. This method clicks an element matching `selector` by performing the following steps:
  8073. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8074. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8075. the element is detached during the checks, the whole action is retried.
  8076. 1. Scroll the element into view if needed.
  8077. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  8078. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  8079. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8080. Passing zero timeout disables this.
  8081. Parameters
  8082. ----------
  8083. selector : str
  8084. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8085. used.
  8086. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8087. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8088. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8089. "Control" on Windows and Linux and to "Meta" on macOS.
  8090. position : Union[{x: float, y: float}, None]
  8091. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8092. the element.
  8093. delay : Union[float, None]
  8094. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  8095. button : Union["left", "middle", "right", None]
  8096. Defaults to `left`.
  8097. click_count : Union[int, None]
  8098. defaults to 1. See [UIEvent.detail].
  8099. timeout : Union[float, None]
  8100. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8101. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8102. force : Union[bool, None]
  8103. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8104. no_wait_after : Union[bool, None]
  8105. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  8106. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  8107. navigating to inaccessible pages. Defaults to `false`.
  8108. Deprecated: This option will default to `true` in the future.
  8109. trial : Union[bool, None]
  8110. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8111. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8112. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8113. are pressed.
  8114. strict : Union[bool, None]
  8115. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8116. element, the call throws an exception.
  8117. """
  8118. return mapping.from_maybe_impl(
  8119. self._sync(
  8120. self._impl_obj.click(
  8121. selector=selector,
  8122. modifiers=mapping.to_impl(modifiers),
  8123. position=position,
  8124. delay=delay,
  8125. button=button,
  8126. clickCount=click_count,
  8127. timeout=timeout,
  8128. force=force,
  8129. noWaitAfter=no_wait_after,
  8130. trial=trial,
  8131. strict=strict,
  8132. )
  8133. )
  8134. )
  8135. def dblclick(
  8136. self,
  8137. selector: str,
  8138. *,
  8139. modifiers: typing.Optional[
  8140. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8141. ] = None,
  8142. position: typing.Optional[Position] = None,
  8143. delay: typing.Optional[float] = None,
  8144. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  8145. timeout: typing.Optional[float] = None,
  8146. force: typing.Optional[bool] = None,
  8147. no_wait_after: typing.Optional[bool] = None,
  8148. strict: typing.Optional[bool] = None,
  8149. trial: typing.Optional[bool] = None,
  8150. ) -> None:
  8151. """Page.dblclick
  8152. This method double clicks an element matching `selector` by performing the following steps:
  8153. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8154. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8155. the element is detached during the checks, the whole action is retried.
  8156. 1. Scroll the element into view if needed.
  8157. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  8158. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8159. Passing zero timeout disables this.
  8160. **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
  8161. Parameters
  8162. ----------
  8163. selector : str
  8164. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8165. used.
  8166. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8167. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8168. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8169. "Control" on Windows and Linux and to "Meta" on macOS.
  8170. position : Union[{x: float, y: float}, None]
  8171. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8172. the element.
  8173. delay : Union[float, None]
  8174. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  8175. button : Union["left", "middle", "right", None]
  8176. Defaults to `left`.
  8177. timeout : Union[float, None]
  8178. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8179. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8180. force : Union[bool, None]
  8181. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8182. no_wait_after : Union[bool, None]
  8183. This option has no effect.
  8184. Deprecated: This option has no effect.
  8185. strict : Union[bool, None]
  8186. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8187. element, the call throws an exception.
  8188. trial : Union[bool, None]
  8189. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8190. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8191. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8192. are pressed.
  8193. """
  8194. return mapping.from_maybe_impl(
  8195. self._sync(
  8196. self._impl_obj.dblclick(
  8197. selector=selector,
  8198. modifiers=mapping.to_impl(modifiers),
  8199. position=position,
  8200. delay=delay,
  8201. button=button,
  8202. timeout=timeout,
  8203. force=force,
  8204. noWaitAfter=no_wait_after,
  8205. strict=strict,
  8206. trial=trial,
  8207. )
  8208. )
  8209. )
  8210. def tap(
  8211. self,
  8212. selector: str,
  8213. *,
  8214. modifiers: typing.Optional[
  8215. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8216. ] = None,
  8217. position: typing.Optional[Position] = None,
  8218. timeout: typing.Optional[float] = None,
  8219. force: typing.Optional[bool] = None,
  8220. no_wait_after: typing.Optional[bool] = None,
  8221. strict: typing.Optional[bool] = None,
  8222. trial: typing.Optional[bool] = None,
  8223. ) -> None:
  8224. """Page.tap
  8225. This method taps an element matching `selector` by performing the following steps:
  8226. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8227. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8228. the element is detached during the checks, the whole action is retried.
  8229. 1. Scroll the element into view if needed.
  8230. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  8231. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8232. Passing zero timeout disables this.
  8233. **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
  8234. Parameters
  8235. ----------
  8236. selector : str
  8237. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8238. used.
  8239. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8240. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8241. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8242. "Control" on Windows and Linux and to "Meta" on macOS.
  8243. position : Union[{x: float, y: float}, None]
  8244. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8245. the element.
  8246. timeout : Union[float, None]
  8247. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8248. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8249. force : Union[bool, None]
  8250. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8251. no_wait_after : Union[bool, None]
  8252. This option has no effect.
  8253. Deprecated: This option has no effect.
  8254. strict : Union[bool, None]
  8255. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8256. element, the call throws an exception.
  8257. trial : Union[bool, None]
  8258. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8259. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8260. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8261. are pressed.
  8262. """
  8263. return mapping.from_maybe_impl(
  8264. self._sync(
  8265. self._impl_obj.tap(
  8266. selector=selector,
  8267. modifiers=mapping.to_impl(modifiers),
  8268. position=position,
  8269. timeout=timeout,
  8270. force=force,
  8271. noWaitAfter=no_wait_after,
  8272. strict=strict,
  8273. trial=trial,
  8274. )
  8275. )
  8276. )
  8277. def fill(
  8278. self,
  8279. selector: str,
  8280. value: str,
  8281. *,
  8282. timeout: typing.Optional[float] = None,
  8283. no_wait_after: typing.Optional[bool] = None,
  8284. strict: typing.Optional[bool] = None,
  8285. force: typing.Optional[bool] = None,
  8286. ) -> None:
  8287. """Page.fill
  8288. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
  8289. focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
  8290. to clear the input field.
  8291. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  8292. error. However, if the element is inside the `<label>` element that has an associated
  8293. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  8294. instead.
  8295. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  8296. Parameters
  8297. ----------
  8298. selector : str
  8299. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8300. used.
  8301. value : str
  8302. Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
  8303. timeout : Union[float, None]
  8304. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8305. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8306. no_wait_after : Union[bool, None]
  8307. This option has no effect.
  8308. Deprecated: This option has no effect.
  8309. strict : Union[bool, None]
  8310. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8311. element, the call throws an exception.
  8312. force : Union[bool, None]
  8313. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8314. """
  8315. return mapping.from_maybe_impl(
  8316. self._sync(
  8317. self._impl_obj.fill(
  8318. selector=selector,
  8319. value=value,
  8320. timeout=timeout,
  8321. noWaitAfter=no_wait_after,
  8322. strict=strict,
  8323. force=force,
  8324. )
  8325. )
  8326. )
  8327. def locator(
  8328. self,
  8329. selector: str,
  8330. *,
  8331. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8332. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8333. has: typing.Optional["Locator"] = None,
  8334. has_not: typing.Optional["Locator"] = None,
  8335. ) -> "Locator":
  8336. """Page.locator
  8337. The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
  8338. to the element immediately before performing an action, so a series of actions on the same locator can in fact be
  8339. performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
  8340. [Learn more about locators](https://playwright.dev/python/docs/locators).
  8341. Parameters
  8342. ----------
  8343. selector : str
  8344. A selector to use when resolving DOM element.
  8345. has_text : Union[Pattern[str], str, None]
  8346. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  8347. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  8348. `<article><div>Playwright</div></article>`.
  8349. has_not_text : Union[Pattern[str], str, None]
  8350. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  8351. When passed a [string], matching is case-insensitive and searches for a substring.
  8352. has : Union[Locator, None]
  8353. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  8354. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  8355. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  8356. the document root. For example, you can find `content` that has `div` in
  8357. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  8358. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  8359. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  8360. has_not : Union[Locator, None]
  8361. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  8362. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  8363. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  8364. Returns
  8365. -------
  8366. Locator
  8367. """
  8368. return mapping.from_impl(
  8369. self._impl_obj.locator(
  8370. selector=selector,
  8371. hasText=has_text,
  8372. hasNotText=has_not_text,
  8373. has=has._impl_obj if has else None,
  8374. hasNot=has_not._impl_obj if has_not else None,
  8375. )
  8376. )
  8377. def get_by_alt_text(
  8378. self,
  8379. text: typing.Union[str, typing.Pattern[str]],
  8380. *,
  8381. exact: typing.Optional[bool] = None,
  8382. ) -> "Locator":
  8383. """Page.get_by_alt_text
  8384. Allows locating elements by their alt text.
  8385. **Usage**
  8386. For example, this method will find the image by alt text \"Playwright logo\":
  8387. ```html
  8388. <img alt='Playwright logo'>
  8389. ```
  8390. ```py
  8391. page.get_by_alt_text(\"Playwright logo\").click()
  8392. ```
  8393. Parameters
  8394. ----------
  8395. text : Union[Pattern[str], str]
  8396. Text to locate the element for.
  8397. exact : Union[bool, None]
  8398. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8399. regular expression. Note that exact match still trims whitespace.
  8400. Returns
  8401. -------
  8402. Locator
  8403. """
  8404. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  8405. def get_by_label(
  8406. self,
  8407. text: typing.Union[str, typing.Pattern[str]],
  8408. *,
  8409. exact: typing.Optional[bool] = None,
  8410. ) -> "Locator":
  8411. """Page.get_by_label
  8412. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  8413. `aria-label` attribute.
  8414. **Usage**
  8415. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  8416. ```html
  8417. <input aria-label=\"Username\">
  8418. <label for=\"password-input\">Password:</label>
  8419. <input id=\"password-input\">
  8420. ```
  8421. ```py
  8422. page.get_by_label(\"Username\").fill(\"john\")
  8423. page.get_by_label(\"Password\").fill(\"secret\")
  8424. ```
  8425. Parameters
  8426. ----------
  8427. text : Union[Pattern[str], str]
  8428. Text to locate the element for.
  8429. exact : Union[bool, None]
  8430. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8431. regular expression. Note that exact match still trims whitespace.
  8432. Returns
  8433. -------
  8434. Locator
  8435. """
  8436. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  8437. def get_by_placeholder(
  8438. self,
  8439. text: typing.Union[str, typing.Pattern[str]],
  8440. *,
  8441. exact: typing.Optional[bool] = None,
  8442. ) -> "Locator":
  8443. """Page.get_by_placeholder
  8444. Allows locating input elements by the placeholder text.
  8445. **Usage**
  8446. For example, consider the following DOM structure.
  8447. ```html
  8448. <input type=\"email\" placeholder=\"name@example.com\" />
  8449. ```
  8450. You can fill the input after locating it by the placeholder text:
  8451. ```py
  8452. page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  8453. ```
  8454. Parameters
  8455. ----------
  8456. text : Union[Pattern[str], str]
  8457. Text to locate the element for.
  8458. exact : Union[bool, None]
  8459. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8460. regular expression. Note that exact match still trims whitespace.
  8461. Returns
  8462. -------
  8463. Locator
  8464. """
  8465. return mapping.from_impl(
  8466. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  8467. )
  8468. def get_by_role(
  8469. self,
  8470. role: Literal[
  8471. "alert",
  8472. "alertdialog",
  8473. "application",
  8474. "article",
  8475. "banner",
  8476. "blockquote",
  8477. "button",
  8478. "caption",
  8479. "cell",
  8480. "checkbox",
  8481. "code",
  8482. "columnheader",
  8483. "combobox",
  8484. "complementary",
  8485. "contentinfo",
  8486. "definition",
  8487. "deletion",
  8488. "dialog",
  8489. "directory",
  8490. "document",
  8491. "emphasis",
  8492. "feed",
  8493. "figure",
  8494. "form",
  8495. "generic",
  8496. "grid",
  8497. "gridcell",
  8498. "group",
  8499. "heading",
  8500. "img",
  8501. "insertion",
  8502. "link",
  8503. "list",
  8504. "listbox",
  8505. "listitem",
  8506. "log",
  8507. "main",
  8508. "marquee",
  8509. "math",
  8510. "menu",
  8511. "menubar",
  8512. "menuitem",
  8513. "menuitemcheckbox",
  8514. "menuitemradio",
  8515. "meter",
  8516. "navigation",
  8517. "none",
  8518. "note",
  8519. "option",
  8520. "paragraph",
  8521. "presentation",
  8522. "progressbar",
  8523. "radio",
  8524. "radiogroup",
  8525. "region",
  8526. "row",
  8527. "rowgroup",
  8528. "rowheader",
  8529. "scrollbar",
  8530. "search",
  8531. "searchbox",
  8532. "separator",
  8533. "slider",
  8534. "spinbutton",
  8535. "status",
  8536. "strong",
  8537. "subscript",
  8538. "superscript",
  8539. "switch",
  8540. "tab",
  8541. "table",
  8542. "tablist",
  8543. "tabpanel",
  8544. "term",
  8545. "textbox",
  8546. "time",
  8547. "timer",
  8548. "toolbar",
  8549. "tooltip",
  8550. "tree",
  8551. "treegrid",
  8552. "treeitem",
  8553. ],
  8554. *,
  8555. checked: typing.Optional[bool] = None,
  8556. disabled: typing.Optional[bool] = None,
  8557. expanded: typing.Optional[bool] = None,
  8558. include_hidden: typing.Optional[bool] = None,
  8559. level: typing.Optional[int] = None,
  8560. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8561. pressed: typing.Optional[bool] = None,
  8562. selected: typing.Optional[bool] = None,
  8563. exact: typing.Optional[bool] = None,
  8564. ) -> "Locator":
  8565. """Page.get_by_role
  8566. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  8567. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  8568. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  8569. **Usage**
  8570. Consider the following DOM structure.
  8571. ```html
  8572. <h3>Sign up</h3>
  8573. <label>
  8574. <input type=\"checkbox\" /> Subscribe
  8575. </label>
  8576. <br/>
  8577. <button>Submit</button>
  8578. ```
  8579. You can locate each element by it's implicit role:
  8580. ```py
  8581. expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  8582. page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  8583. page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  8584. ```
  8585. **Details**
  8586. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  8587. about the ARIA guidelines.
  8588. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  8589. that is recognized by the role selector. You can find all the
  8590. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  8591. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  8592. Parameters
  8593. ----------
  8594. role : Union["alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"]
  8595. Required aria role.
  8596. checked : Union[bool, None]
  8597. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  8598. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  8599. disabled : Union[bool, None]
  8600. An attribute that is usually set by `aria-disabled` or `disabled`.
  8601. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  8602. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  8603. expanded : Union[bool, None]
  8604. An attribute that is usually set by `aria-expanded`.
  8605. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  8606. include_hidden : Union[bool, None]
  8607. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  8608. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  8609. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  8610. level : Union[int, None]
  8611. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  8612. for `<h1>-<h6>` elements.
  8613. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  8614. name : Union[Pattern[str], str, None]
  8615. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  8616. case-insensitive and searches for a substring, use `exact` to control this behavior.
  8617. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  8618. pressed : Union[bool, None]
  8619. An attribute that is usually set by `aria-pressed`.
  8620. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  8621. selected : Union[bool, None]
  8622. An attribute that is usually set by `aria-selected`.
  8623. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  8624. exact : Union[bool, None]
  8625. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  8626. regular expression. Note that exact match still trims whitespace.
  8627. Returns
  8628. -------
  8629. Locator
  8630. """
  8631. return mapping.from_impl(
  8632. self._impl_obj.get_by_role(
  8633. role=role,
  8634. checked=checked,
  8635. disabled=disabled,
  8636. expanded=expanded,
  8637. includeHidden=include_hidden,
  8638. level=level,
  8639. name=name,
  8640. pressed=pressed,
  8641. selected=selected,
  8642. exact=exact,
  8643. )
  8644. )
  8645. def get_by_test_id(
  8646. self, test_id: typing.Union[str, typing.Pattern[str]]
  8647. ) -> "Locator":
  8648. """Page.get_by_test_id
  8649. Locate element by the test id.
  8650. **Usage**
  8651. Consider the following DOM structure.
  8652. ```html
  8653. <button data-testid=\"directions\">Itinéraire</button>
  8654. ```
  8655. You can locate the element by it's test id:
  8656. ```py
  8657. page.get_by_test_id(\"directions\").click()
  8658. ```
  8659. **Details**
  8660. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  8661. configure a different test id attribute if necessary.
  8662. Parameters
  8663. ----------
  8664. test_id : Union[Pattern[str], str]
  8665. Id to locate the element by.
  8666. Returns
  8667. -------
  8668. Locator
  8669. """
  8670. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  8671. def get_by_text(
  8672. self,
  8673. text: typing.Union[str, typing.Pattern[str]],
  8674. *,
  8675. exact: typing.Optional[bool] = None,
  8676. ) -> "Locator":
  8677. """Page.get_by_text
  8678. Allows locating elements that contain given text.
  8679. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  8680. filter by the text content.
  8681. **Usage**
  8682. Consider the following DOM structure:
  8683. ```html
  8684. <div>Hello <span>world</span></div>
  8685. <div>Hello</div>
  8686. ```
  8687. You can locate by text substring, exact string, or a regular expression:
  8688. ```py
  8689. # Matches <span>
  8690. page.get_by_text(\"world\")
  8691. # Matches first <div>
  8692. page.get_by_text(\"Hello world\")
  8693. # Matches second <div>
  8694. page.get_by_text(\"Hello\", exact=True)
  8695. # Matches both <div>s
  8696. page.get_by_text(re.compile(\"Hello\"))
  8697. # Matches second <div>
  8698. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  8699. ```
  8700. **Details**
  8701. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  8702. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  8703. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  8704. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  8705. Parameters
  8706. ----------
  8707. text : Union[Pattern[str], str]
  8708. Text to locate the element for.
  8709. exact : Union[bool, None]
  8710. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8711. regular expression. Note that exact match still trims whitespace.
  8712. Returns
  8713. -------
  8714. Locator
  8715. """
  8716. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  8717. def get_by_title(
  8718. self,
  8719. text: typing.Union[str, typing.Pattern[str]],
  8720. *,
  8721. exact: typing.Optional[bool] = None,
  8722. ) -> "Locator":
  8723. """Page.get_by_title
  8724. Allows locating elements by their title attribute.
  8725. **Usage**
  8726. Consider the following DOM structure.
  8727. ```html
  8728. <span title='Issues count'>25 issues</span>
  8729. ```
  8730. You can check the issues count after locating it by the title text:
  8731. ```py
  8732. expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  8733. ```
  8734. Parameters
  8735. ----------
  8736. text : Union[Pattern[str], str]
  8737. Text to locate the element for.
  8738. exact : Union[bool, None]
  8739. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8740. regular expression. Note that exact match still trims whitespace.
  8741. Returns
  8742. -------
  8743. Locator
  8744. """
  8745. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  8746. def frame_locator(self, selector: str) -> "FrameLocator":
  8747. """Page.frame_locator
  8748. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  8749. in that iframe.
  8750. **Usage**
  8751. Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
  8752. id=\"my-frame\">`:
  8753. ```py
  8754. locator = page.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
  8755. locator.click()
  8756. ```
  8757. Parameters
  8758. ----------
  8759. selector : str
  8760. A selector to use when resolving DOM element.
  8761. Returns
  8762. -------
  8763. FrameLocator
  8764. """
  8765. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  8766. def focus(
  8767. self,
  8768. selector: str,
  8769. *,
  8770. strict: typing.Optional[bool] = None,
  8771. timeout: typing.Optional[float] = None,
  8772. ) -> None:
  8773. """Page.focus
  8774. This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
  8775. method waits until a matching element appears in the DOM.
  8776. Parameters
  8777. ----------
  8778. selector : str
  8779. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8780. used.
  8781. strict : Union[bool, None]
  8782. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8783. element, the call throws an exception.
  8784. timeout : Union[float, None]
  8785. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8786. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8787. """
  8788. return mapping.from_maybe_impl(
  8789. self._sync(
  8790. self._impl_obj.focus(selector=selector, strict=strict, timeout=timeout)
  8791. )
  8792. )
  8793. def text_content(
  8794. self,
  8795. selector: str,
  8796. *,
  8797. strict: typing.Optional[bool] = None,
  8798. timeout: typing.Optional[float] = None,
  8799. ) -> typing.Optional[str]:
  8800. """Page.text_content
  8801. Returns `element.textContent`.
  8802. Parameters
  8803. ----------
  8804. selector : str
  8805. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8806. used.
  8807. strict : Union[bool, None]
  8808. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8809. element, the call throws an exception.
  8810. timeout : Union[float, None]
  8811. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8812. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8813. Returns
  8814. -------
  8815. Union[str, None]
  8816. """
  8817. return mapping.from_maybe_impl(
  8818. self._sync(
  8819. self._impl_obj.text_content(
  8820. selector=selector, strict=strict, timeout=timeout
  8821. )
  8822. )
  8823. )
  8824. def inner_text(
  8825. self,
  8826. selector: str,
  8827. *,
  8828. strict: typing.Optional[bool] = None,
  8829. timeout: typing.Optional[float] = None,
  8830. ) -> str:
  8831. """Page.inner_text
  8832. Returns `element.innerText`.
  8833. Parameters
  8834. ----------
  8835. selector : str
  8836. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8837. used.
  8838. strict : Union[bool, None]
  8839. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8840. element, the call throws an exception.
  8841. timeout : Union[float, None]
  8842. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8843. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8844. Returns
  8845. -------
  8846. str
  8847. """
  8848. return mapping.from_maybe_impl(
  8849. self._sync(
  8850. self._impl_obj.inner_text(
  8851. selector=selector, strict=strict, timeout=timeout
  8852. )
  8853. )
  8854. )
  8855. def inner_html(
  8856. self,
  8857. selector: str,
  8858. *,
  8859. strict: typing.Optional[bool] = None,
  8860. timeout: typing.Optional[float] = None,
  8861. ) -> str:
  8862. """Page.inner_html
  8863. Returns `element.innerHTML`.
  8864. Parameters
  8865. ----------
  8866. selector : str
  8867. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8868. used.
  8869. strict : Union[bool, None]
  8870. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8871. element, the call throws an exception.
  8872. timeout : Union[float, None]
  8873. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8874. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8875. Returns
  8876. -------
  8877. str
  8878. """
  8879. return mapping.from_maybe_impl(
  8880. self._sync(
  8881. self._impl_obj.inner_html(
  8882. selector=selector, strict=strict, timeout=timeout
  8883. )
  8884. )
  8885. )
  8886. def get_attribute(
  8887. self,
  8888. selector: str,
  8889. name: str,
  8890. *,
  8891. strict: typing.Optional[bool] = None,
  8892. timeout: typing.Optional[float] = None,
  8893. ) -> typing.Optional[str]:
  8894. """Page.get_attribute
  8895. Returns element attribute value.
  8896. Parameters
  8897. ----------
  8898. selector : str
  8899. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8900. used.
  8901. name : str
  8902. Attribute name to get the value for.
  8903. strict : Union[bool, None]
  8904. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8905. element, the call throws an exception.
  8906. timeout : Union[float, None]
  8907. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8908. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8909. Returns
  8910. -------
  8911. Union[str, None]
  8912. """
  8913. return mapping.from_maybe_impl(
  8914. self._sync(
  8915. self._impl_obj.get_attribute(
  8916. selector=selector, name=name, strict=strict, timeout=timeout
  8917. )
  8918. )
  8919. )
  8920. def hover(
  8921. self,
  8922. selector: str,
  8923. *,
  8924. modifiers: typing.Optional[
  8925. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8926. ] = None,
  8927. position: typing.Optional[Position] = None,
  8928. timeout: typing.Optional[float] = None,
  8929. no_wait_after: typing.Optional[bool] = None,
  8930. force: typing.Optional[bool] = None,
  8931. strict: typing.Optional[bool] = None,
  8932. trial: typing.Optional[bool] = None,
  8933. ) -> None:
  8934. """Page.hover
  8935. This method hovers over an element matching `selector` by performing the following steps:
  8936. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8937. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8938. the element is detached during the checks, the whole action is retried.
  8939. 1. Scroll the element into view if needed.
  8940. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  8941. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8942. Passing zero timeout disables this.
  8943. Parameters
  8944. ----------
  8945. selector : str
  8946. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8947. used.
  8948. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8949. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8950. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8951. "Control" on Windows and Linux and to "Meta" on macOS.
  8952. position : Union[{x: float, y: float}, None]
  8953. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8954. the element.
  8955. timeout : Union[float, None]
  8956. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8957. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8958. no_wait_after : Union[bool, None]
  8959. This option has no effect.
  8960. Deprecated: This option has no effect.
  8961. force : Union[bool, None]
  8962. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8963. strict : Union[bool, None]
  8964. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8965. element, the call throws an exception.
  8966. trial : Union[bool, None]
  8967. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8968. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8969. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8970. are pressed.
  8971. """
  8972. return mapping.from_maybe_impl(
  8973. self._sync(
  8974. self._impl_obj.hover(
  8975. selector=selector,
  8976. modifiers=mapping.to_impl(modifiers),
  8977. position=position,
  8978. timeout=timeout,
  8979. noWaitAfter=no_wait_after,
  8980. force=force,
  8981. strict=strict,
  8982. trial=trial,
  8983. )
  8984. )
  8985. )
  8986. def drag_and_drop(
  8987. self,
  8988. source: str,
  8989. target: str,
  8990. *,
  8991. source_position: typing.Optional[Position] = None,
  8992. target_position: typing.Optional[Position] = None,
  8993. force: typing.Optional[bool] = None,
  8994. no_wait_after: typing.Optional[bool] = None,
  8995. timeout: typing.Optional[float] = None,
  8996. strict: typing.Optional[bool] = None,
  8997. trial: typing.Optional[bool] = None,
  8998. steps: typing.Optional[int] = None,
  8999. ) -> None:
  9000. """Page.drag_and_drop
  9001. This method drags the source element to the target element. It will first move to the source element, perform a
  9002. `mousedown`, then move to the target element and perform a `mouseup`.
  9003. **Usage**
  9004. ```py
  9005. page.drag_and_drop(\"#source\", \"#target\")
  9006. # or specify exact positions relative to the top-left corners of the elements:
  9007. page.drag_and_drop(
  9008. \"#source\",
  9009. \"#target\",
  9010. source_position={\"x\": 34, \"y\": 7},
  9011. target_position={\"x\": 10, \"y\": 20}
  9012. )
  9013. ```
  9014. Parameters
  9015. ----------
  9016. source : str
  9017. A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
  9018. be used.
  9019. target : str
  9020. A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
  9021. will be used.
  9022. source_position : Union[{x: float, y: float}, None]
  9023. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  9024. specified, some visible point of the element is used.
  9025. target_position : Union[{x: float, y: float}, None]
  9026. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  9027. specified, some visible point of the element is used.
  9028. force : Union[bool, None]
  9029. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9030. no_wait_after : Union[bool, None]
  9031. This option has no effect.
  9032. Deprecated: This option has no effect.
  9033. timeout : Union[float, None]
  9034. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9035. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9036. strict : Union[bool, None]
  9037. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9038. element, the call throws an exception.
  9039. trial : Union[bool, None]
  9040. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9041. to `false`. Useful to wait until the element is ready for the action without performing it.
  9042. steps : Union[int, None]
  9043. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  9044. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  9045. """
  9046. return mapping.from_maybe_impl(
  9047. self._sync(
  9048. self._impl_obj.drag_and_drop(
  9049. source=source,
  9050. target=target,
  9051. sourcePosition=source_position,
  9052. targetPosition=target_position,
  9053. force=force,
  9054. noWaitAfter=no_wait_after,
  9055. timeout=timeout,
  9056. strict=strict,
  9057. trial=trial,
  9058. steps=steps,
  9059. )
  9060. )
  9061. )
  9062. def select_option(
  9063. self,
  9064. selector: str,
  9065. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  9066. *,
  9067. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  9068. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  9069. element: typing.Optional[
  9070. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  9071. ] = None,
  9072. timeout: typing.Optional[float] = None,
  9073. no_wait_after: typing.Optional[bool] = None,
  9074. force: typing.Optional[bool] = None,
  9075. strict: typing.Optional[bool] = None,
  9076. ) -> typing.List[str]:
  9077. """Page.select_option
  9078. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
  9079. until all specified options are present in the `<select>` element and selects these options.
  9080. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  9081. the `<label>` element that has an associated
  9082. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  9083. instead.
  9084. Returns the array of option values that have been successfully selected.
  9085. Triggers a `change` and `input` event once all the provided options have been selected.
  9086. **Usage**
  9087. ```py
  9088. # Single selection matching the value or label
  9089. page.select_option(\"select#colors\", \"blue\")
  9090. # single selection matching both the label
  9091. page.select_option(\"select#colors\", label=\"blue\")
  9092. # multiple selection
  9093. page.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
  9094. ```
  9095. Parameters
  9096. ----------
  9097. selector : str
  9098. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9099. used.
  9100. value : Union[Sequence[str], str, None]
  9101. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  9102. otherwise only the first option matching one of the passed options is selected. Optional.
  9103. index : Union[Sequence[int], int, None]
  9104. Options to select by index. Optional.
  9105. label : Union[Sequence[str], str, None]
  9106. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  9107. otherwise only the first option matching one of the passed options is selected. Optional.
  9108. element : Union[ElementHandle, Sequence[ElementHandle], None]
  9109. Option elements to select. Optional.
  9110. timeout : Union[float, None]
  9111. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9112. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9113. no_wait_after : Union[bool, None]
  9114. This option has no effect.
  9115. Deprecated: This option has no effect.
  9116. force : Union[bool, None]
  9117. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9118. strict : Union[bool, None]
  9119. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9120. element, the call throws an exception.
  9121. Returns
  9122. -------
  9123. List[str]
  9124. """
  9125. return mapping.from_maybe_impl(
  9126. self._sync(
  9127. self._impl_obj.select_option(
  9128. selector=selector,
  9129. value=mapping.to_impl(value),
  9130. index=mapping.to_impl(index),
  9131. label=mapping.to_impl(label),
  9132. element=mapping.to_impl(element),
  9133. timeout=timeout,
  9134. noWaitAfter=no_wait_after,
  9135. force=force,
  9136. strict=strict,
  9137. )
  9138. )
  9139. )
  9140. def input_value(
  9141. self,
  9142. selector: str,
  9143. *,
  9144. strict: typing.Optional[bool] = None,
  9145. timeout: typing.Optional[float] = None,
  9146. ) -> str:
  9147. """Page.input_value
  9148. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  9149. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  9150. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  9151. control.
  9152. Parameters
  9153. ----------
  9154. selector : str
  9155. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9156. used.
  9157. strict : Union[bool, None]
  9158. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9159. element, the call throws an exception.
  9160. timeout : Union[float, None]
  9161. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9162. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9163. Returns
  9164. -------
  9165. str
  9166. """
  9167. return mapping.from_maybe_impl(
  9168. self._sync(
  9169. self._impl_obj.input_value(
  9170. selector=selector, strict=strict, timeout=timeout
  9171. )
  9172. )
  9173. )
  9174. def set_input_files(
  9175. self,
  9176. selector: str,
  9177. files: typing.Union[
  9178. str,
  9179. pathlib.Path,
  9180. FilePayload,
  9181. typing.Sequence[typing.Union[str, pathlib.Path]],
  9182. typing.Sequence[FilePayload],
  9183. ],
  9184. *,
  9185. timeout: typing.Optional[float] = None,
  9186. strict: typing.Optional[bool] = None,
  9187. no_wait_after: typing.Optional[bool] = None,
  9188. ) -> None:
  9189. """Page.set_input_files
  9190. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  9191. they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
  9192. with a `[webkitdirectory]` attribute, only a single directory path is supported.
  9193. This method expects `selector` to point to an
  9194. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  9195. the `<label>` element that has an associated
  9196. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  9197. Parameters
  9198. ----------
  9199. selector : str
  9200. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9201. used.
  9202. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  9203. timeout : Union[float, None]
  9204. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9205. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9206. strict : Union[bool, None]
  9207. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9208. element, the call throws an exception.
  9209. no_wait_after : Union[bool, None]
  9210. This option has no effect.
  9211. Deprecated: This option has no effect.
  9212. """
  9213. return mapping.from_maybe_impl(
  9214. self._sync(
  9215. self._impl_obj.set_input_files(
  9216. selector=selector,
  9217. files=mapping.to_impl(files),
  9218. timeout=timeout,
  9219. strict=strict,
  9220. noWaitAfter=no_wait_after,
  9221. )
  9222. )
  9223. )
  9224. def type(
  9225. self,
  9226. selector: str,
  9227. text: str,
  9228. *,
  9229. delay: typing.Optional[float] = None,
  9230. timeout: typing.Optional[float] = None,
  9231. no_wait_after: typing.Optional[bool] = None,
  9232. strict: typing.Optional[bool] = None,
  9233. ) -> None:
  9234. """Page.type
  9235. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to
  9236. send fine-grained keyboard events. To fill values in form fields, use `page.fill()`.
  9237. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  9238. **Usage**
  9239. Parameters
  9240. ----------
  9241. selector : str
  9242. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9243. used.
  9244. text : str
  9245. A text to type into a focused element.
  9246. delay : Union[float, None]
  9247. Time to wait between key presses in milliseconds. Defaults to 0.
  9248. timeout : Union[float, None]
  9249. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9250. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9251. no_wait_after : Union[bool, None]
  9252. This option has no effect.
  9253. Deprecated: This option has no effect.
  9254. strict : Union[bool, None]
  9255. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9256. element, the call throws an exception.
  9257. """
  9258. return mapping.from_maybe_impl(
  9259. self._sync(
  9260. self._impl_obj.type(
  9261. selector=selector,
  9262. text=text,
  9263. delay=delay,
  9264. timeout=timeout,
  9265. noWaitAfter=no_wait_after,
  9266. strict=strict,
  9267. )
  9268. )
  9269. )
  9270. def press(
  9271. self,
  9272. selector: str,
  9273. key: str,
  9274. *,
  9275. delay: typing.Optional[float] = None,
  9276. timeout: typing.Optional[float] = None,
  9277. no_wait_after: typing.Optional[bool] = None,
  9278. strict: typing.Optional[bool] = None,
  9279. ) -> None:
  9280. """Page.press
  9281. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  9282. `key` can specify the intended
  9283. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  9284. to generate the text for. A superset of the `key` values can be found
  9285. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  9286. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  9287. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  9288. etc.
  9289. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  9290. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  9291. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  9292. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  9293. texts.
  9294. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  9295. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  9296. **Usage**
  9297. ```py
  9298. page = browser.new_page()
  9299. page.goto(\"https://keycode.info\")
  9300. page.press(\"body\", \"A\")
  9301. page.screenshot(path=\"a.png\")
  9302. page.press(\"body\", \"ArrowLeft\")
  9303. page.screenshot(path=\"arrow_left.png\")
  9304. page.press(\"body\", \"Shift+O\")
  9305. page.screenshot(path=\"o.png\")
  9306. browser.close()
  9307. ```
  9308. Parameters
  9309. ----------
  9310. selector : str
  9311. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9312. used.
  9313. key : str
  9314. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  9315. delay : Union[float, None]
  9316. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  9317. timeout : Union[float, None]
  9318. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9319. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9320. no_wait_after : Union[bool, None]
  9321. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  9322. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  9323. navigating to inaccessible pages. Defaults to `false`.
  9324. Deprecated: This option will default to `true` in the future.
  9325. strict : Union[bool, None]
  9326. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9327. element, the call throws an exception.
  9328. """
  9329. return mapping.from_maybe_impl(
  9330. self._sync(
  9331. self._impl_obj.press(
  9332. selector=selector,
  9333. key=key,
  9334. delay=delay,
  9335. timeout=timeout,
  9336. noWaitAfter=no_wait_after,
  9337. strict=strict,
  9338. )
  9339. )
  9340. )
  9341. def check(
  9342. self,
  9343. selector: str,
  9344. *,
  9345. position: typing.Optional[Position] = None,
  9346. timeout: typing.Optional[float] = None,
  9347. force: typing.Optional[bool] = None,
  9348. no_wait_after: typing.Optional[bool] = None,
  9349. strict: typing.Optional[bool] = None,
  9350. trial: typing.Optional[bool] = None,
  9351. ) -> None:
  9352. """Page.check
  9353. This method checks an element matching `selector` by performing the following steps:
  9354. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9355. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  9356. already checked, this method returns immediately.
  9357. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9358. the element is detached during the checks, the whole action is retried.
  9359. 1. Scroll the element into view if needed.
  9360. 1. Use `page.mouse` to click in the center of the element.
  9361. 1. Ensure that the element is now checked. If not, this method throws.
  9362. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9363. Passing zero timeout disables this.
  9364. Parameters
  9365. ----------
  9366. selector : str
  9367. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9368. used.
  9369. position : Union[{x: float, y: float}, None]
  9370. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9371. the element.
  9372. timeout : Union[float, None]
  9373. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9374. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9375. force : Union[bool, None]
  9376. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9377. no_wait_after : Union[bool, None]
  9378. This option has no effect.
  9379. Deprecated: This option has no effect.
  9380. strict : Union[bool, None]
  9381. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9382. element, the call throws an exception.
  9383. trial : Union[bool, None]
  9384. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9385. to `false`. Useful to wait until the element is ready for the action without performing it.
  9386. """
  9387. return mapping.from_maybe_impl(
  9388. self._sync(
  9389. self._impl_obj.check(
  9390. selector=selector,
  9391. position=position,
  9392. timeout=timeout,
  9393. force=force,
  9394. noWaitAfter=no_wait_after,
  9395. strict=strict,
  9396. trial=trial,
  9397. )
  9398. )
  9399. )
  9400. def uncheck(
  9401. self,
  9402. selector: str,
  9403. *,
  9404. position: typing.Optional[Position] = None,
  9405. timeout: typing.Optional[float] = None,
  9406. force: typing.Optional[bool] = None,
  9407. no_wait_after: typing.Optional[bool] = None,
  9408. strict: typing.Optional[bool] = None,
  9409. trial: typing.Optional[bool] = None,
  9410. ) -> None:
  9411. """Page.uncheck
  9412. This method unchecks an element matching `selector` by performing the following steps:
  9413. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9414. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  9415. already unchecked, this method returns immediately.
  9416. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9417. the element is detached during the checks, the whole action is retried.
  9418. 1. Scroll the element into view if needed.
  9419. 1. Use `page.mouse` to click in the center of the element.
  9420. 1. Ensure that the element is now unchecked. If not, this method throws.
  9421. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9422. Passing zero timeout disables this.
  9423. Parameters
  9424. ----------
  9425. selector : str
  9426. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9427. used.
  9428. position : Union[{x: float, y: float}, None]
  9429. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9430. the element.
  9431. timeout : Union[float, None]
  9432. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9433. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9434. force : Union[bool, None]
  9435. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9436. no_wait_after : Union[bool, None]
  9437. This option has no effect.
  9438. Deprecated: This option has no effect.
  9439. strict : Union[bool, None]
  9440. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9441. element, the call throws an exception.
  9442. trial : Union[bool, None]
  9443. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9444. to `false`. Useful to wait until the element is ready for the action without performing it.
  9445. """
  9446. return mapping.from_maybe_impl(
  9447. self._sync(
  9448. self._impl_obj.uncheck(
  9449. selector=selector,
  9450. position=position,
  9451. timeout=timeout,
  9452. force=force,
  9453. noWaitAfter=no_wait_after,
  9454. strict=strict,
  9455. trial=trial,
  9456. )
  9457. )
  9458. )
  9459. def wait_for_timeout(self, timeout: float) -> None:
  9460. """Page.wait_for_timeout
  9461. Waits for the given `timeout` in milliseconds.
  9462. Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
  9463. to be flaky. Use signals such as network events, selectors becoming visible and others instead.
  9464. **Usage**
  9465. ```py
  9466. # wait for 1 second
  9467. page.wait_for_timeout(1000)
  9468. ```
  9469. Parameters
  9470. ----------
  9471. timeout : float
  9472. A timeout to wait for
  9473. """
  9474. return mapping.from_maybe_impl(
  9475. self._sync(self._impl_obj.wait_for_timeout(timeout=timeout))
  9476. )
  9477. def wait_for_function(
  9478. self,
  9479. expression: str,
  9480. *,
  9481. arg: typing.Optional[typing.Any] = None,
  9482. timeout: typing.Optional[float] = None,
  9483. polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
  9484. ) -> "JSHandle":
  9485. """Page.wait_for_function
  9486. Returns when the `expression` returns a truthy value. It resolves to a JSHandle of the truthy value.
  9487. **Usage**
  9488. The `page.wait_for_function()` can be used to observe viewport size change:
  9489. ```py
  9490. from playwright.sync_api import sync_playwright, Playwright
  9491. def run(playwright: Playwright):
  9492. webkit = playwright.webkit
  9493. browser = webkit.launch()
  9494. page = browser.new_page()
  9495. page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
  9496. page.wait_for_function(\"() => window.x > 0\")
  9497. browser.close()
  9498. with sync_playwright() as playwright:
  9499. run(playwright)
  9500. ```
  9501. To pass an argument to the predicate of `page.wait_for_function()` function:
  9502. ```py
  9503. selector = \".foo\"
  9504. page.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
  9505. ```
  9506. Parameters
  9507. ----------
  9508. expression : str
  9509. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  9510. function is automatically invoked.
  9511. arg : Union[Any, None]
  9512. Optional argument to pass to `expression`.
  9513. timeout : Union[float, None]
  9514. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9515. default value can be changed by using the `browser_context.set_default_timeout()` or
  9516. `page.set_default_timeout()` methods.
  9517. polling : Union["raf", float, None]
  9518. If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
  9519. is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
  9520. `raf`.
  9521. Returns
  9522. -------
  9523. JSHandle
  9524. """
  9525. return mapping.from_impl(
  9526. self._sync(
  9527. self._impl_obj.wait_for_function(
  9528. expression=expression,
  9529. arg=mapping.to_impl(arg),
  9530. timeout=timeout,
  9531. polling=polling,
  9532. )
  9533. )
  9534. )
  9535. def pause(self) -> None:
  9536. """Page.pause
  9537. Pauses script execution. Playwright will stop executing the script and wait for the user to either press the
  9538. 'Resume' button in the page overlay or to call `playwright.resume()` in the DevTools console.
  9539. User can inspect selectors or perform manual steps while paused. Resume will continue running the original script
  9540. from the place it was paused.
  9541. **NOTE** This method requires Playwright to be started in a headed mode, with a falsy `headless` option.
  9542. """
  9543. return mapping.from_maybe_impl(self._sync(self._impl_obj.pause()))
  9544. def pdf(
  9545. self,
  9546. *,
  9547. scale: typing.Optional[float] = None,
  9548. display_header_footer: typing.Optional[bool] = None,
  9549. header_template: typing.Optional[str] = None,
  9550. footer_template: typing.Optional[str] = None,
  9551. print_background: typing.Optional[bool] = None,
  9552. landscape: typing.Optional[bool] = None,
  9553. page_ranges: typing.Optional[str] = None,
  9554. format: typing.Optional[str] = None,
  9555. width: typing.Optional[typing.Union[str, float]] = None,
  9556. height: typing.Optional[typing.Union[str, float]] = None,
  9557. prefer_css_page_size: typing.Optional[bool] = None,
  9558. margin: typing.Optional[PdfMargins] = None,
  9559. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  9560. outline: typing.Optional[bool] = None,
  9561. tagged: typing.Optional[bool] = None,
  9562. ) -> bytes:
  9563. """Page.pdf
  9564. Returns the PDF buffer.
  9565. `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
  9566. `page.emulate_media()` before calling `page.pdf()`:
  9567. **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
  9568. [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust)
  9569. property to force rendering of exact colors.
  9570. **Usage**
  9571. ```py
  9572. # generates a pdf with \"screen\" media type.
  9573. page.emulate_media(media=\"screen\")
  9574. page.pdf(path=\"page.pdf\")
  9575. ```
  9576. The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as
  9577. pixels.
  9578. A few examples:
  9579. - `page.pdf({width: 100})` - prints with width set to 100 pixels
  9580. - `page.pdf({width: '100px'})` - prints with width set to 100 pixels
  9581. - `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
  9582. All possible units are:
  9583. - `px` - pixel
  9584. - `in` - inch
  9585. - `cm` - centimeter
  9586. - `mm` - millimeter
  9587. The `format` options are:
  9588. - `Letter`: 8.5in x 11in
  9589. - `Legal`: 8.5in x 14in
  9590. - `Tabloid`: 11in x 17in
  9591. - `Ledger`: 17in x 11in
  9592. - `A0`: 33.1in x 46.8in
  9593. - `A1`: 23.4in x 33.1in
  9594. - `A2`: 16.54in x 23.4in
  9595. - `A3`: 11.7in x 16.54in
  9596. - `A4`: 8.27in x 11.7in
  9597. - `A5`: 5.83in x 8.27in
  9598. - `A6`: 4.13in x 5.83in
  9599. **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations: > 1. Script tags inside
  9600. templates are not evaluated. > 2. Page styles are not visible inside templates.
  9601. Parameters
  9602. ----------
  9603. scale : Union[float, None]
  9604. Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
  9605. display_header_footer : Union[bool, None]
  9606. Display header and footer. Defaults to `false`.
  9607. header_template : Union[str, None]
  9608. HTML template for the print header. Should be valid HTML markup with following classes used to inject printing
  9609. values into them:
  9610. - `'date'` formatted print date
  9611. - `'title'` document title
  9612. - `'url'` document location
  9613. - `'pageNumber'` current page number
  9614. - `'totalPages'` total pages in the document
  9615. footer_template : Union[str, None]
  9616. HTML template for the print footer. Should use the same format as the `headerTemplate`.
  9617. print_background : Union[bool, None]
  9618. Print background graphics. Defaults to `false`.
  9619. landscape : Union[bool, None]
  9620. Paper orientation. Defaults to `false`.
  9621. page_ranges : Union[str, None]
  9622. Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
  9623. format : Union[str, None]
  9624. Paper format. If set, takes priority over `width` or `height` options. Defaults to 'Letter'.
  9625. width : Union[float, str, None]
  9626. Paper width, accepts values labeled with units.
  9627. height : Union[float, str, None]
  9628. Paper height, accepts values labeled with units.
  9629. prefer_css_page_size : Union[bool, None]
  9630. Give any CSS `@page` size declared in the page priority over what is declared in `width` and `height` or `format`
  9631. options. Defaults to `false`, which will scale the content to fit the paper size.
  9632. margin : Union[{top: Union[float, str, None], right: Union[float, str, None], bottom: Union[float, str, None], left: Union[float, str, None]}, None]
  9633. Paper margins, defaults to none.
  9634. path : Union[pathlib.Path, str, None]
  9635. The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to the current working
  9636. directory. If no path is provided, the PDF won't be saved to the disk.
  9637. outline : Union[bool, None]
  9638. Whether or not to embed the document outline into the PDF. Defaults to `false`.
  9639. tagged : Union[bool, None]
  9640. Whether or not to generate tagged (accessible) PDF. Defaults to `false`.
  9641. Returns
  9642. -------
  9643. bytes
  9644. """
  9645. return mapping.from_maybe_impl(
  9646. self._sync(
  9647. self._impl_obj.pdf(
  9648. scale=scale,
  9649. displayHeaderFooter=display_header_footer,
  9650. headerTemplate=header_template,
  9651. footerTemplate=footer_template,
  9652. printBackground=print_background,
  9653. landscape=landscape,
  9654. pageRanges=page_ranges,
  9655. format=format,
  9656. width=width,
  9657. height=height,
  9658. preferCSSPageSize=prefer_css_page_size,
  9659. margin=margin,
  9660. path=path,
  9661. outline=outline,
  9662. tagged=tagged,
  9663. )
  9664. )
  9665. )
  9666. def expect_event(
  9667. self,
  9668. event: str,
  9669. predicate: typing.Optional[typing.Callable] = None,
  9670. *,
  9671. timeout: typing.Optional[float] = None,
  9672. ) -> EventContextManager:
  9673. """Page.expect_event
  9674. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  9675. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
  9676. **Usage**
  9677. ```py
  9678. with page.expect_event(\"framenavigated\") as event_info:
  9679. page.get_by_role(\"button\")
  9680. frame = event_info.value
  9681. ```
  9682. Parameters
  9683. ----------
  9684. event : str
  9685. Event name, same one typically passed into `*.on(event)`.
  9686. predicate : Union[Callable, None]
  9687. Receives the event data and resolves to truthy value when the waiting should resolve.
  9688. timeout : Union[float, None]
  9689. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9690. default value can be changed by using the `browser_context.set_default_timeout()`.
  9691. Returns
  9692. -------
  9693. EventContextManager
  9694. """
  9695. return EventContextManager(
  9696. self,
  9697. self._impl_obj.expect_event(
  9698. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  9699. ).future,
  9700. )
  9701. def expect_console_message(
  9702. self,
  9703. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  9704. *,
  9705. timeout: typing.Optional[float] = None,
  9706. ) -> EventContextManager["ConsoleMessage"]:
  9707. """Page.expect_console_message
  9708. Performs action and waits for a `ConsoleMessage` to be logged by in the page. If predicate is provided, it passes
  9709. `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to return a truthy value.
  9710. Will throw an error if the page is closed before the `page.on('console')` event is fired.
  9711. Parameters
  9712. ----------
  9713. predicate : Union[Callable[[ConsoleMessage], bool], None]
  9714. Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
  9715. timeout : Union[float, None]
  9716. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9717. default value can be changed by using the `browser_context.set_default_timeout()`.
  9718. Returns
  9719. -------
  9720. EventContextManager[ConsoleMessage]
  9721. """
  9722. return EventContextManager(
  9723. self,
  9724. self._impl_obj.expect_console_message(
  9725. predicate=self._wrap_handler(predicate), timeout=timeout
  9726. ).future,
  9727. )
  9728. def expect_download(
  9729. self,
  9730. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  9731. *,
  9732. timeout: typing.Optional[float] = None,
  9733. ) -> EventContextManager["Download"]:
  9734. """Page.expect_download
  9735. Performs action and waits for a new `Download`. If predicate is provided, it passes `Download` value into the
  9736. `predicate` function and waits for `predicate(download)` to return a truthy value. Will throw an error if the page
  9737. is closed before the download event is fired.
  9738. Parameters
  9739. ----------
  9740. predicate : Union[Callable[[Download], bool], None]
  9741. Receives the `Download` object and resolves to truthy value when the waiting should resolve.
  9742. timeout : Union[float, None]
  9743. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9744. default value can be changed by using the `browser_context.set_default_timeout()`.
  9745. Returns
  9746. -------
  9747. EventContextManager[Download]
  9748. """
  9749. return EventContextManager(
  9750. self,
  9751. self._impl_obj.expect_download(
  9752. predicate=self._wrap_handler(predicate), timeout=timeout
  9753. ).future,
  9754. )
  9755. def expect_file_chooser(
  9756. self,
  9757. predicate: typing.Optional[typing.Callable[["FileChooser"], bool]] = None,
  9758. *,
  9759. timeout: typing.Optional[float] = None,
  9760. ) -> EventContextManager["FileChooser"]:
  9761. """Page.expect_file_chooser
  9762. Performs action and waits for a new `FileChooser` to be created. If predicate is provided, it passes `FileChooser`
  9763. value into the `predicate` function and waits for `predicate(fileChooser)` to return a truthy value. Will throw an
  9764. error if the page is closed before the file chooser is opened.
  9765. Parameters
  9766. ----------
  9767. predicate : Union[Callable[[FileChooser], bool], None]
  9768. Receives the `FileChooser` object and resolves to truthy value when the waiting should resolve.
  9769. timeout : Union[float, None]
  9770. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9771. default value can be changed by using the `browser_context.set_default_timeout()`.
  9772. Returns
  9773. -------
  9774. EventContextManager[FileChooser]
  9775. """
  9776. return EventContextManager(
  9777. self,
  9778. self._impl_obj.expect_file_chooser(
  9779. predicate=self._wrap_handler(predicate), timeout=timeout
  9780. ).future,
  9781. )
  9782. def expect_navigation(
  9783. self,
  9784. *,
  9785. url: typing.Optional[
  9786. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  9787. ] = None,
  9788. wait_until: typing.Optional[
  9789. Literal["commit", "domcontentloaded", "load", "networkidle"]
  9790. ] = None,
  9791. timeout: typing.Optional[float] = None,
  9792. ) -> EventContextManager["Response"]:
  9793. """Page.expect_navigation
  9794. Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the
  9795. navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
  9796. navigation due to History API usage, the navigation will resolve with `null`.
  9797. **Usage**
  9798. This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will
  9799. indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from
  9800. a `setTimeout`. Consider this example:
  9801. ```py
  9802. with page.expect_navigation():
  9803. # This action triggers the navigation after a timeout.
  9804. page.get_by_text(\"Navigate after timeout\").click()
  9805. # Resolves after navigation has finished
  9806. ```
  9807. **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
  9808. is considered a navigation.
  9809. Parameters
  9810. ----------
  9811. url : Union[Callable[[str], bool], Pattern[str], str, None]
  9812. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  9813. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  9814. equal to the string.
  9815. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  9816. When to consider operation succeeded, defaults to `load`. Events can be either:
  9817. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  9818. - `'load'` - consider operation to be finished when the `load` event is fired.
  9819. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  9820. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  9821. - `'commit'` - consider operation to be finished when network response is received and the document started
  9822. loading.
  9823. timeout : Union[float, None]
  9824. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  9825. be changed by using the `browser_context.set_default_navigation_timeout()`,
  9826. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  9827. `page.set_default_timeout()` methods.
  9828. Returns
  9829. -------
  9830. EventContextManager[Response]
  9831. """
  9832. return EventContextManager(
  9833. self,
  9834. self._impl_obj.expect_navigation(
  9835. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  9836. ).future,
  9837. )
  9838. def expect_popup(
  9839. self,
  9840. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  9841. *,
  9842. timeout: typing.Optional[float] = None,
  9843. ) -> EventContextManager["Page"]:
  9844. """Page.expect_popup
  9845. Performs action and waits for a popup `Page`. If predicate is provided, it passes [Popup] value into the
  9846. `predicate` function and waits for `predicate(page)` to return a truthy value. Will throw an error if the page is
  9847. closed before the popup event is fired.
  9848. Parameters
  9849. ----------
  9850. predicate : Union[Callable[[Page], bool], None]
  9851. Receives the `Page` object and resolves to truthy value when the waiting should resolve.
  9852. timeout : Union[float, None]
  9853. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9854. default value can be changed by using the `browser_context.set_default_timeout()`.
  9855. Returns
  9856. -------
  9857. EventContextManager[Page]
  9858. """
  9859. return EventContextManager(
  9860. self,
  9861. self._impl_obj.expect_popup(
  9862. predicate=self._wrap_handler(predicate), timeout=timeout
  9863. ).future,
  9864. )
  9865. def expect_request(
  9866. self,
  9867. url_or_predicate: typing.Union[
  9868. str, typing.Pattern[str], typing.Callable[["Request"], bool]
  9869. ],
  9870. *,
  9871. timeout: typing.Optional[float] = None,
  9872. ) -> EventContextManager["Request"]:
  9873. """Page.expect_request
  9874. Waits for the matching request and returns it. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more
  9875. details about events.
  9876. **Usage**
  9877. ```py
  9878. with page.expect_request(\"http://example.com/resource\") as first:
  9879. page.get_by_text(\"trigger request\").click()
  9880. first_request = first.value
  9881. # or with a lambda
  9882. with page.expect_request(lambda request: request.url == \"http://example.com\" and request.method == \"get\") as second:
  9883. page.get_by_text(\"trigger request\").click()
  9884. second_request = second.value
  9885. ```
  9886. Parameters
  9887. ----------
  9888. url_or_predicate : Union[Callable[[Request], bool], Pattern[str], str]
  9889. Request URL string, regex or predicate receiving `Request` object. When a `baseURL` via the context options was
  9890. provided and the passed URL is a path, it gets merged via the
  9891. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  9892. timeout : Union[float, None]
  9893. Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
  9894. be changed by using the `page.set_default_timeout()` method.
  9895. Returns
  9896. -------
  9897. EventContextManager[Request]
  9898. """
  9899. return EventContextManager(
  9900. self,
  9901. self._impl_obj.expect_request(
  9902. urlOrPredicate=self._wrap_handler(url_or_predicate), timeout=timeout
  9903. ).future,
  9904. )
  9905. def expect_request_finished(
  9906. self,
  9907. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  9908. *,
  9909. timeout: typing.Optional[float] = None,
  9910. ) -> EventContextManager["Request"]:
  9911. """Page.expect_request_finished
  9912. Performs action and waits for a `Request` to finish loading. If predicate is provided, it passes `Request` value
  9913. into the `predicate` function and waits for `predicate(request)` to return a truthy value. Will throw an error if
  9914. the page is closed before the `page.on('request_finished')` event is fired.
  9915. Parameters
  9916. ----------
  9917. predicate : Union[Callable[[Request], bool], None]
  9918. Receives the `Request` object and resolves to truthy value when the waiting should resolve.
  9919. timeout : Union[float, None]
  9920. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9921. default value can be changed by using the `browser_context.set_default_timeout()`.
  9922. Returns
  9923. -------
  9924. EventContextManager[Request]
  9925. """
  9926. return EventContextManager(
  9927. self,
  9928. self._impl_obj.expect_request_finished(
  9929. predicate=self._wrap_handler(predicate), timeout=timeout
  9930. ).future,
  9931. )
  9932. def expect_response(
  9933. self,
  9934. url_or_predicate: typing.Union[
  9935. str, typing.Pattern[str], typing.Callable[["Response"], bool]
  9936. ],
  9937. *,
  9938. timeout: typing.Optional[float] = None,
  9939. ) -> EventContextManager["Response"]:
  9940. """Page.expect_response
  9941. Returns the matched response. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more details about
  9942. events.
  9943. **Usage**
  9944. ```py
  9945. with page.expect_response(\"https://example.com/resource\") as response_info:
  9946. page.get_by_text(\"trigger response\").click()
  9947. response = response_info.value
  9948. return response.ok
  9949. # or with a lambda
  9950. with page.expect_response(lambda response: response.url == \"https://example.com\" and response.status == 200 and response.request.method == \"get\") as response_info:
  9951. page.get_by_text(\"trigger response\").click()
  9952. response = response_info.value
  9953. return response.ok
  9954. ```
  9955. Parameters
  9956. ----------
  9957. url_or_predicate : Union[Callable[[Response], bool], Pattern[str], str]
  9958. Request URL string, regex or predicate receiving `Response` object. When a `baseURL` via the context options was
  9959. provided and the passed URL is a path, it gets merged via the
  9960. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  9961. timeout : Union[float, None]
  9962. Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
  9963. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9964. Returns
  9965. -------
  9966. EventContextManager[Response]
  9967. """
  9968. return EventContextManager(
  9969. self,
  9970. self._impl_obj.expect_response(
  9971. urlOrPredicate=self._wrap_handler(url_or_predicate), timeout=timeout
  9972. ).future,
  9973. )
  9974. def expect_websocket(
  9975. self,
  9976. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  9977. *,
  9978. timeout: typing.Optional[float] = None,
  9979. ) -> EventContextManager["WebSocket"]:
  9980. """Page.expect_websocket
  9981. Performs action and waits for a new `WebSocket`. If predicate is provided, it passes `WebSocket` value into the
  9982. `predicate` function and waits for `predicate(webSocket)` to return a truthy value. Will throw an error if the page
  9983. is closed before the WebSocket event is fired.
  9984. Parameters
  9985. ----------
  9986. predicate : Union[Callable[[WebSocket], bool], None]
  9987. Receives the `WebSocket` object and resolves to truthy value when the waiting should resolve.
  9988. timeout : Union[float, None]
  9989. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9990. default value can be changed by using the `browser_context.set_default_timeout()`.
  9991. Returns
  9992. -------
  9993. EventContextManager[WebSocket]
  9994. """
  9995. return EventContextManager(
  9996. self,
  9997. self._impl_obj.expect_websocket(
  9998. predicate=self._wrap_handler(predicate), timeout=timeout
  9999. ).future,
  10000. )
  10001. def expect_worker(
  10002. self,
  10003. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  10004. *,
  10005. timeout: typing.Optional[float] = None,
  10006. ) -> EventContextManager["Worker"]:
  10007. """Page.expect_worker
  10008. Performs action and waits for a new `Worker`. If predicate is provided, it passes `Worker` value into the
  10009. `predicate` function and waits for `predicate(worker)` to return a truthy value. Will throw an error if the page is
  10010. closed before the worker event is fired.
  10011. Parameters
  10012. ----------
  10013. predicate : Union[Callable[[Worker], bool], None]
  10014. Receives the `Worker` object and resolves to truthy value when the waiting should resolve.
  10015. timeout : Union[float, None]
  10016. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10017. default value can be changed by using the `browser_context.set_default_timeout()`.
  10018. Returns
  10019. -------
  10020. EventContextManager[Worker]
  10021. """
  10022. return EventContextManager(
  10023. self,
  10024. self._impl_obj.expect_worker(
  10025. predicate=self._wrap_handler(predicate), timeout=timeout
  10026. ).future,
  10027. )
  10028. def set_checked(
  10029. self,
  10030. selector: str,
  10031. checked: bool,
  10032. *,
  10033. position: typing.Optional[Position] = None,
  10034. timeout: typing.Optional[float] = None,
  10035. force: typing.Optional[bool] = None,
  10036. no_wait_after: typing.Optional[bool] = None,
  10037. strict: typing.Optional[bool] = None,
  10038. trial: typing.Optional[bool] = None,
  10039. ) -> None:
  10040. """Page.set_checked
  10041. This method checks or unchecks an element matching `selector` by performing the following steps:
  10042. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  10043. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  10044. 1. If the element already has the right checked state, this method returns immediately.
  10045. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  10046. the element is detached during the checks, the whole action is retried.
  10047. 1. Scroll the element into view if needed.
  10048. 1. Use `page.mouse` to click in the center of the element.
  10049. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  10050. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  10051. Passing zero timeout disables this.
  10052. Parameters
  10053. ----------
  10054. selector : str
  10055. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  10056. used.
  10057. checked : bool
  10058. Whether to check or uncheck the checkbox.
  10059. position : Union[{x: float, y: float}, None]
  10060. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  10061. the element.
  10062. timeout : Union[float, None]
  10063. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  10064. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  10065. force : Union[bool, None]
  10066. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  10067. no_wait_after : Union[bool, None]
  10068. This option has no effect.
  10069. Deprecated: This option has no effect.
  10070. strict : Union[bool, None]
  10071. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  10072. element, the call throws an exception.
  10073. trial : Union[bool, None]
  10074. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  10075. to `false`. Useful to wait until the element is ready for the action without performing it.
  10076. """
  10077. return mapping.from_maybe_impl(
  10078. self._sync(
  10079. self._impl_obj.set_checked(
  10080. selector=selector,
  10081. checked=checked,
  10082. position=position,
  10083. timeout=timeout,
  10084. force=force,
  10085. noWaitAfter=no_wait_after,
  10086. strict=strict,
  10087. trial=trial,
  10088. )
  10089. )
  10090. )
  10091. def add_locator_handler(
  10092. self,
  10093. locator: "Locator",
  10094. handler: typing.Union[
  10095. typing.Callable[["Locator"], typing.Any], typing.Callable[[], typing.Any]
  10096. ],
  10097. *,
  10098. no_wait_after: typing.Optional[bool] = None,
  10099. times: typing.Optional[int] = None,
  10100. ) -> None:
  10101. """Page.add_locator_handler
  10102. When testing a web page, sometimes unexpected overlays like a \"Sign up\" dialog appear and block actions you want to
  10103. automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making
  10104. them tricky to handle in automated tests.
  10105. This method lets you set up a special function, called a handler, that activates when it detects that overlay is
  10106. visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
  10107. Things to keep in mind:
  10108. - When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as
  10109. a part of your normal test flow, instead of using `page.add_locator_handler()`.
  10110. - Playwright checks for the overlay every time before executing or retrying an action that requires an
  10111. [actionability check](https://playwright.dev/python/docs/actionability), or before performing an auto-waiting assertion check. When overlay
  10112. is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the
  10113. handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't
  10114. perform any actions, the handler will not be triggered.
  10115. - After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible
  10116. anymore. You can opt-out of this behavior with `noWaitAfter`.
  10117. - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler.
  10118. If your handler takes too long, it might cause timeouts.
  10119. - You can register multiple handlers. However, only a single handler will be running at a time. Make sure the
  10120. actions within a handler don't depend on another handler.
  10121. **NOTE** Running the handler will alter your page state mid-test. For example it will change the currently focused
  10122. element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on
  10123. the focus and mouse state being unchanged.
  10124. For example, consider a test that calls `locator.focus()` followed by `keyboard.press()`. If your
  10125. handler clicks a button between these two actions, the focused element most likely will be wrong, and key press
  10126. will happen on the unexpected element. Use `locator.press()` instead to avoid this problem.
  10127. Another example is a series of mouse actions, where `mouse.move()` is followed by `mouse.down()`.
  10128. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down.
  10129. Prefer self-contained actions like `locator.click()` that do not rely on the state being unchanged by a
  10130. handler.
  10131. **Usage**
  10132. An example that closes a \"Sign up to the newsletter\" dialog when it appears:
  10133. ```py
  10134. # Setup the handler.
  10135. async def handler():
  10136. await page.get_by_role(\"button\", name=\"No thanks\").click()
  10137. await page.add_locator_handler(page.get_by_text(\"Sign up to the newsletter\"), handler)
  10138. # Write the test as usual.
  10139. await page.goto(\"https://example.com\")
  10140. await page.get_by_role(\"button\", name=\"Start here\").click()
  10141. ```
  10142. An example that skips the \"Confirm your security details\" page when it is shown:
  10143. ```py
  10144. # Setup the handler.
  10145. async def handler():
  10146. await page.get_by_role(\"button\", name=\"Remind me later\").click()
  10147. await page.add_locator_handler(page.get_by_text(\"Confirm your security details\"), handler)
  10148. # Write the test as usual.
  10149. await page.goto(\"https://example.com\")
  10150. await page.get_by_role(\"button\", name=\"Start here\").click()
  10151. ```
  10152. An example with a custom callback on every actionability check. It uses a `<body>` locator that is always visible,
  10153. so the handler is called before every actionability check. It is important to specify `noWaitAfter`, because the
  10154. handler does not hide the `<body>` element.
  10155. ```py
  10156. # Setup the handler.
  10157. async def handler():
  10158. await page.evaluate(\"window.removeObstructionsForTestIfNeeded()\")
  10159. await page.add_locator_handler(page.locator(\"body\"), handler, no_wait_after=True)
  10160. # Write the test as usual.
  10161. await page.goto(\"https://example.com\")
  10162. await page.get_by_role(\"button\", name=\"Start here\").click()
  10163. ```
  10164. Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
  10165. invocations by setting `times`:
  10166. ```py
  10167. async def handler(locator):
  10168. await locator.click()
  10169. await page.add_locator_handler(page.get_by_label(\"Close\"), handler, times=1)
  10170. ```
  10171. Parameters
  10172. ----------
  10173. locator : Locator
  10174. Locator that triggers the handler.
  10175. handler : Union[Callable[[Locator], Any], Callable[[], Any]]
  10176. Function that should be run once `locator` appears. This function should get rid of the element that blocks actions
  10177. like click.
  10178. no_wait_after : Union[bool, None]
  10179. By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then
  10180. Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of
  10181. this behavior, so that overlay can stay visible after the handler has run.
  10182. times : Union[int, None]
  10183. Specifies the maximum number of times this handler should be called. Unlimited by default.
  10184. """
  10185. return mapping.from_maybe_impl(
  10186. self._sync(
  10187. self._impl_obj.add_locator_handler(
  10188. locator=locator._impl_obj,
  10189. handler=self._wrap_handler(handler),
  10190. noWaitAfter=no_wait_after,
  10191. times=times,
  10192. )
  10193. )
  10194. )
  10195. def remove_locator_handler(self, locator: "Locator") -> None:
  10196. """Page.remove_locator_handler
  10197. Removes all locator handlers added by `page.add_locator_handler()` for a specific locator.
  10198. Parameters
  10199. ----------
  10200. locator : Locator
  10201. Locator passed to `page.add_locator_handler()`.
  10202. """
  10203. return mapping.from_maybe_impl(
  10204. self._sync(self._impl_obj.remove_locator_handler(locator=locator._impl_obj))
  10205. )
  10206. def requests(self) -> typing.List["Request"]:
  10207. """Page.requests
  10208. Returns up to (currently) 100 last network request from this page. See `page.on('request')` for more details.
  10209. Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory
  10210. growth as new requests come in. Once collected, retrieving most information about the request is impossible.
  10211. Note that requests reported through the `page.on('request')` request are not collected, so there is a trade off
  10212. between efficient memory usage with `page.requests()` and the amount of available information reported
  10213. through `page.on('request')`.
  10214. Returns
  10215. -------
  10216. List[Request]
  10217. """
  10218. return mapping.from_impl_list(self._sync(self._impl_obj.requests()))
  10219. def console_messages(self) -> typing.List["ConsoleMessage"]:
  10220. """Page.console_messages
  10221. Returns up to (currently) 200 last console messages from this page. See `page.on('console')` for more details.
  10222. Returns
  10223. -------
  10224. List[ConsoleMessage]
  10225. """
  10226. return mapping.from_impl_list(self._sync(self._impl_obj.console_messages()))
  10227. def page_errors(self) -> typing.List["Error"]:
  10228. """Page.page_errors
  10229. Returns up to (currently) 200 last page errors from this page. See `page.on('page_error')` for more details.
  10230. Returns
  10231. -------
  10232. List[Error]
  10233. """
  10234. return mapping.from_impl_list(self._sync(self._impl_obj.page_errors()))
  10235. mapping.register(PageImpl, Page)
  10236. class WebError(SyncBase):
  10237. @property
  10238. def page(self) -> typing.Optional["Page"]:
  10239. """WebError.page
  10240. The page that produced this unhandled exception, if any.
  10241. Returns
  10242. -------
  10243. Union[Page, None]
  10244. """
  10245. return mapping.from_impl_nullable(self._impl_obj.page)
  10246. @property
  10247. def error(self) -> "Error":
  10248. """WebError.error
  10249. Unhandled error that was thrown.
  10250. Returns
  10251. -------
  10252. Error
  10253. """
  10254. return mapping.from_impl(self._impl_obj.error)
  10255. mapping.register(WebErrorImpl, WebError)
  10256. class BrowserContext(SyncContextManager):
  10257. @typing.overload
  10258. def on(
  10259. self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "None"]
  10260. ) -> None:
  10261. """
  10262. This event is not emitted."""
  10263. @typing.overload
  10264. def on(
  10265. self, event: Literal["close"], f: typing.Callable[["BrowserContext"], "None"]
  10266. ) -> None:
  10267. """
  10268. Emitted when Browser context gets closed. This might happen because of one of the following:
  10269. - Browser context is closed.
  10270. - Browser application is closed or crashed.
  10271. - The `browser.close()` method was called."""
  10272. @typing.overload
  10273. def on(
  10274. self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
  10275. ) -> None:
  10276. """
  10277. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  10278. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
  10279. **Usage**
  10280. ```py
  10281. def print_args(msg):
  10282. for arg in msg.args:
  10283. print(arg.json_value())
  10284. context.on(\"console\", print_args)
  10285. page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  10286. ```"""
  10287. @typing.overload
  10288. def on(
  10289. self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
  10290. ) -> None:
  10291. """
  10292. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  10293. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  10294. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  10295. and actions like click will never finish.
  10296. **Usage**
  10297. ```python
  10298. context.on(\"dialog\", lambda dialog: dialog.accept())
  10299. ```
  10300. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  10301. automatically dismissed."""
  10302. @typing.overload
  10303. def on(self, event: Literal["page"], f: typing.Callable[["Page"], "None"]) -> None:
  10304. """
  10305. The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
  10306. will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
  10307. specific page.
  10308. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  10309. popup with `window.open('http://example.com')`, this event will fire when the network request to
  10310. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  10311. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  10312. instead of similar methods on the `Page`.
  10313. ```py
  10314. with context.expect_page() as page_info:
  10315. page.get_by_text(\"open new page\").click(),
  10316. page = page_info.value
  10317. print(page.evaluate(\"location.href\"))
  10318. ```
  10319. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  10320. need it in most cases)."""
  10321. @typing.overload
  10322. def on(
  10323. self, event: Literal["weberror"], f: typing.Callable[["WebError"], "None"]
  10324. ) -> None:
  10325. """
  10326. Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
  10327. page, use `page.on('page_error')` instead."""
  10328. @typing.overload
  10329. def on(
  10330. self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
  10331. ) -> None:
  10332. """
  10333. Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
  10334. only listen for requests from a particular page, use `page.on('request')`.
  10335. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
  10336. """
  10337. @typing.overload
  10338. def on(
  10339. self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
  10340. ) -> None:
  10341. """
  10342. Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
  10343. use `page.on('request_failed')`.
  10344. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  10345. will complete with `browser_context.on('request_finished')` event and not with
  10346. `browser_context.on('request_failed')`."""
  10347. @typing.overload
  10348. def on(
  10349. self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
  10350. ) -> None:
  10351. """
  10352. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  10353. sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
  10354. particular page, use `page.on('request_finished')`."""
  10355. @typing.overload
  10356. def on(
  10357. self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
  10358. ) -> None:
  10359. """
  10360. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  10361. events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
  10362. `page.on('response')`."""
  10363. @typing.overload
  10364. def on(
  10365. self, event: Literal["serviceworker"], f: typing.Callable[["Worker"], "None"]
  10366. ) -> None:
  10367. """
  10368. **NOTE** Service workers are only supported on Chromium-based browsers.
  10369. Emitted when new service worker is created in the context."""
  10370. def on(self, event: str, f: typing.Callable[..., None]) -> None:
  10371. return super().on(event=event, f=f)
  10372. @typing.overload
  10373. def once(
  10374. self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "None"]
  10375. ) -> None:
  10376. """
  10377. This event is not emitted."""
  10378. @typing.overload
  10379. def once(
  10380. self, event: Literal["close"], f: typing.Callable[["BrowserContext"], "None"]
  10381. ) -> None:
  10382. """
  10383. Emitted when Browser context gets closed. This might happen because of one of the following:
  10384. - Browser context is closed.
  10385. - Browser application is closed or crashed.
  10386. - The `browser.close()` method was called."""
  10387. @typing.overload
  10388. def once(
  10389. self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
  10390. ) -> None:
  10391. """
  10392. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  10393. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
  10394. **Usage**
  10395. ```py
  10396. def print_args(msg):
  10397. for arg in msg.args:
  10398. print(arg.json_value())
  10399. context.on(\"console\", print_args)
  10400. page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  10401. ```"""
  10402. @typing.overload
  10403. def once(
  10404. self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
  10405. ) -> None:
  10406. """
  10407. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  10408. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  10409. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  10410. and actions like click will never finish.
  10411. **Usage**
  10412. ```python
  10413. context.on(\"dialog\", lambda dialog: dialog.accept())
  10414. ```
  10415. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  10416. automatically dismissed."""
  10417. @typing.overload
  10418. def once(
  10419. self, event: Literal["page"], f: typing.Callable[["Page"], "None"]
  10420. ) -> None:
  10421. """
  10422. The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
  10423. will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
  10424. specific page.
  10425. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  10426. popup with `window.open('http://example.com')`, this event will fire when the network request to
  10427. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  10428. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  10429. instead of similar methods on the `Page`.
  10430. ```py
  10431. with context.expect_page() as page_info:
  10432. page.get_by_text(\"open new page\").click(),
  10433. page = page_info.value
  10434. print(page.evaluate(\"location.href\"))
  10435. ```
  10436. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  10437. need it in most cases)."""
  10438. @typing.overload
  10439. def once(
  10440. self, event: Literal["weberror"], f: typing.Callable[["WebError"], "None"]
  10441. ) -> None:
  10442. """
  10443. Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
  10444. page, use `page.on('page_error')` instead."""
  10445. @typing.overload
  10446. def once(
  10447. self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
  10448. ) -> None:
  10449. """
  10450. Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
  10451. only listen for requests from a particular page, use `page.on('request')`.
  10452. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
  10453. """
  10454. @typing.overload
  10455. def once(
  10456. self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
  10457. ) -> None:
  10458. """
  10459. Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
  10460. use `page.on('request_failed')`.
  10461. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  10462. will complete with `browser_context.on('request_finished')` event and not with
  10463. `browser_context.on('request_failed')`."""
  10464. @typing.overload
  10465. def once(
  10466. self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
  10467. ) -> None:
  10468. """
  10469. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  10470. sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
  10471. particular page, use `page.on('request_finished')`."""
  10472. @typing.overload
  10473. def once(
  10474. self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
  10475. ) -> None:
  10476. """
  10477. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  10478. events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
  10479. `page.on('response')`."""
  10480. @typing.overload
  10481. def once(
  10482. self, event: Literal["serviceworker"], f: typing.Callable[["Worker"], "None"]
  10483. ) -> None:
  10484. """
  10485. **NOTE** Service workers are only supported on Chromium-based browsers.
  10486. Emitted when new service worker is created in the context."""
  10487. def once(self, event: str, f: typing.Callable[..., None]) -> None:
  10488. return super().once(event=event, f=f)
  10489. @property
  10490. def pages(self) -> typing.List["Page"]:
  10491. """BrowserContext.pages
  10492. Returns all open pages in the context.
  10493. Returns
  10494. -------
  10495. List[Page]
  10496. """
  10497. return mapping.from_impl_list(self._impl_obj.pages)
  10498. @property
  10499. def browser(self) -> typing.Optional["Browser"]:
  10500. """BrowserContext.browser
  10501. Gets the browser instance that owns the context. Returns `null` if the context is created outside of normal
  10502. browser, e.g. Android or Electron.
  10503. Returns
  10504. -------
  10505. Union[Browser, None]
  10506. """
  10507. return mapping.from_impl_nullable(self._impl_obj.browser)
  10508. @property
  10509. def background_pages(self) -> typing.List["Page"]:
  10510. """BrowserContext.background_pages
  10511. Returns an empty list.
  10512. Returns
  10513. -------
  10514. List[Page]
  10515. """
  10516. return mapping.from_impl_list(self._impl_obj.background_pages)
  10517. @property
  10518. def service_workers(self) -> typing.List["Worker"]:
  10519. """BrowserContext.service_workers
  10520. **NOTE** Service workers are only supported on Chromium-based browsers.
  10521. All existing service workers in the context.
  10522. Returns
  10523. -------
  10524. List[Worker]
  10525. """
  10526. return mapping.from_impl_list(self._impl_obj.service_workers)
  10527. @property
  10528. def tracing(self) -> "Tracing":
  10529. """BrowserContext.tracing
  10530. Returns
  10531. -------
  10532. Tracing
  10533. """
  10534. return mapping.from_impl(self._impl_obj.tracing)
  10535. @property
  10536. def request(self) -> "APIRequestContext":
  10537. """BrowserContext.request
  10538. API testing helper associated with this context. Requests made with this API will use context cookies.
  10539. Returns
  10540. -------
  10541. APIRequestContext
  10542. """
  10543. return mapping.from_impl(self._impl_obj.request)
  10544. @property
  10545. def clock(self) -> "Clock":
  10546. """BrowserContext.clock
  10547. Playwright has ability to mock clock and passage of time.
  10548. Returns
  10549. -------
  10550. Clock
  10551. """
  10552. return mapping.from_impl(self._impl_obj.clock)
  10553. def set_default_navigation_timeout(self, timeout: float) -> None:
  10554. """BrowserContext.set_default_navigation_timeout
  10555. This setting will change the default maximum navigation time for the following methods and related shortcuts:
  10556. - `page.go_back()`
  10557. - `page.go_forward()`
  10558. - `page.goto()`
  10559. - `page.reload()`
  10560. - `page.set_content()`
  10561. - `page.expect_navigation()`
  10562. **NOTE** `page.set_default_navigation_timeout()` and `page.set_default_timeout()` take priority over
  10563. `browser_context.set_default_navigation_timeout()`.
  10564. Parameters
  10565. ----------
  10566. timeout : float
  10567. Maximum navigation time in milliseconds
  10568. """
  10569. return mapping.from_maybe_impl(
  10570. self._impl_obj.set_default_navigation_timeout(timeout=timeout)
  10571. )
  10572. def set_default_timeout(self, timeout: float) -> None:
  10573. """BrowserContext.set_default_timeout
  10574. This setting will change the default maximum time for all the methods accepting `timeout` option.
  10575. **NOTE** `page.set_default_navigation_timeout()`, `page.set_default_timeout()` and
  10576. `browser_context.set_default_navigation_timeout()` take priority over
  10577. `browser_context.set_default_timeout()`.
  10578. Parameters
  10579. ----------
  10580. timeout : float
  10581. Maximum time in milliseconds. Pass `0` to disable timeout.
  10582. """
  10583. return mapping.from_maybe_impl(
  10584. self._impl_obj.set_default_timeout(timeout=timeout)
  10585. )
  10586. def new_page(self) -> "Page":
  10587. """BrowserContext.new_page
  10588. Creates a new page in the browser context.
  10589. Returns
  10590. -------
  10591. Page
  10592. """
  10593. return mapping.from_impl(self._sync(self._impl_obj.new_page()))
  10594. def cookies(
  10595. self, urls: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None
  10596. ) -> typing.List[Cookie]:
  10597. """BrowserContext.cookies
  10598. If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
  10599. URLs are returned.
  10600. Parameters
  10601. ----------
  10602. urls : Union[Sequence[str], str, None]
  10603. Optional list of URLs.
  10604. Returns
  10605. -------
  10606. List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}]
  10607. """
  10608. return mapping.from_impl_list(
  10609. self._sync(self._impl_obj.cookies(urls=mapping.to_impl(urls)))
  10610. )
  10611. def add_cookies(self, cookies: typing.Sequence[SetCookieParam]) -> None:
  10612. """BrowserContext.add_cookies
  10613. Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies
  10614. can be obtained via `browser_context.cookies()`.
  10615. **Usage**
  10616. ```py
  10617. browser_context.add_cookies([cookie_object1, cookie_object2])
  10618. ```
  10619. Parameters
  10620. ----------
  10621. cookies : Sequence[{name: str, value: str, url: Union[str, None], domain: Union[str, None], path: Union[str, None], expires: Union[float, None], httpOnly: Union[bool, None], secure: Union[bool, None], sameSite: Union["Lax", "None", "Strict", None], partitionKey: Union[str, None]}]
  10622. """
  10623. return mapping.from_maybe_impl(
  10624. self._sync(self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies)))
  10625. )
  10626. def clear_cookies(
  10627. self,
  10628. *,
  10629. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  10630. domain: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  10631. path: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  10632. ) -> None:
  10633. """BrowserContext.clear_cookies
  10634. Removes cookies from context. Accepts optional filter.
  10635. **Usage**
  10636. ```py
  10637. context.clear_cookies()
  10638. context.clear_cookies(name=\"session-id\")
  10639. context.clear_cookies(domain=\"my-origin.com\")
  10640. context.clear_cookies(path=\"/api/v1\")
  10641. context.clear_cookies(name=\"session-id\", domain=\"my-origin.com\")
  10642. ```
  10643. Parameters
  10644. ----------
  10645. name : Union[Pattern[str], str, None]
  10646. Only removes cookies with the given name.
  10647. domain : Union[Pattern[str], str, None]
  10648. Only removes cookies with the given domain.
  10649. path : Union[Pattern[str], str, None]
  10650. Only removes cookies with the given path.
  10651. """
  10652. return mapping.from_maybe_impl(
  10653. self._sync(
  10654. self._impl_obj.clear_cookies(name=name, domain=domain, path=path)
  10655. )
  10656. )
  10657. def grant_permissions(
  10658. self, permissions: typing.Sequence[str], *, origin: typing.Optional[str] = None
  10659. ) -> None:
  10660. """BrowserContext.grant_permissions
  10661. Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
  10662. specified.
  10663. Parameters
  10664. ----------
  10665. permissions : Sequence[str]
  10666. A list of permissions to grant.
  10667. **NOTE** Supported permissions differ between browsers, and even between different versions of the same browser.
  10668. Any permission may stop working after an update.
  10669. Here are some permissions that may be supported by some browsers:
  10670. - `'accelerometer'`
  10671. - `'ambient-light-sensor'`
  10672. - `'background-sync'`
  10673. - `'camera'`
  10674. - `'clipboard-read'`
  10675. - `'clipboard-write'`
  10676. - `'geolocation'`
  10677. - `'gyroscope'`
  10678. - `'local-fonts'`
  10679. - `'local-network-access'`
  10680. - `'magnetometer'`
  10681. - `'microphone'`
  10682. - `'midi-sysex'` (system-exclusive midi)
  10683. - `'midi'`
  10684. - `'notifications'`
  10685. - `'payment-handler'`
  10686. - `'storage-access'`
  10687. origin : Union[str, None]
  10688. The [origin] to grant permissions to, e.g. "https://example.com".
  10689. """
  10690. return mapping.from_maybe_impl(
  10691. self._sync(
  10692. self._impl_obj.grant_permissions(
  10693. permissions=mapping.to_impl(permissions), origin=origin
  10694. )
  10695. )
  10696. )
  10697. def clear_permissions(self) -> None:
  10698. """BrowserContext.clear_permissions
  10699. Clears all permission overrides for the browser context.
  10700. **Usage**
  10701. ```py
  10702. context = browser.new_context()
  10703. context.grant_permissions([\"clipboard-read\"])
  10704. # do stuff ..
  10705. context.clear_permissions()
  10706. ```
  10707. """
  10708. return mapping.from_maybe_impl(self._sync(self._impl_obj.clear_permissions()))
  10709. def set_geolocation(self, geolocation: typing.Optional[Geolocation] = None) -> None:
  10710. """BrowserContext.set_geolocation
  10711. Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
  10712. **Usage**
  10713. ```py
  10714. browser_context.set_geolocation({\"latitude\": 59.95, \"longitude\": 30.31667})
  10715. ```
  10716. **NOTE** Consider using `browser_context.grant_permissions()` to grant permissions for the browser context
  10717. pages to read its geolocation.
  10718. Parameters
  10719. ----------
  10720. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  10721. """
  10722. return mapping.from_maybe_impl(
  10723. self._sync(self._impl_obj.set_geolocation(geolocation=geolocation))
  10724. )
  10725. def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
  10726. """BrowserContext.set_extra_http_headers
  10727. The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are
  10728. merged with page-specific extra HTTP headers set with `page.set_extra_http_headers()`. If page overrides a
  10729. particular header, page-specific header value will be used instead of the browser context header value.
  10730. **NOTE** `browser_context.set_extra_http_headers()` does not guarantee the order of headers in the outgoing
  10731. requests.
  10732. Parameters
  10733. ----------
  10734. headers : Dict[str, str]
  10735. An object containing additional HTTP headers to be sent with every request. All header values must be strings.
  10736. """
  10737. return mapping.from_maybe_impl(
  10738. self._sync(
  10739. self._impl_obj.set_extra_http_headers(headers=mapping.to_impl(headers))
  10740. )
  10741. )
  10742. def set_offline(self, offline: bool) -> None:
  10743. """BrowserContext.set_offline
  10744. Parameters
  10745. ----------
  10746. offline : bool
  10747. Whether to emulate network being offline for the browser context.
  10748. """
  10749. return mapping.from_maybe_impl(
  10750. self._sync(self._impl_obj.set_offline(offline=offline))
  10751. )
  10752. def add_init_script(
  10753. self,
  10754. script: typing.Optional[str] = None,
  10755. *,
  10756. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  10757. ) -> None:
  10758. """BrowserContext.add_init_script
  10759. Adds a script which would be evaluated in one of the following scenarios:
  10760. - Whenever a page is created in the browser context or is navigated.
  10761. - Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is
  10762. evaluated in the context of the newly attached frame.
  10763. The script is evaluated after the document was created but before any of its scripts were run. This is useful to
  10764. amend the JavaScript environment, e.g. to seed `Math.random`.
  10765. **Usage**
  10766. An example of overriding `Math.random` before the page loads:
  10767. ```py
  10768. # in your playwright script, assuming the preload.js file is in same directory.
  10769. browser_context.add_init_script(path=\"preload.js\")
  10770. ```
  10771. **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
  10772. `page.add_init_script()` is not defined.
  10773. Parameters
  10774. ----------
  10775. script : Union[str, None]
  10776. Script to be evaluated in all pages in the browser context. Optional.
  10777. path : Union[pathlib.Path, str, None]
  10778. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  10779. directory. Optional.
  10780. """
  10781. return mapping.from_maybe_impl(
  10782. self._sync(self._impl_obj.add_init_script(script=script, path=path))
  10783. )
  10784. def expose_binding(
  10785. self,
  10786. name: str,
  10787. callback: typing.Callable,
  10788. *,
  10789. handle: typing.Optional[bool] = None,
  10790. ) -> None:
  10791. """BrowserContext.expose_binding
  10792. The method adds a function called `name` on the `window` object of every frame in every page in the context. When
  10793. called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  10794. If the `callback` returns a [Promise], it will be awaited.
  10795. The first argument of the `callback` function contains information about the caller: `{ browserContext:
  10796. BrowserContext, page: Page, frame: Frame }`.
  10797. See `page.expose_binding()` for page-only version.
  10798. **Usage**
  10799. An example of exposing page URL to all frames in all pages in the context:
  10800. ```py
  10801. from playwright.sync_api import sync_playwright, Playwright
  10802. def run(playwright: Playwright):
  10803. webkit = playwright.webkit
  10804. browser = webkit.launch(headless=False)
  10805. context = browser.new_context()
  10806. context.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
  10807. page = context.new_page()
  10808. page.set_content(\"\"\"
  10809. <script>
  10810. async function onClick() {
  10811. document.querySelector('div').textContent = await window.pageURL();
  10812. }
  10813. </script>
  10814. <button onclick=\"onClick()\">Click me</button>
  10815. <div></div>
  10816. \"\"\")
  10817. page.get_by_role(\"button\").click()
  10818. with sync_playwright() as playwright:
  10819. run(playwright)
  10820. ```
  10821. Parameters
  10822. ----------
  10823. name : str
  10824. Name of the function on the window object.
  10825. callback : Callable
  10826. Callback function that will be called in the Playwright's context.
  10827. handle : Union[bool, None]
  10828. Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
  10829. supported. When passing by value, multiple arguments are supported.
  10830. Deprecated: This option will be removed in the future.
  10831. """
  10832. return mapping.from_maybe_impl(
  10833. self._sync(
  10834. self._impl_obj.expose_binding(
  10835. name=name, callback=self._wrap_handler(callback), handle=handle
  10836. )
  10837. )
  10838. )
  10839. def expose_function(self, name: str, callback: typing.Callable) -> None:
  10840. """BrowserContext.expose_function
  10841. The method adds a function called `name` on the `window` object of every frame in every page in the context. When
  10842. called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  10843. If the `callback` returns a [Promise], it will be awaited.
  10844. See `page.expose_function()` for page-only version.
  10845. **Usage**
  10846. An example of adding a `sha256` function to all pages in the context:
  10847. ```py
  10848. import hashlib
  10849. from playwright.sync_api import sync_playwright
  10850. def sha256(text: str) -> str:
  10851. m = hashlib.sha256()
  10852. m.update(bytes(text, \"utf8\"))
  10853. return m.hexdigest()
  10854. def run(playwright: Playwright):
  10855. webkit = playwright.webkit
  10856. browser = webkit.launch(headless=False)
  10857. context = browser.new_context()
  10858. context.expose_function(\"sha256\", sha256)
  10859. page = context.new_page()
  10860. page.set_content(\"\"\"
  10861. <script>
  10862. async function onClick() {
  10863. document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  10864. }
  10865. </script>
  10866. <button onclick=\"onClick()\">Click me</button>
  10867. <div></div>
  10868. \"\"\")
  10869. page.get_by_role(\"button\").click()
  10870. with sync_playwright() as playwright:
  10871. run(playwright)
  10872. ```
  10873. Parameters
  10874. ----------
  10875. name : str
  10876. Name of the function on the window object.
  10877. callback : Callable
  10878. Callback function that will be called in the Playwright's context.
  10879. """
  10880. return mapping.from_maybe_impl(
  10881. self._sync(
  10882. self._impl_obj.expose_function(
  10883. name=name, callback=self._wrap_handler(callback)
  10884. )
  10885. )
  10886. )
  10887. def route(
  10888. self,
  10889. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  10890. handler: typing.Union[
  10891. typing.Callable[["Route"], typing.Any],
  10892. typing.Callable[["Route", "Request"], typing.Any],
  10893. ],
  10894. *,
  10895. times: typing.Optional[int] = None,
  10896. ) -> None:
  10897. """BrowserContext.route
  10898. Routing provides the capability to modify network requests that are made by any page in the browser context. Once
  10899. route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
  10900. **NOTE** `browser_context.route()` will not intercept requests intercepted by Service Worker. See
  10901. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  10902. using request interception by setting `serviceWorkers` to `'block'`.
  10903. **Usage**
  10904. An example of a naive handler that aborts all image requests:
  10905. ```py
  10906. context = browser.new_context()
  10907. page = context.new_page()
  10908. context.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
  10909. page.goto(\"https://example.com\")
  10910. browser.close()
  10911. ```
  10912. or the same snippet using a regex pattern instead:
  10913. ```py
  10914. context = browser.new_context()
  10915. page = context.new_page()
  10916. context.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
  10917. page = await context.new_page()
  10918. page = context.new_page()
  10919. page.goto(\"https://example.com\")
  10920. browser.close()
  10921. ```
  10922. It is possible to examine the request to decide the route action. For example, mocking all requests that contain
  10923. some post data, and leaving all other requests as is:
  10924. ```py
  10925. def handle_route(route: Route):
  10926. if (\"my-string\" in route.request.post_data):
  10927. route.fulfill(body=\"mocked-data\")
  10928. else:
  10929. route.continue_()
  10930. context.route(\"/api/**\", handle_route)
  10931. ```
  10932. Page routes (set up with `page.route()`) take precedence over browser context routes when request matches
  10933. both handlers.
  10934. To remove a route with its handler you can use `browser_context.unroute()`.
  10935. **NOTE** Enabling routing disables http cache.
  10936. Parameters
  10937. ----------
  10938. url : Union[Callable[[str], bool], Pattern[str], str]
  10939. A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
  10940. the context options and the provided URL is a string that does not start with `*`, it is resolved using the
  10941. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  10942. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
  10943. handler function to route the request.
  10944. times : Union[int, None]
  10945. How often a route should be used. By default it will be used every time.
  10946. """
  10947. return mapping.from_maybe_impl(
  10948. self._sync(
  10949. self._impl_obj.route(
  10950. url=self._wrap_handler(url),
  10951. handler=self._wrap_handler(handler),
  10952. times=times,
  10953. )
  10954. )
  10955. )
  10956. def unroute(
  10957. self,
  10958. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  10959. handler: typing.Optional[
  10960. typing.Union[
  10961. typing.Callable[["Route"], typing.Any],
  10962. typing.Callable[["Route", "Request"], typing.Any],
  10963. ]
  10964. ] = None,
  10965. ) -> None:
  10966. """BrowserContext.unroute
  10967. Removes a route created with `browser_context.route()`. When `handler` is not specified, removes all routes
  10968. for the `url`.
  10969. Parameters
  10970. ----------
  10971. url : Union[Callable[[str], bool], Pattern[str], str]
  10972. A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
  10973. `browser_context.route()`.
  10974. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
  10975. Optional handler function used to register a routing with `browser_context.route()`.
  10976. """
  10977. return mapping.from_maybe_impl(
  10978. self._sync(
  10979. self._impl_obj.unroute(
  10980. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  10981. )
  10982. )
  10983. )
  10984. def route_web_socket(
  10985. self,
  10986. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  10987. handler: typing.Callable[["WebSocketRoute"], typing.Any],
  10988. ) -> None:
  10989. """BrowserContext.route_web_socket
  10990. This method allows to modify websocket connections that are made by any page in the browser context.
  10991. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
  10992. method before creating any pages.
  10993. **Usage**
  10994. Below is an example of a simple handler that blocks some websocket messages. See `WebSocketRoute` for more details
  10995. and examples.
  10996. ```py
  10997. def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  10998. if message == \"to-be-blocked\":
  10999. return
  11000. ws.send(message)
  11001. def handler(ws: WebSocketRoute):
  11002. ws.route_send(lambda message: message_handler(ws, message))
  11003. ws.connect()
  11004. context.route_web_socket(\"/ws\", handler)
  11005. ```
  11006. Parameters
  11007. ----------
  11008. url : Union[Callable[[str], bool], Pattern[str], str]
  11009. Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
  11010. `baseURL` context option.
  11011. handler : Callable[[WebSocketRoute], Any]
  11012. Handler function to route the WebSocket.
  11013. """
  11014. return mapping.from_maybe_impl(
  11015. self._sync(
  11016. self._impl_obj.route_web_socket(
  11017. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  11018. )
  11019. )
  11020. )
  11021. def unroute_all(
  11022. self,
  11023. *,
  11024. behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
  11025. ) -> None:
  11026. """BrowserContext.unroute_all
  11027. Removes all routes created with `browser_context.route()` and `browser_context.route_from_har()`.
  11028. Parameters
  11029. ----------
  11030. behavior : Union["default", "ignoreErrors", "wait", None]
  11031. Specifies whether to wait for already running handlers and what to do if they throw errors:
  11032. - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
  11033. result in unhandled error
  11034. - `'wait'` - wait for current handler calls (if any) to finish
  11035. - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
  11036. after unrouting are silently caught
  11037. """
  11038. return mapping.from_maybe_impl(
  11039. self._sync(self._impl_obj.unroute_all(behavior=behavior))
  11040. )
  11041. def route_from_har(
  11042. self,
  11043. har: typing.Union[pathlib.Path, str],
  11044. *,
  11045. url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  11046. not_found: typing.Optional[Literal["abort", "fallback"]] = None,
  11047. update: typing.Optional[bool] = None,
  11048. update_content: typing.Optional[Literal["attach", "embed"]] = None,
  11049. update_mode: typing.Optional[Literal["full", "minimal"]] = None,
  11050. ) -> None:
  11051. """BrowserContext.route_from_har
  11052. If specified the network requests that are made in the context will be served from the HAR file. Read more about
  11053. [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
  11054. Playwright will not serve requests intercepted by Service Worker from the HAR file. See
  11055. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  11056. using request interception by setting `serviceWorkers` to `'block'`.
  11057. Parameters
  11058. ----------
  11059. har : Union[pathlib.Path, str]
  11060. Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
  11061. relative path, then it is resolved relative to the current working directory.
  11062. url : Union[Pattern[str], str, None]
  11063. A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
  11064. pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
  11065. not_found : Union["abort", "fallback", None]
  11066. - If set to 'abort' any request not found in the HAR file will be aborted.
  11067. - If set to 'fallback' falls through to the next route handler in the handler chain.
  11068. Defaults to abort.
  11069. update : Union[bool, None]
  11070. If specified, updates the given HAR with the actual network information instead of serving from file. The file is
  11071. written to disk when `browser_context.close()` is called.
  11072. update_content : Union["attach", "embed", None]
  11073. Optional setting to control resource content management. If `attach` is specified, resources are persisted as
  11074. separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
  11075. update_mode : Union["full", "minimal", None]
  11076. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  11077. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
  11078. `minimal`.
  11079. """
  11080. return mapping.from_maybe_impl(
  11081. self._sync(
  11082. self._impl_obj.route_from_har(
  11083. har=har,
  11084. url=url,
  11085. notFound=not_found,
  11086. update=update,
  11087. updateContent=update_content,
  11088. updateMode=update_mode,
  11089. )
  11090. )
  11091. )
  11092. def expect_event(
  11093. self,
  11094. event: str,
  11095. predicate: typing.Optional[typing.Callable] = None,
  11096. *,
  11097. timeout: typing.Optional[float] = None,
  11098. ) -> EventContextManager:
  11099. """BrowserContext.expect_event
  11100. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  11101. value. Will throw an error if the context closes before the event is fired. Returns the event data value.
  11102. **Usage**
  11103. ```py
  11104. with context.expect_event(\"page\") as event_info:
  11105. page.get_by_role(\"button\").click()
  11106. page = event_info.value
  11107. ```
  11108. Parameters
  11109. ----------
  11110. event : str
  11111. Event name, same one would pass into `browserContext.on(event)`.
  11112. predicate : Union[Callable, None]
  11113. Receives the event data and resolves to truthy value when the waiting should resolve.
  11114. timeout : Union[float, None]
  11115. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11116. default value can be changed by using the `browser_context.set_default_timeout()`.
  11117. Returns
  11118. -------
  11119. EventContextManager
  11120. """
  11121. return EventContextManager(
  11122. self,
  11123. self._impl_obj.expect_event(
  11124. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  11125. ).future,
  11126. )
  11127. def close(self, *, reason: typing.Optional[str] = None) -> None:
  11128. """BrowserContext.close
  11129. Closes the browser context. All the pages that belong to the browser context will be closed.
  11130. **NOTE** The default browser context cannot be closed.
  11131. Parameters
  11132. ----------
  11133. reason : Union[str, None]
  11134. The reason to be reported to the operations interrupted by the context closure.
  11135. """
  11136. return mapping.from_maybe_impl(self._sync(self._impl_obj.close(reason=reason)))
  11137. def storage_state(
  11138. self,
  11139. *,
  11140. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11141. indexed_db: typing.Optional[bool] = None,
  11142. ) -> StorageState:
  11143. """BrowserContext.storage_state
  11144. Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB
  11145. snapshot.
  11146. Parameters
  11147. ----------
  11148. path : Union[pathlib.Path, str, None]
  11149. The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
  11150. working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
  11151. indexed_db : Union[bool, None]
  11152. Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage
  11153. state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication,
  11154. enable this.
  11155. Returns
  11156. -------
  11157. {cookies: List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: List[{origin: str, localStorage: List[{name: str, value: str}]}]}
  11158. """
  11159. return mapping.from_impl(
  11160. self._sync(self._impl_obj.storage_state(path=path, indexedDB=indexed_db))
  11161. )
  11162. def wait_for_event(
  11163. self,
  11164. event: str,
  11165. predicate: typing.Optional[typing.Callable] = None,
  11166. *,
  11167. timeout: typing.Optional[float] = None,
  11168. ) -> typing.Any:
  11169. """BrowserContext.wait_for_event
  11170. **NOTE** In most cases, you should use `browser_context.expect_event()`.
  11171. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  11172. and waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed
  11173. before the `event` is fired.
  11174. Parameters
  11175. ----------
  11176. event : str
  11177. Event name, same one typically passed into `*.on(event)`.
  11178. predicate : Union[Callable, None]
  11179. Receives the event data and resolves to truthy value when the waiting should resolve.
  11180. timeout : Union[float, None]
  11181. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11182. default value can be changed by using the `browser_context.set_default_timeout()`.
  11183. Returns
  11184. -------
  11185. Any
  11186. """
  11187. return mapping.from_maybe_impl(
  11188. self._sync(
  11189. self._impl_obj.wait_for_event(
  11190. event=event,
  11191. predicate=self._wrap_handler(predicate),
  11192. timeout=timeout,
  11193. )
  11194. )
  11195. )
  11196. def expect_console_message(
  11197. self,
  11198. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  11199. *,
  11200. timeout: typing.Optional[float] = None,
  11201. ) -> EventContextManager["ConsoleMessage"]:
  11202. """BrowserContext.expect_console_message
  11203. Performs action and waits for a `ConsoleMessage` to be logged by in the pages in the context. If predicate is
  11204. provided, it passes `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to
  11205. return a truthy value. Will throw an error if the page is closed before the `browser_context.on('console')` event
  11206. is fired.
  11207. Parameters
  11208. ----------
  11209. predicate : Union[Callable[[ConsoleMessage], bool], None]
  11210. Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
  11211. timeout : Union[float, None]
  11212. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11213. default value can be changed by using the `browser_context.set_default_timeout()`.
  11214. Returns
  11215. -------
  11216. EventContextManager[ConsoleMessage]
  11217. """
  11218. return EventContextManager(
  11219. self,
  11220. self._impl_obj.expect_console_message(
  11221. predicate=self._wrap_handler(predicate), timeout=timeout
  11222. ).future,
  11223. )
  11224. def expect_page(
  11225. self,
  11226. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  11227. *,
  11228. timeout: typing.Optional[float] = None,
  11229. ) -> EventContextManager["Page"]:
  11230. """BrowserContext.expect_page
  11231. Performs action and waits for a new `Page` to be created in the context. If predicate is provided, it passes `Page`
  11232. value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error
  11233. if the context closes before new `Page` is created.
  11234. Parameters
  11235. ----------
  11236. predicate : Union[Callable[[Page], bool], None]
  11237. Receives the `Page` object and resolves to truthy value when the waiting should resolve.
  11238. timeout : Union[float, None]
  11239. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11240. default value can be changed by using the `browser_context.set_default_timeout()`.
  11241. Returns
  11242. -------
  11243. EventContextManager[Page]
  11244. """
  11245. return EventContextManager(
  11246. self,
  11247. self._impl_obj.expect_page(
  11248. predicate=self._wrap_handler(predicate), timeout=timeout
  11249. ).future,
  11250. )
  11251. def new_cdp_session(self, page: typing.Union["Page", "Frame"]) -> "CDPSession":
  11252. """BrowserContext.new_cdp_session
  11253. **NOTE** CDP sessions are only supported on Chromium-based browsers.
  11254. Returns the newly created session.
  11255. Parameters
  11256. ----------
  11257. page : Union[Frame, Page]
  11258. Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a
  11259. `Page` or `Frame` type.
  11260. Returns
  11261. -------
  11262. CDPSession
  11263. """
  11264. return mapping.from_impl(self._sync(self._impl_obj.new_cdp_session(page=page)))
  11265. mapping.register(BrowserContextImpl, BrowserContext)
  11266. class CDPSession(SyncBase):
  11267. def send(
  11268. self, method: str, params: typing.Optional[typing.Dict] = None
  11269. ) -> typing.Dict:
  11270. """CDPSession.send
  11271. Parameters
  11272. ----------
  11273. method : str
  11274. Protocol method name.
  11275. params : Union[Dict, None]
  11276. Optional method parameters.
  11277. Returns
  11278. -------
  11279. Dict
  11280. """
  11281. return mapping.from_maybe_impl(
  11282. self._sync(
  11283. self._impl_obj.send(method=method, params=mapping.to_impl(params))
  11284. )
  11285. )
  11286. def detach(self) -> None:
  11287. """CDPSession.detach
  11288. Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
  11289. used to send messages.
  11290. """
  11291. return mapping.from_maybe_impl(self._sync(self._impl_obj.detach()))
  11292. mapping.register(CDPSessionImpl, CDPSession)
  11293. class Browser(SyncContextManager):
  11294. def on(
  11295. self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "None"]
  11296. ) -> None:
  11297. """
  11298. Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
  11299. following:
  11300. - Browser application is closed or crashed.
  11301. - The `browser.close()` method was called."""
  11302. return super().on(event=event, f=f)
  11303. def once(
  11304. self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "None"]
  11305. ) -> None:
  11306. """
  11307. Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
  11308. following:
  11309. - Browser application is closed or crashed.
  11310. - The `browser.close()` method was called."""
  11311. return super().once(event=event, f=f)
  11312. @property
  11313. def contexts(self) -> typing.List["BrowserContext"]:
  11314. """Browser.contexts
  11315. Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
  11316. **Usage**
  11317. ```py
  11318. browser = pw.webkit.launch()
  11319. print(len(browser.contexts)) # prints `0`
  11320. context = browser.new_context()
  11321. print(len(browser.contexts)) # prints `1`
  11322. ```
  11323. Returns
  11324. -------
  11325. List[BrowserContext]
  11326. """
  11327. return mapping.from_impl_list(self._impl_obj.contexts)
  11328. @property
  11329. def browser_type(self) -> "BrowserType":
  11330. """Browser.browser_type
  11331. Get the browser type (chromium, firefox or webkit) that the browser belongs to.
  11332. Returns
  11333. -------
  11334. BrowserType
  11335. """
  11336. return mapping.from_impl(self._impl_obj.browser_type)
  11337. @property
  11338. def version(self) -> str:
  11339. """Browser.version
  11340. Returns the browser version.
  11341. Returns
  11342. -------
  11343. str
  11344. """
  11345. return mapping.from_maybe_impl(self._impl_obj.version)
  11346. def is_connected(self) -> bool:
  11347. """Browser.is_connected
  11348. Indicates that the browser is connected.
  11349. Returns
  11350. -------
  11351. bool
  11352. """
  11353. return mapping.from_maybe_impl(self._impl_obj.is_connected())
  11354. def new_context(
  11355. self,
  11356. *,
  11357. viewport: typing.Optional[ViewportSize] = None,
  11358. screen: typing.Optional[ViewportSize] = None,
  11359. no_viewport: typing.Optional[bool] = None,
  11360. ignore_https_errors: typing.Optional[bool] = None,
  11361. java_script_enabled: typing.Optional[bool] = None,
  11362. bypass_csp: typing.Optional[bool] = None,
  11363. user_agent: typing.Optional[str] = None,
  11364. locale: typing.Optional[str] = None,
  11365. timezone_id: typing.Optional[str] = None,
  11366. geolocation: typing.Optional[Geolocation] = None,
  11367. permissions: typing.Optional[typing.Sequence[str]] = None,
  11368. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  11369. offline: typing.Optional[bool] = None,
  11370. http_credentials: typing.Optional[HttpCredentials] = None,
  11371. device_scale_factor: typing.Optional[float] = None,
  11372. is_mobile: typing.Optional[bool] = None,
  11373. has_touch: typing.Optional[bool] = None,
  11374. color_scheme: typing.Optional[
  11375. Literal["dark", "light", "no-preference", "null"]
  11376. ] = None,
  11377. reduced_motion: typing.Optional[
  11378. Literal["no-preference", "null", "reduce"]
  11379. ] = None,
  11380. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  11381. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  11382. accept_downloads: typing.Optional[bool] = None,
  11383. default_browser_type: typing.Optional[str] = None,
  11384. proxy: typing.Optional[ProxySettings] = None,
  11385. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11386. record_har_omit_content: typing.Optional[bool] = None,
  11387. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11388. record_video_size: typing.Optional[ViewportSize] = None,
  11389. storage_state: typing.Optional[
  11390. typing.Union[StorageState, str, pathlib.Path]
  11391. ] = None,
  11392. base_url: typing.Optional[str] = None,
  11393. strict_selectors: typing.Optional[bool] = None,
  11394. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  11395. record_har_url_filter: typing.Optional[
  11396. typing.Union[typing.Pattern[str], str]
  11397. ] = None,
  11398. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  11399. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  11400. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  11401. ) -> "BrowserContext":
  11402. """Browser.new_context
  11403. Creates a new browser context. It won't share cookies/cache with other browser contexts.
  11404. **NOTE** If directly using this method to create `BrowserContext`s, it is best practice to explicitly close the
  11405. returned context via `browser_context.close()` when your code is done with the `BrowserContext`, and before
  11406. calling `browser.close()`. This will ensure the `context` is closed gracefully and any artifacts—like HARs
  11407. and videos—are fully flushed and saved.
  11408. **Usage**
  11409. ```py
  11410. browser = playwright.firefox.launch() # or \"chromium\" or \"webkit\".
  11411. # create a new incognito browser context.
  11412. context = browser.new_context()
  11413. # create a new page in a pristine context.
  11414. page = context.new_page()
  11415. page.goto(\"https://example.com\")
  11416. # gracefully close up everything
  11417. context.close()
  11418. browser.close()
  11419. ```
  11420. Parameters
  11421. ----------
  11422. viewport : Union[{width: int, height: int}, None]
  11423. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  11424. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  11425. screen : Union[{width: int, height: int}, None]
  11426. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  11427. `viewport` is set.
  11428. no_viewport : Union[bool, None]
  11429. Does not enforce fixed viewport, allows resizing window in the headed mode.
  11430. ignore_https_errors : Union[bool, None]
  11431. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  11432. java_script_enabled : Union[bool, None]
  11433. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  11434. [disabling JavaScript](../emulation.md#javascript-enabled).
  11435. bypass_csp : Union[bool, None]
  11436. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  11437. user_agent : Union[str, None]
  11438. Specific user agent to use in this context.
  11439. locale : Union[str, None]
  11440. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  11441. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  11442. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  11443. timezone_id : Union[str, None]
  11444. Changes the timezone of the context. See
  11445. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  11446. for a list of supported timezone IDs. Defaults to the system timezone.
  11447. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  11448. permissions : Union[Sequence[str], None]
  11449. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  11450. more details. Defaults to none.
  11451. extra_http_headers : Union[Dict[str, str], None]
  11452. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  11453. offline : Union[bool, None]
  11454. Whether to emulate network being offline. Defaults to `false`. Learn more about
  11455. [network emulation](../emulation.md#offline).
  11456. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  11457. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  11458. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  11459. device_scale_factor : Union[float, None]
  11460. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  11461. [emulating devices with device scale factor](../emulation.md#devices).
  11462. is_mobile : Union[bool, None]
  11463. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  11464. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  11465. about [mobile emulation](../emulation.md#ismobile).
  11466. has_touch : Union[bool, None]
  11467. Specifies if viewport supports touch events. Defaults to false. Learn more about
  11468. [mobile emulation](../emulation.md#devices).
  11469. color_scheme : Union["dark", "light", "no-preference", "null", None]
  11470. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  11471. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  11472. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  11473. reduced_motion : Union["no-preference", "null", "reduce", None]
  11474. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  11475. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11476. `'no-preference'`.
  11477. forced_colors : Union["active", "none", "null", None]
  11478. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  11479. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11480. `'none'`.
  11481. contrast : Union["more", "no-preference", "null", None]
  11482. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  11483. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11484. `'no-preference'`.
  11485. accept_downloads : Union[bool, None]
  11486. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  11487. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  11488. Network proxy settings to use with this context. Defaults to none.
  11489. record_har_path : Union[pathlib.Path, str, None]
  11490. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  11491. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  11492. for the HAR to be saved.
  11493. record_har_omit_content : Union[bool, None]
  11494. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  11495. record_video_dir : Union[pathlib.Path, str, None]
  11496. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  11497. sure to call `browser_context.close()` for videos to be saved.
  11498. record_video_size : Union[{width: int, height: int}, None]
  11499. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  11500. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  11501. will be scaled down if necessary to fit the specified size.
  11502. storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}, None]
  11503. Learn more about [storage state and auth](../auth.md).
  11504. Populates context with given storage state. This option can be used to initialize context with logged-in
  11505. information obtained via `browser_context.storage_state()`.
  11506. base_url : Union[str, None]
  11507. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  11508. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  11509. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  11510. corresponding URL. Unset by default. Examples:
  11511. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  11512. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  11513. `http://localhost:3000/foo/bar.html`
  11514. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  11515. `http://localhost:3000/bar.html`
  11516. strict_selectors : Union[bool, None]
  11517. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  11518. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  11519. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  11520. more about the strict mode.
  11521. service_workers : Union["allow", "block", None]
  11522. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  11523. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  11524. registered.
  11525. - `'block'`: Playwright will block all registration of Service Workers.
  11526. record_har_url_filter : Union[Pattern[str], str, None]
  11527. record_har_mode : Union["full", "minimal", None]
  11528. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  11529. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  11530. record_har_content : Union["attach", "embed", "omit", None]
  11531. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  11532. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  11533. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  11534. client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None]
  11535. TLS Client Authentication allows the server to request a client certificate and verify it.
  11536. **Details**
  11537. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  11538. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  11539. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  11540. with an exact match to the request origin that the certificate is valid for.
  11541. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  11542. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  11543. does not match any of the domains you plan to visit.
  11544. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  11545. work by replacing `localhost` with `local.playwright`.
  11546. Returns
  11547. -------
  11548. BrowserContext
  11549. """
  11550. return mapping.from_impl(
  11551. self._sync(
  11552. self._impl_obj.new_context(
  11553. viewport=viewport,
  11554. screen=screen,
  11555. noViewport=no_viewport,
  11556. ignoreHTTPSErrors=ignore_https_errors,
  11557. javaScriptEnabled=java_script_enabled,
  11558. bypassCSP=bypass_csp,
  11559. userAgent=user_agent,
  11560. locale=locale,
  11561. timezoneId=timezone_id,
  11562. geolocation=geolocation,
  11563. permissions=mapping.to_impl(permissions),
  11564. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  11565. offline=offline,
  11566. httpCredentials=http_credentials,
  11567. deviceScaleFactor=device_scale_factor,
  11568. isMobile=is_mobile,
  11569. hasTouch=has_touch,
  11570. colorScheme=color_scheme,
  11571. reducedMotion=reduced_motion,
  11572. forcedColors=forced_colors,
  11573. contrast=contrast,
  11574. acceptDownloads=accept_downloads,
  11575. defaultBrowserType=default_browser_type,
  11576. proxy=proxy,
  11577. recordHarPath=record_har_path,
  11578. recordHarOmitContent=record_har_omit_content,
  11579. recordVideoDir=record_video_dir,
  11580. recordVideoSize=record_video_size,
  11581. storageState=storage_state,
  11582. baseURL=base_url,
  11583. strictSelectors=strict_selectors,
  11584. serviceWorkers=service_workers,
  11585. recordHarUrlFilter=record_har_url_filter,
  11586. recordHarMode=record_har_mode,
  11587. recordHarContent=record_har_content,
  11588. clientCertificates=client_certificates,
  11589. )
  11590. )
  11591. )
  11592. def new_page(
  11593. self,
  11594. *,
  11595. viewport: typing.Optional[ViewportSize] = None,
  11596. screen: typing.Optional[ViewportSize] = None,
  11597. no_viewport: typing.Optional[bool] = None,
  11598. ignore_https_errors: typing.Optional[bool] = None,
  11599. java_script_enabled: typing.Optional[bool] = None,
  11600. bypass_csp: typing.Optional[bool] = None,
  11601. user_agent: typing.Optional[str] = None,
  11602. locale: typing.Optional[str] = None,
  11603. timezone_id: typing.Optional[str] = None,
  11604. geolocation: typing.Optional[Geolocation] = None,
  11605. permissions: typing.Optional[typing.Sequence[str]] = None,
  11606. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  11607. offline: typing.Optional[bool] = None,
  11608. http_credentials: typing.Optional[HttpCredentials] = None,
  11609. device_scale_factor: typing.Optional[float] = None,
  11610. is_mobile: typing.Optional[bool] = None,
  11611. has_touch: typing.Optional[bool] = None,
  11612. color_scheme: typing.Optional[
  11613. Literal["dark", "light", "no-preference", "null"]
  11614. ] = None,
  11615. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  11616. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  11617. reduced_motion: typing.Optional[
  11618. Literal["no-preference", "null", "reduce"]
  11619. ] = None,
  11620. accept_downloads: typing.Optional[bool] = None,
  11621. default_browser_type: typing.Optional[str] = None,
  11622. proxy: typing.Optional[ProxySettings] = None,
  11623. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11624. record_har_omit_content: typing.Optional[bool] = None,
  11625. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11626. record_video_size: typing.Optional[ViewportSize] = None,
  11627. storage_state: typing.Optional[
  11628. typing.Union[StorageState, str, pathlib.Path]
  11629. ] = None,
  11630. base_url: typing.Optional[str] = None,
  11631. strict_selectors: typing.Optional[bool] = None,
  11632. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  11633. record_har_url_filter: typing.Optional[
  11634. typing.Union[typing.Pattern[str], str]
  11635. ] = None,
  11636. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  11637. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  11638. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  11639. ) -> "Page":
  11640. """Browser.new_page
  11641. Creates a new page in a new browser context. Closing this page will close the context as well.
  11642. This is a convenience API that should only be used for the single-page scenarios and short snippets. Production
  11643. code and testing frameworks should explicitly create `browser.new_context()` followed by the
  11644. `browser_context.new_page()` to control their exact life times.
  11645. Parameters
  11646. ----------
  11647. viewport : Union[{width: int, height: int}, None]
  11648. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  11649. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  11650. screen : Union[{width: int, height: int}, None]
  11651. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  11652. `viewport` is set.
  11653. no_viewport : Union[bool, None]
  11654. Does not enforce fixed viewport, allows resizing window in the headed mode.
  11655. ignore_https_errors : Union[bool, None]
  11656. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  11657. java_script_enabled : Union[bool, None]
  11658. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  11659. [disabling JavaScript](../emulation.md#javascript-enabled).
  11660. bypass_csp : Union[bool, None]
  11661. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  11662. user_agent : Union[str, None]
  11663. Specific user agent to use in this context.
  11664. locale : Union[str, None]
  11665. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  11666. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  11667. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  11668. timezone_id : Union[str, None]
  11669. Changes the timezone of the context. See
  11670. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  11671. for a list of supported timezone IDs. Defaults to the system timezone.
  11672. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  11673. permissions : Union[Sequence[str], None]
  11674. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  11675. more details. Defaults to none.
  11676. extra_http_headers : Union[Dict[str, str], None]
  11677. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  11678. offline : Union[bool, None]
  11679. Whether to emulate network being offline. Defaults to `false`. Learn more about
  11680. [network emulation](../emulation.md#offline).
  11681. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  11682. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  11683. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  11684. device_scale_factor : Union[float, None]
  11685. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  11686. [emulating devices with device scale factor](../emulation.md#devices).
  11687. is_mobile : Union[bool, None]
  11688. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  11689. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  11690. about [mobile emulation](../emulation.md#ismobile).
  11691. has_touch : Union[bool, None]
  11692. Specifies if viewport supports touch events. Defaults to false. Learn more about
  11693. [mobile emulation](../emulation.md#devices).
  11694. color_scheme : Union["dark", "light", "no-preference", "null", None]
  11695. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  11696. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  11697. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  11698. forced_colors : Union["active", "none", "null", None]
  11699. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  11700. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11701. `'none'`.
  11702. contrast : Union["more", "no-preference", "null", None]
  11703. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  11704. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11705. `'no-preference'`.
  11706. reduced_motion : Union["no-preference", "null", "reduce", None]
  11707. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  11708. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11709. `'no-preference'`.
  11710. accept_downloads : Union[bool, None]
  11711. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  11712. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  11713. Network proxy settings to use with this context. Defaults to none.
  11714. record_har_path : Union[pathlib.Path, str, None]
  11715. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  11716. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  11717. for the HAR to be saved.
  11718. record_har_omit_content : Union[bool, None]
  11719. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  11720. record_video_dir : Union[pathlib.Path, str, None]
  11721. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  11722. sure to call `browser_context.close()` for videos to be saved.
  11723. record_video_size : Union[{width: int, height: int}, None]
  11724. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  11725. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  11726. will be scaled down if necessary to fit the specified size.
  11727. storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}, None]
  11728. Learn more about [storage state and auth](../auth.md).
  11729. Populates context with given storage state. This option can be used to initialize context with logged-in
  11730. information obtained via `browser_context.storage_state()`.
  11731. base_url : Union[str, None]
  11732. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  11733. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  11734. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  11735. corresponding URL. Unset by default. Examples:
  11736. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  11737. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  11738. `http://localhost:3000/foo/bar.html`
  11739. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  11740. `http://localhost:3000/bar.html`
  11741. strict_selectors : Union[bool, None]
  11742. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  11743. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  11744. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  11745. more about the strict mode.
  11746. service_workers : Union["allow", "block", None]
  11747. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  11748. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  11749. registered.
  11750. - `'block'`: Playwright will block all registration of Service Workers.
  11751. record_har_url_filter : Union[Pattern[str], str, None]
  11752. record_har_mode : Union["full", "minimal", None]
  11753. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  11754. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  11755. record_har_content : Union["attach", "embed", "omit", None]
  11756. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  11757. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  11758. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  11759. client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None]
  11760. TLS Client Authentication allows the server to request a client certificate and verify it.
  11761. **Details**
  11762. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  11763. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  11764. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  11765. with an exact match to the request origin that the certificate is valid for.
  11766. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  11767. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  11768. does not match any of the domains you plan to visit.
  11769. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  11770. work by replacing `localhost` with `local.playwright`.
  11771. Returns
  11772. -------
  11773. Page
  11774. """
  11775. return mapping.from_impl(
  11776. self._sync(
  11777. self._impl_obj.new_page(
  11778. viewport=viewport,
  11779. screen=screen,
  11780. noViewport=no_viewport,
  11781. ignoreHTTPSErrors=ignore_https_errors,
  11782. javaScriptEnabled=java_script_enabled,
  11783. bypassCSP=bypass_csp,
  11784. userAgent=user_agent,
  11785. locale=locale,
  11786. timezoneId=timezone_id,
  11787. geolocation=geolocation,
  11788. permissions=mapping.to_impl(permissions),
  11789. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  11790. offline=offline,
  11791. httpCredentials=http_credentials,
  11792. deviceScaleFactor=device_scale_factor,
  11793. isMobile=is_mobile,
  11794. hasTouch=has_touch,
  11795. colorScheme=color_scheme,
  11796. forcedColors=forced_colors,
  11797. contrast=contrast,
  11798. reducedMotion=reduced_motion,
  11799. acceptDownloads=accept_downloads,
  11800. defaultBrowserType=default_browser_type,
  11801. proxy=proxy,
  11802. recordHarPath=record_har_path,
  11803. recordHarOmitContent=record_har_omit_content,
  11804. recordVideoDir=record_video_dir,
  11805. recordVideoSize=record_video_size,
  11806. storageState=storage_state,
  11807. baseURL=base_url,
  11808. strictSelectors=strict_selectors,
  11809. serviceWorkers=service_workers,
  11810. recordHarUrlFilter=record_har_url_filter,
  11811. recordHarMode=record_har_mode,
  11812. recordHarContent=record_har_content,
  11813. clientCertificates=client_certificates,
  11814. )
  11815. )
  11816. )
  11817. def close(self, *, reason: typing.Optional[str] = None) -> None:
  11818. """Browser.close
  11819. In case this browser is obtained using `browser_type.launch()`, closes the browser and all of its pages (if
  11820. any were opened).
  11821. In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from
  11822. the browser server.
  11823. **NOTE** This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close
  11824. events, call `browser_context.close()` on any `BrowserContext` instances you explicitly created earlier
  11825. using `browser.new_context()` **before** calling `browser.close()`.
  11826. The `Browser` object itself is considered to be disposed and cannot be used anymore.
  11827. Parameters
  11828. ----------
  11829. reason : Union[str, None]
  11830. The reason to be reported to the operations interrupted by the browser closure.
  11831. """
  11832. return mapping.from_maybe_impl(self._sync(self._impl_obj.close(reason=reason)))
  11833. def new_browser_cdp_session(self) -> "CDPSession":
  11834. """Browser.new_browser_cdp_session
  11835. **NOTE** CDP Sessions are only supported on Chromium-based browsers.
  11836. Returns the newly created browser session.
  11837. Returns
  11838. -------
  11839. CDPSession
  11840. """
  11841. return mapping.from_impl(self._sync(self._impl_obj.new_browser_cdp_session()))
  11842. def start_tracing(
  11843. self,
  11844. *,
  11845. page: typing.Optional["Page"] = None,
  11846. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11847. screenshots: typing.Optional[bool] = None,
  11848. categories: typing.Optional[typing.Sequence[str]] = None,
  11849. ) -> None:
  11850. """Browser.start_tracing
  11851. **NOTE** This API controls
  11852. [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
  11853. chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
  11854. [here](https://playwright.dev/python/docs/api/class-tracing).
  11855. You can use `browser.start_tracing()` and `browser.stop_tracing()` to create a trace file that can be
  11856. opened in Chrome DevTools performance panel.
  11857. **Usage**
  11858. ```py
  11859. browser.start_tracing(page, path=\"trace.json\")
  11860. page.goto(\"https://www.google.com\")
  11861. browser.stop_tracing()
  11862. ```
  11863. Parameters
  11864. ----------
  11865. page : Union[Page, None]
  11866. Optional, if specified, tracing includes screenshots of the given page.
  11867. path : Union[pathlib.Path, str, None]
  11868. A path to write the trace file to.
  11869. screenshots : Union[bool, None]
  11870. captures screenshots in the trace.
  11871. categories : Union[Sequence[str], None]
  11872. specify custom categories to use instead of default.
  11873. """
  11874. return mapping.from_maybe_impl(
  11875. self._sync(
  11876. self._impl_obj.start_tracing(
  11877. page=page._impl_obj if page else None,
  11878. path=path,
  11879. screenshots=screenshots,
  11880. categories=mapping.to_impl(categories),
  11881. )
  11882. )
  11883. )
  11884. def stop_tracing(self) -> bytes:
  11885. """Browser.stop_tracing
  11886. **NOTE** This API controls
  11887. [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
  11888. chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
  11889. [here](https://playwright.dev/python/docs/api/class-tracing).
  11890. Returns the buffer with trace data.
  11891. Returns
  11892. -------
  11893. bytes
  11894. """
  11895. return mapping.from_maybe_impl(self._sync(self._impl_obj.stop_tracing()))
  11896. mapping.register(BrowserImpl, Browser)
  11897. class BrowserType(SyncBase):
  11898. @property
  11899. def name(self) -> str:
  11900. """BrowserType.name
  11901. Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
  11902. Returns
  11903. -------
  11904. str
  11905. """
  11906. return mapping.from_maybe_impl(self._impl_obj.name)
  11907. @property
  11908. def executable_path(self) -> str:
  11909. """BrowserType.executable_path
  11910. A path where Playwright expects to find a bundled browser executable.
  11911. Returns
  11912. -------
  11913. str
  11914. """
  11915. return mapping.from_maybe_impl(self._impl_obj.executable_path)
  11916. def launch(
  11917. self,
  11918. *,
  11919. executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11920. channel: typing.Optional[str] = None,
  11921. args: typing.Optional[typing.Sequence[str]] = None,
  11922. ignore_default_args: typing.Optional[
  11923. typing.Union[bool, typing.Sequence[str]]
  11924. ] = None,
  11925. handle_sigint: typing.Optional[bool] = None,
  11926. handle_sigterm: typing.Optional[bool] = None,
  11927. handle_sighup: typing.Optional[bool] = None,
  11928. timeout: typing.Optional[float] = None,
  11929. env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  11930. headless: typing.Optional[bool] = None,
  11931. proxy: typing.Optional[ProxySettings] = None,
  11932. downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11933. slow_mo: typing.Optional[float] = None,
  11934. traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11935. chromium_sandbox: typing.Optional[bool] = None,
  11936. firefox_user_prefs: typing.Optional[
  11937. typing.Dict[str, typing.Union[str, float, bool]]
  11938. ] = None,
  11939. ) -> "Browser":
  11940. """BrowserType.launch
  11941. Returns the browser instance.
  11942. **Usage**
  11943. You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
  11944. ```py
  11945. browser = playwright.chromium.launch( # or \"firefox\" or \"webkit\".
  11946. ignore_default_args=[\"--mute-audio\"]
  11947. )
  11948. ```
  11949. > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it
  11950. works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other
  11951. version. Use `executablePath` option with extreme caution.
  11952. >
  11953. > If Google Chrome (rather than Chromium) is preferred, a
  11954. [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
  11955. [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
  11956. >
  11957. > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs
  11958. for video playback. See
  11959. [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
  11960. other differences between Chromium and Chrome.
  11961. [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
  11962. describes some differences for Linux users.
  11963. Parameters
  11964. ----------
  11965. executable_path : Union[pathlib.Path, str, None]
  11966. Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
  11967. resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
  11968. Firefox or WebKit, use at your own risk.
  11969. channel : Union[str, None]
  11970. Browser distribution channel.
  11971. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
  11972. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
  11973. "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
  11974. args : Union[Sequence[str], None]
  11975. **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
  11976. Additional arguments to pass to the browser instance. The list of Chromium flags can be found
  11977. [here](https://peter.sh/experiments/chromium-command-line-switches/).
  11978. ignore_default_args : Union[Sequence[str], bool, None]
  11979. If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
  11980. given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
  11981. handle_sigint : Union[bool, None]
  11982. Close the browser process on Ctrl-C. Defaults to `true`.
  11983. handle_sigterm : Union[bool, None]
  11984. Close the browser process on SIGTERM. Defaults to `true`.
  11985. handle_sighup : Union[bool, None]
  11986. Close the browser process on SIGHUP. Defaults to `true`.
  11987. timeout : Union[float, None]
  11988. Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
  11989. to disable timeout.
  11990. env : Union[Dict[str, Union[bool, float, str]], None]
  11991. Specify environment variables that will be visible to the browser. Defaults to `process.env`.
  11992. headless : Union[bool, None]
  11993. Whether to run browser in headless mode. More details for
  11994. [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
  11995. [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
  11996. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  11997. Network proxy settings.
  11998. downloads_path : Union[pathlib.Path, str, None]
  11999. If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
  12000. is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
  12001. created in is closed.
  12002. slow_mo : Union[float, None]
  12003. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12004. on.
  12005. traces_dir : Union[pathlib.Path, str, None]
  12006. If specified, traces are saved into this directory.
  12007. chromium_sandbox : Union[bool, None]
  12008. Enable Chromium sandboxing. Defaults to `false`.
  12009. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
  12010. Firefox user preferences. Learn more about the Firefox user preferences at
  12011. [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
  12012. You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
  12013. `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
  12014. Returns
  12015. -------
  12016. Browser
  12017. """
  12018. return mapping.from_impl(
  12019. self._sync(
  12020. self._impl_obj.launch(
  12021. executablePath=executable_path,
  12022. channel=channel,
  12023. args=mapping.to_impl(args),
  12024. ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
  12025. handleSIGINT=handle_sigint,
  12026. handleSIGTERM=handle_sigterm,
  12027. handleSIGHUP=handle_sighup,
  12028. timeout=timeout,
  12029. env=mapping.to_impl(env),
  12030. headless=headless,
  12031. proxy=proxy,
  12032. downloadsPath=downloads_path,
  12033. slowMo=slow_mo,
  12034. tracesDir=traces_dir,
  12035. chromiumSandbox=chromium_sandbox,
  12036. firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
  12037. )
  12038. )
  12039. )
  12040. def launch_persistent_context(
  12041. self,
  12042. user_data_dir: typing.Union[str, pathlib.Path],
  12043. *,
  12044. channel: typing.Optional[str] = None,
  12045. executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12046. args: typing.Optional[typing.Sequence[str]] = None,
  12047. ignore_default_args: typing.Optional[
  12048. typing.Union[bool, typing.Sequence[str]]
  12049. ] = None,
  12050. handle_sigint: typing.Optional[bool] = None,
  12051. handle_sigterm: typing.Optional[bool] = None,
  12052. handle_sighup: typing.Optional[bool] = None,
  12053. timeout: typing.Optional[float] = None,
  12054. env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  12055. headless: typing.Optional[bool] = None,
  12056. proxy: typing.Optional[ProxySettings] = None,
  12057. downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12058. slow_mo: typing.Optional[float] = None,
  12059. viewport: typing.Optional[ViewportSize] = None,
  12060. screen: typing.Optional[ViewportSize] = None,
  12061. no_viewport: typing.Optional[bool] = None,
  12062. ignore_https_errors: typing.Optional[bool] = None,
  12063. java_script_enabled: typing.Optional[bool] = None,
  12064. bypass_csp: typing.Optional[bool] = None,
  12065. user_agent: typing.Optional[str] = None,
  12066. locale: typing.Optional[str] = None,
  12067. timezone_id: typing.Optional[str] = None,
  12068. geolocation: typing.Optional[Geolocation] = None,
  12069. permissions: typing.Optional[typing.Sequence[str]] = None,
  12070. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  12071. offline: typing.Optional[bool] = None,
  12072. http_credentials: typing.Optional[HttpCredentials] = None,
  12073. device_scale_factor: typing.Optional[float] = None,
  12074. is_mobile: typing.Optional[bool] = None,
  12075. has_touch: typing.Optional[bool] = None,
  12076. color_scheme: typing.Optional[
  12077. Literal["dark", "light", "no-preference", "null"]
  12078. ] = None,
  12079. reduced_motion: typing.Optional[
  12080. Literal["no-preference", "null", "reduce"]
  12081. ] = None,
  12082. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  12083. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  12084. accept_downloads: typing.Optional[bool] = None,
  12085. traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12086. chromium_sandbox: typing.Optional[bool] = None,
  12087. firefox_user_prefs: typing.Optional[
  12088. typing.Dict[str, typing.Union[str, float, bool]]
  12089. ] = None,
  12090. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12091. record_har_omit_content: typing.Optional[bool] = None,
  12092. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12093. record_video_size: typing.Optional[ViewportSize] = None,
  12094. base_url: typing.Optional[str] = None,
  12095. strict_selectors: typing.Optional[bool] = None,
  12096. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  12097. record_har_url_filter: typing.Optional[
  12098. typing.Union[typing.Pattern[str], str]
  12099. ] = None,
  12100. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  12101. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  12102. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  12103. ) -> "BrowserContext":
  12104. """BrowserType.launch_persistent_context
  12105. Returns the persistent browser context instance.
  12106. Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
  12107. context will automatically close the browser.
  12108. Parameters
  12109. ----------
  12110. user_data_dir : Union[pathlib.Path, str]
  12111. Path to a User Data Directory, which stores browser session data like cookies and local storage. Pass an empty
  12112. string to create a temporary directory.
  12113. More details for
  12114. [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
  12115. [Firefox](https://wiki.mozilla.org/Firefox/CommandLineOptions#User_profile). Chromium's user data directory is the
  12116. **parent** directory of the "Profile Path" seen at `chrome://version`.
  12117. Note that browsers do not allow launching multiple instances with the same User Data Directory.
  12118. **NOTE** Chromium/Chrome: Due to recent Chrome policy changes, automating the default Chrome user profile is not
  12119. supported. Pointing `userDataDir` to Chrome's main "User Data" directory (the profile used for your regular
  12120. browsing) may result in pages not loading or the browser exiting. Create and use a separate directory (for example,
  12121. an empty folder) as your automation profile instead. See https://developer.chrome.com/blog/remote-debugging-port
  12122. for details.
  12123. channel : Union[str, None]
  12124. Browser distribution channel.
  12125. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
  12126. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
  12127. "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
  12128. executable_path : Union[pathlib.Path, str, None]
  12129. Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
  12130. resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
  12131. Firefox or WebKit, use at your own risk.
  12132. args : Union[Sequence[str], None]
  12133. **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
  12134. Additional arguments to pass to the browser instance. The list of Chromium flags can be found
  12135. [here](https://peter.sh/experiments/chromium-command-line-switches/).
  12136. ignore_default_args : Union[Sequence[str], bool, None]
  12137. If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
  12138. given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
  12139. handle_sigint : Union[bool, None]
  12140. Close the browser process on Ctrl-C. Defaults to `true`.
  12141. handle_sigterm : Union[bool, None]
  12142. Close the browser process on SIGTERM. Defaults to `true`.
  12143. handle_sighup : Union[bool, None]
  12144. Close the browser process on SIGHUP. Defaults to `true`.
  12145. timeout : Union[float, None]
  12146. Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
  12147. to disable timeout.
  12148. env : Union[Dict[str, Union[bool, float, str]], None]
  12149. Specify environment variables that will be visible to the browser. Defaults to `process.env`.
  12150. headless : Union[bool, None]
  12151. Whether to run browser in headless mode. More details for
  12152. [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
  12153. [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
  12154. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  12155. Network proxy settings.
  12156. downloads_path : Union[pathlib.Path, str, None]
  12157. If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
  12158. is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
  12159. created in is closed.
  12160. slow_mo : Union[float, None]
  12161. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12162. on.
  12163. viewport : Union[{width: int, height: int}, None]
  12164. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  12165. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  12166. screen : Union[{width: int, height: int}, None]
  12167. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  12168. `viewport` is set.
  12169. no_viewport : Union[bool, None]
  12170. Does not enforce fixed viewport, allows resizing window in the headed mode.
  12171. ignore_https_errors : Union[bool, None]
  12172. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  12173. java_script_enabled : Union[bool, None]
  12174. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  12175. [disabling JavaScript](../emulation.md#javascript-enabled).
  12176. bypass_csp : Union[bool, None]
  12177. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  12178. user_agent : Union[str, None]
  12179. Specific user agent to use in this context.
  12180. locale : Union[str, None]
  12181. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  12182. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  12183. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  12184. timezone_id : Union[str, None]
  12185. Changes the timezone of the context. See
  12186. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  12187. for a list of supported timezone IDs. Defaults to the system timezone.
  12188. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  12189. permissions : Union[Sequence[str], None]
  12190. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  12191. more details. Defaults to none.
  12192. extra_http_headers : Union[Dict[str, str], None]
  12193. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  12194. offline : Union[bool, None]
  12195. Whether to emulate network being offline. Defaults to `false`. Learn more about
  12196. [network emulation](../emulation.md#offline).
  12197. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  12198. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  12199. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  12200. device_scale_factor : Union[float, None]
  12201. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  12202. [emulating devices with device scale factor](../emulation.md#devices).
  12203. is_mobile : Union[bool, None]
  12204. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  12205. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  12206. about [mobile emulation](../emulation.md#ismobile).
  12207. has_touch : Union[bool, None]
  12208. Specifies if viewport supports touch events. Defaults to false. Learn more about
  12209. [mobile emulation](../emulation.md#devices).
  12210. color_scheme : Union["dark", "light", "no-preference", "null", None]
  12211. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  12212. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  12213. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  12214. reduced_motion : Union["no-preference", "null", "reduce", None]
  12215. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  12216. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12217. `'no-preference'`.
  12218. forced_colors : Union["active", "none", "null", None]
  12219. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  12220. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12221. `'none'`.
  12222. contrast : Union["more", "no-preference", "null", None]
  12223. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  12224. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12225. `'no-preference'`.
  12226. accept_downloads : Union[bool, None]
  12227. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  12228. traces_dir : Union[pathlib.Path, str, None]
  12229. If specified, traces are saved into this directory.
  12230. chromium_sandbox : Union[bool, None]
  12231. Enable Chromium sandboxing. Defaults to `false`.
  12232. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
  12233. Firefox user preferences. Learn more about the Firefox user preferences at
  12234. [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
  12235. You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
  12236. `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
  12237. record_har_path : Union[pathlib.Path, str, None]
  12238. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  12239. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  12240. for the HAR to be saved.
  12241. record_har_omit_content : Union[bool, None]
  12242. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  12243. record_video_dir : Union[pathlib.Path, str, None]
  12244. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  12245. sure to call `browser_context.close()` for videos to be saved.
  12246. record_video_size : Union[{width: int, height: int}, None]
  12247. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  12248. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  12249. will be scaled down if necessary to fit the specified size.
  12250. base_url : Union[str, None]
  12251. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  12252. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  12253. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  12254. corresponding URL. Unset by default. Examples:
  12255. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  12256. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  12257. `http://localhost:3000/foo/bar.html`
  12258. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  12259. `http://localhost:3000/bar.html`
  12260. strict_selectors : Union[bool, None]
  12261. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  12262. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  12263. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  12264. more about the strict mode.
  12265. service_workers : Union["allow", "block", None]
  12266. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  12267. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  12268. registered.
  12269. - `'block'`: Playwright will block all registration of Service Workers.
  12270. record_har_url_filter : Union[Pattern[str], str, None]
  12271. record_har_mode : Union["full", "minimal", None]
  12272. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  12273. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  12274. record_har_content : Union["attach", "embed", "omit", None]
  12275. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  12276. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  12277. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  12278. client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None]
  12279. TLS Client Authentication allows the server to request a client certificate and verify it.
  12280. **Details**
  12281. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  12282. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  12283. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  12284. with an exact match to the request origin that the certificate is valid for.
  12285. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  12286. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  12287. does not match any of the domains you plan to visit.
  12288. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  12289. work by replacing `localhost` with `local.playwright`.
  12290. Returns
  12291. -------
  12292. BrowserContext
  12293. """
  12294. return mapping.from_impl(
  12295. self._sync(
  12296. self._impl_obj.launch_persistent_context(
  12297. userDataDir=user_data_dir,
  12298. channel=channel,
  12299. executablePath=executable_path,
  12300. args=mapping.to_impl(args),
  12301. ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
  12302. handleSIGINT=handle_sigint,
  12303. handleSIGTERM=handle_sigterm,
  12304. handleSIGHUP=handle_sighup,
  12305. timeout=timeout,
  12306. env=mapping.to_impl(env),
  12307. headless=headless,
  12308. proxy=proxy,
  12309. downloadsPath=downloads_path,
  12310. slowMo=slow_mo,
  12311. viewport=viewport,
  12312. screen=screen,
  12313. noViewport=no_viewport,
  12314. ignoreHTTPSErrors=ignore_https_errors,
  12315. javaScriptEnabled=java_script_enabled,
  12316. bypassCSP=bypass_csp,
  12317. userAgent=user_agent,
  12318. locale=locale,
  12319. timezoneId=timezone_id,
  12320. geolocation=geolocation,
  12321. permissions=mapping.to_impl(permissions),
  12322. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  12323. offline=offline,
  12324. httpCredentials=http_credentials,
  12325. deviceScaleFactor=device_scale_factor,
  12326. isMobile=is_mobile,
  12327. hasTouch=has_touch,
  12328. colorScheme=color_scheme,
  12329. reducedMotion=reduced_motion,
  12330. forcedColors=forced_colors,
  12331. contrast=contrast,
  12332. acceptDownloads=accept_downloads,
  12333. tracesDir=traces_dir,
  12334. chromiumSandbox=chromium_sandbox,
  12335. firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
  12336. recordHarPath=record_har_path,
  12337. recordHarOmitContent=record_har_omit_content,
  12338. recordVideoDir=record_video_dir,
  12339. recordVideoSize=record_video_size,
  12340. baseURL=base_url,
  12341. strictSelectors=strict_selectors,
  12342. serviceWorkers=service_workers,
  12343. recordHarUrlFilter=record_har_url_filter,
  12344. recordHarMode=record_har_mode,
  12345. recordHarContent=record_har_content,
  12346. clientCertificates=client_certificates,
  12347. )
  12348. )
  12349. )
  12350. def connect_over_cdp(
  12351. self,
  12352. endpoint_url: str,
  12353. *,
  12354. timeout: typing.Optional[float] = None,
  12355. slow_mo: typing.Optional[float] = None,
  12356. headers: typing.Optional[typing.Dict[str, str]] = None,
  12357. is_local: typing.Optional[bool] = None,
  12358. ) -> "Browser":
  12359. """BrowserType.connect_over_cdp
  12360. This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
  12361. The default browser context is accessible via `browser.contexts()`.
  12362. **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
  12363. **NOTE** This connection is significantly lower fidelity than the Playwright protocol connection via
  12364. `browser_type.connect()`. If you are experiencing issues or attempting to use advanced functionality, you
  12365. probably want to use `browser_type.connect()`.
  12366. **Usage**
  12367. ```py
  12368. browser = playwright.chromium.connect_over_cdp(\"http://localhost:9222\")
  12369. default_context = browser.contexts[0]
  12370. page = default_context.pages[0]
  12371. ```
  12372. Parameters
  12373. ----------
  12374. endpoint_url : str
  12375. A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
  12376. `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
  12377. timeout : Union[float, None]
  12378. Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
  12379. `0` to disable timeout.
  12380. slow_mo : Union[float, None]
  12381. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12382. on. Defaults to 0.
  12383. headers : Union[Dict[str, str], None]
  12384. Additional HTTP headers to be sent with connect request. Optional.
  12385. is_local : Union[bool, None]
  12386. Tells Playwright that it runs on the same host as the CDP server. It will enable certain optimizations that rely
  12387. upon the file system being the same between Playwright and the Browser.
  12388. Returns
  12389. -------
  12390. Browser
  12391. """
  12392. return mapping.from_impl(
  12393. self._sync(
  12394. self._impl_obj.connect_over_cdp(
  12395. endpointURL=endpoint_url,
  12396. timeout=timeout,
  12397. slowMo=slow_mo,
  12398. headers=mapping.to_impl(headers),
  12399. isLocal=is_local,
  12400. )
  12401. )
  12402. )
  12403. def connect(
  12404. self,
  12405. ws_endpoint: str,
  12406. *,
  12407. timeout: typing.Optional[float] = None,
  12408. slow_mo: typing.Optional[float] = None,
  12409. headers: typing.Optional[typing.Dict[str, str]] = None,
  12410. expose_network: typing.Optional[str] = None,
  12411. ) -> "Browser":
  12412. """BrowserType.connect
  12413. This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js.
  12414. **NOTE** The major and minor version of the Playwright instance that connects needs to match the version of
  12415. Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
  12416. Parameters
  12417. ----------
  12418. ws_endpoint : str
  12419. A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`.
  12420. timeout : Union[float, None]
  12421. Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout).
  12422. slow_mo : Union[float, None]
  12423. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12424. on. Defaults to 0.
  12425. headers : Union[Dict[str, str], None]
  12426. Additional HTTP headers to be sent with web socket connect request. Optional.
  12427. expose_network : Union[str, None]
  12428. This option exposes network available on the connecting client to the browser being connected to. Consists of a
  12429. list of rules separated by comma.
  12430. Available rules:
  12431. 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
  12432. 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
  12433. 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
  12434. Some common examples:
  12435. 1. `"*"` to expose all network.
  12436. 1. `"<loopback>"` to expose localhost network.
  12437. 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to expose test/staging deployments and
  12438. localhost.
  12439. Returns
  12440. -------
  12441. Browser
  12442. """
  12443. return mapping.from_impl(
  12444. self._sync(
  12445. self._impl_obj.connect(
  12446. wsEndpoint=ws_endpoint,
  12447. timeout=timeout,
  12448. slowMo=slow_mo,
  12449. headers=mapping.to_impl(headers),
  12450. exposeNetwork=expose_network,
  12451. )
  12452. )
  12453. )
  12454. mapping.register(BrowserTypeImpl, BrowserType)
  12455. class Playwright(SyncBase):
  12456. @property
  12457. def devices(self) -> typing.Dict:
  12458. """Playwright.devices
  12459. Returns a dictionary of devices to be used with `browser.new_context()` or `browser.new_page()`.
  12460. ```py
  12461. from playwright.sync_api import sync_playwright, Playwright
  12462. def run(playwright: Playwright):
  12463. webkit = playwright.webkit
  12464. iphone = playwright.devices[\"iPhone 6\"]
  12465. browser = webkit.launch()
  12466. context = browser.new_context(**iphone)
  12467. page = context.new_page()
  12468. page.goto(\"http://example.com\")
  12469. # other actions...
  12470. browser.close()
  12471. with sync_playwright() as playwright:
  12472. run(playwright)
  12473. ```
  12474. Returns
  12475. -------
  12476. Dict
  12477. """
  12478. return mapping.from_maybe_impl(self._impl_obj.devices)
  12479. @property
  12480. def selectors(self) -> "Selectors":
  12481. """Playwright.selectors
  12482. Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/python/docs/extensibility) for more
  12483. information.
  12484. Returns
  12485. -------
  12486. Selectors
  12487. """
  12488. return mapping.from_impl(self._impl_obj.selectors)
  12489. @property
  12490. def chromium(self) -> "BrowserType":
  12491. """Playwright.chromium
  12492. This object can be used to launch or connect to Chromium, returning instances of `Browser`.
  12493. Returns
  12494. -------
  12495. BrowserType
  12496. """
  12497. return mapping.from_impl(self._impl_obj.chromium)
  12498. @property
  12499. def firefox(self) -> "BrowserType":
  12500. """Playwright.firefox
  12501. This object can be used to launch or connect to Firefox, returning instances of `Browser`.
  12502. Returns
  12503. -------
  12504. BrowserType
  12505. """
  12506. return mapping.from_impl(self._impl_obj.firefox)
  12507. @property
  12508. def webkit(self) -> "BrowserType":
  12509. """Playwright.webkit
  12510. This object can be used to launch or connect to WebKit, returning instances of `Browser`.
  12511. Returns
  12512. -------
  12513. BrowserType
  12514. """
  12515. return mapping.from_impl(self._impl_obj.webkit)
  12516. @property
  12517. def request(self) -> "APIRequest":
  12518. """Playwright.request
  12519. Exposes API that can be used for the Web API testing.
  12520. Returns
  12521. -------
  12522. APIRequest
  12523. """
  12524. return mapping.from_impl(self._impl_obj.request)
  12525. def __getitem__(self, value: str) -> "BrowserType":
  12526. return mapping.from_impl(self._impl_obj.__getitem__(value=value))
  12527. def stop(self) -> None:
  12528. """Playwright.stop
  12529. Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful
  12530. in REPL applications.
  12531. ```py
  12532. from playwright.sync_api import sync_playwright
  12533. playwright = sync_playwright().start()
  12534. browser = playwright.chromium.launch()
  12535. page = browser.new_page()
  12536. page.goto(\"https://playwright.dev/\")
  12537. page.screenshot(path=\"example.png\")
  12538. browser.close()
  12539. playwright.stop()
  12540. ```
  12541. """
  12542. return mapping.from_maybe_impl(self._sync(self._impl_obj.stop()))
  12543. mapping.register(PlaywrightImpl, Playwright)
  12544. class Tracing(SyncBase):
  12545. def start(
  12546. self,
  12547. *,
  12548. name: typing.Optional[str] = None,
  12549. title: typing.Optional[str] = None,
  12550. snapshots: typing.Optional[bool] = None,
  12551. screenshots: typing.Optional[bool] = None,
  12552. sources: typing.Optional[bool] = None,
  12553. ) -> None:
  12554. """Tracing.start
  12555. Start tracing.
  12556. **NOTE** You probably want to
  12557. [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead
  12558. of using `Tracing.start`.
  12559. The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions
  12560. (like `expect` calls). We recommend
  12561. [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),
  12562. which includes those assertions and provides a more complete trace for debugging test failures.
  12563. **Usage**
  12564. ```py
  12565. context.tracing.start(screenshots=True, snapshots=True)
  12566. page = context.new_page()
  12567. page.goto(\"https://playwright.dev\")
  12568. context.tracing.stop(path = \"trace.zip\")
  12569. ```
  12570. Parameters
  12571. ----------
  12572. name : Union[str, None]
  12573. If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
  12574. `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
  12575. need to pass `path` option to `tracing.stop()` instead.
  12576. title : Union[str, None]
  12577. Trace name to be shown in the Trace Viewer.
  12578. snapshots : Union[bool, None]
  12579. If this option is true tracing will
  12580. - capture DOM snapshot on every action
  12581. - record network activity
  12582. screenshots : Union[bool, None]
  12583. Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.
  12584. sources : Union[bool, None]
  12585. Whether to include source files for trace actions.
  12586. """
  12587. return mapping.from_maybe_impl(
  12588. self._sync(
  12589. self._impl_obj.start(
  12590. name=name,
  12591. title=title,
  12592. snapshots=snapshots,
  12593. screenshots=screenshots,
  12594. sources=sources,
  12595. )
  12596. )
  12597. )
  12598. def start_chunk(
  12599. self, *, title: typing.Optional[str] = None, name: typing.Optional[str] = None
  12600. ) -> None:
  12601. """Tracing.start_chunk
  12602. Start a new trace chunk. If you'd like to record multiple traces on the same `BrowserContext`, use
  12603. `tracing.start()` once, and then create multiple trace chunks with `tracing.start_chunk()` and
  12604. `tracing.stop_chunk()`.
  12605. **Usage**
  12606. ```py
  12607. context.tracing.start(screenshots=True, snapshots=True)
  12608. page = context.new_page()
  12609. page.goto(\"https://playwright.dev\")
  12610. context.tracing.start_chunk()
  12611. page.get_by_text(\"Get Started\").click()
  12612. # Everything between start_chunk and stop_chunk will be recorded in the trace.
  12613. context.tracing.stop_chunk(path = \"trace1.zip\")
  12614. context.tracing.start_chunk()
  12615. page.goto(\"http://example.com\")
  12616. # Save a second trace file with different actions.
  12617. context.tracing.stop_chunk(path = \"trace2.zip\")
  12618. ```
  12619. Parameters
  12620. ----------
  12621. title : Union[str, None]
  12622. Trace name to be shown in the Trace Viewer.
  12623. name : Union[str, None]
  12624. If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
  12625. `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
  12626. need to pass `path` option to `tracing.stop_chunk()` instead.
  12627. """
  12628. return mapping.from_maybe_impl(
  12629. self._sync(self._impl_obj.start_chunk(title=title, name=name))
  12630. )
  12631. def stop_chunk(
  12632. self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
  12633. ) -> None:
  12634. """Tracing.stop_chunk
  12635. Stop the trace chunk. See `tracing.start_chunk()` for more details about multiple trace chunks.
  12636. Parameters
  12637. ----------
  12638. path : Union[pathlib.Path, str, None]
  12639. Export trace collected since the last `tracing.start_chunk()` call into the file with the given path.
  12640. """
  12641. return mapping.from_maybe_impl(self._sync(self._impl_obj.stop_chunk(path=path)))
  12642. def stop(
  12643. self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
  12644. ) -> None:
  12645. """Tracing.stop
  12646. Stop tracing.
  12647. Parameters
  12648. ----------
  12649. path : Union[pathlib.Path, str, None]
  12650. Export trace into the file with the given path.
  12651. """
  12652. return mapping.from_maybe_impl(self._sync(self._impl_obj.stop(path=path)))
  12653. def group(
  12654. self, name: str, *, location: typing.Optional[TracingGroupLocation] = None
  12655. ) -> None:
  12656. """Tracing.group
  12657. **NOTE** Use `test.step` instead when available.
  12658. Creates a new group within the trace, assigning any subsequent API calls to this group, until
  12659. `tracing.group_end()` is called. Groups can be nested and will be visible in the trace viewer.
  12660. **Usage**
  12661. ```py
  12662. # All actions between group and group_end
  12663. # will be shown in the trace viewer as a group.
  12664. await page.context.tracing.group(\"Open Playwright.dev > API\")
  12665. await page.goto(\"https://playwright.dev/\")
  12666. await page.get_by_role(\"link\", name=\"API\").click()
  12667. await page.context.tracing.group_end()
  12668. ```
  12669. Parameters
  12670. ----------
  12671. name : str
  12672. Group name shown in the trace viewer.
  12673. location : Union[{file: str, line: Union[int, None], column: Union[int, None]}, None]
  12674. Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the
  12675. `tracing.group()` call.
  12676. """
  12677. return mapping.from_maybe_impl(
  12678. self._sync(self._impl_obj.group(name=name, location=location))
  12679. )
  12680. def group_end(self) -> None:
  12681. """Tracing.group_end
  12682. Closes the last group created by `tracing.group()`.
  12683. """
  12684. return mapping.from_maybe_impl(self._sync(self._impl_obj.group_end()))
  12685. mapping.register(TracingImpl, Tracing)
  12686. class Locator(SyncBase):
  12687. @property
  12688. def page(self) -> "Page":
  12689. """Locator.page
  12690. A page this locator belongs to.
  12691. Returns
  12692. -------
  12693. Page
  12694. """
  12695. return mapping.from_impl(self._impl_obj.page)
  12696. @property
  12697. def first(self) -> "Locator":
  12698. """Locator.first
  12699. Returns locator to the first matching element.
  12700. Returns
  12701. -------
  12702. Locator
  12703. """
  12704. return mapping.from_impl(self._impl_obj.first)
  12705. @property
  12706. def last(self) -> "Locator":
  12707. """Locator.last
  12708. Returns locator to the last matching element.
  12709. **Usage**
  12710. ```py
  12711. banana = page.get_by_role(\"listitem\").last
  12712. ```
  12713. Returns
  12714. -------
  12715. Locator
  12716. """
  12717. return mapping.from_impl(self._impl_obj.last)
  12718. @property
  12719. def content_frame(self) -> "FrameLocator":
  12720. """Locator.content_frame
  12721. Returns a `FrameLocator` object pointing to the same `iframe` as this locator.
  12722. Useful when you have a `Locator` object obtained somewhere, and later on would like to interact with the content
  12723. inside the frame.
  12724. For a reverse operation, use `frame_locator.owner()`.
  12725. **Usage**
  12726. ```py
  12727. locator = page.locator(\"iframe[name=\\\"embedded\\\"]\")
  12728. # ...
  12729. frame_locator = locator.content_frame
  12730. frame_locator.get_by_role(\"button\").click()
  12731. ```
  12732. Returns
  12733. -------
  12734. FrameLocator
  12735. """
  12736. return mapping.from_impl(self._impl_obj.content_frame)
  12737. @property
  12738. def description(self) -> typing.Optional[str]:
  12739. """Locator.description
  12740. Returns locator description previously set with `locator.describe()`. Returns `null` if no custom
  12741. description has been set.
  12742. **Usage**
  12743. ```py
  12744. button = page.get_by_role(\"button\").describe(\"Subscribe button\")
  12745. print(button.description()) # \"Subscribe button\"
  12746. input = page.get_by_role(\"textbox\")
  12747. print(input.description()) # None
  12748. ```
  12749. Returns
  12750. -------
  12751. Union[str, None]
  12752. """
  12753. return mapping.from_maybe_impl(self._impl_obj.description)
  12754. def bounding_box(
  12755. self, *, timeout: typing.Optional[float] = None
  12756. ) -> typing.Optional[FloatRect]:
  12757. """Locator.bounding_box
  12758. This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
  12759. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
  12760. window.
  12761. **Details**
  12762. Scrolling affects the returned bounding box, similarly to
  12763. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  12764. That means `x` and/or `y` may be negative.
  12765. Elements from child frames return the bounding box relative to the main frame, unlike the
  12766. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  12767. Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
  12768. following snippet should click the center of the element.
  12769. **Usage**
  12770. ```py
  12771. box = page.get_by_role(\"button\").bounding_box()
  12772. page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
  12773. ```
  12774. Parameters
  12775. ----------
  12776. timeout : Union[float, None]
  12777. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12778. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12779. Returns
  12780. -------
  12781. Union[{x: float, y: float, width: float, height: float}, None]
  12782. """
  12783. return mapping.from_impl_nullable(
  12784. self._sync(self._impl_obj.bounding_box(timeout=timeout))
  12785. )
  12786. def check(
  12787. self,
  12788. *,
  12789. position: typing.Optional[Position] = None,
  12790. timeout: typing.Optional[float] = None,
  12791. force: typing.Optional[bool] = None,
  12792. no_wait_after: typing.Optional[bool] = None,
  12793. trial: typing.Optional[bool] = None,
  12794. ) -> None:
  12795. """Locator.check
  12796. Ensure that checkbox or radio element is checked.
  12797. **Details**
  12798. Performs the following steps:
  12799. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  12800. checked, this method returns immediately.
  12801. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  12802. 1. Scroll the element into view if needed.
  12803. 1. Use `page.mouse` to click in the center of the element.
  12804. 1. Ensure that the element is now checked. If not, this method throws.
  12805. If the element is detached from the DOM at any moment during the action, this method throws.
  12806. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  12807. Passing zero timeout disables this.
  12808. **Usage**
  12809. ```py
  12810. page.get_by_role(\"checkbox\").check()
  12811. ```
  12812. Parameters
  12813. ----------
  12814. position : Union[{x: float, y: float}, None]
  12815. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  12816. the element.
  12817. timeout : Union[float, None]
  12818. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12819. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12820. force : Union[bool, None]
  12821. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  12822. no_wait_after : Union[bool, None]
  12823. This option has no effect.
  12824. Deprecated: This option has no effect.
  12825. trial : Union[bool, None]
  12826. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  12827. to `false`. Useful to wait until the element is ready for the action without performing it.
  12828. """
  12829. return mapping.from_maybe_impl(
  12830. self._sync(
  12831. self._impl_obj.check(
  12832. position=position,
  12833. timeout=timeout,
  12834. force=force,
  12835. noWaitAfter=no_wait_after,
  12836. trial=trial,
  12837. )
  12838. )
  12839. )
  12840. def click(
  12841. self,
  12842. *,
  12843. modifiers: typing.Optional[
  12844. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  12845. ] = None,
  12846. position: typing.Optional[Position] = None,
  12847. delay: typing.Optional[float] = None,
  12848. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  12849. click_count: typing.Optional[int] = None,
  12850. timeout: typing.Optional[float] = None,
  12851. force: typing.Optional[bool] = None,
  12852. no_wait_after: typing.Optional[bool] = None,
  12853. trial: typing.Optional[bool] = None,
  12854. steps: typing.Optional[int] = None,
  12855. ) -> None:
  12856. """Locator.click
  12857. Click an element.
  12858. **Details**
  12859. This method clicks the element by performing the following steps:
  12860. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  12861. 1. Scroll the element into view if needed.
  12862. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  12863. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  12864. If the element is detached from the DOM at any moment during the action, this method throws.
  12865. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  12866. Passing zero timeout disables this.
  12867. **Usage**
  12868. Click a button:
  12869. ```py
  12870. page.get_by_role(\"button\").click()
  12871. ```
  12872. Shift-right-click at a specific position on a canvas:
  12873. ```py
  12874. page.locator(\"canvas\").click(
  12875. button=\"right\", modifiers=[\"Shift\"], position={\"x\": 23, \"y\": 32}
  12876. )
  12877. ```
  12878. Parameters
  12879. ----------
  12880. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  12881. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  12882. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  12883. "Control" on Windows and Linux and to "Meta" on macOS.
  12884. position : Union[{x: float, y: float}, None]
  12885. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  12886. the element.
  12887. delay : Union[float, None]
  12888. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  12889. button : Union["left", "middle", "right", None]
  12890. Defaults to `left`.
  12891. click_count : Union[int, None]
  12892. defaults to 1. See [UIEvent.detail].
  12893. timeout : Union[float, None]
  12894. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12895. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12896. force : Union[bool, None]
  12897. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  12898. no_wait_after : Union[bool, None]
  12899. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  12900. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  12901. navigating to inaccessible pages. Defaults to `false`.
  12902. Deprecated: This option will default to `true` in the future.
  12903. trial : Union[bool, None]
  12904. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  12905. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  12906. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  12907. are pressed.
  12908. steps : Union[int, None]
  12909. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  12910. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  12911. """
  12912. return mapping.from_maybe_impl(
  12913. self._sync(
  12914. self._impl_obj.click(
  12915. modifiers=mapping.to_impl(modifiers),
  12916. position=position,
  12917. delay=delay,
  12918. button=button,
  12919. clickCount=click_count,
  12920. timeout=timeout,
  12921. force=force,
  12922. noWaitAfter=no_wait_after,
  12923. trial=trial,
  12924. steps=steps,
  12925. )
  12926. )
  12927. )
  12928. def dblclick(
  12929. self,
  12930. *,
  12931. modifiers: typing.Optional[
  12932. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  12933. ] = None,
  12934. position: typing.Optional[Position] = None,
  12935. delay: typing.Optional[float] = None,
  12936. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  12937. timeout: typing.Optional[float] = None,
  12938. force: typing.Optional[bool] = None,
  12939. no_wait_after: typing.Optional[bool] = None,
  12940. trial: typing.Optional[bool] = None,
  12941. steps: typing.Optional[int] = None,
  12942. ) -> None:
  12943. """Locator.dblclick
  12944. Double-click an element.
  12945. **Details**
  12946. This method double clicks the element by performing the following steps:
  12947. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  12948. 1. Scroll the element into view if needed.
  12949. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  12950. If the element is detached from the DOM at any moment during the action, this method throws.
  12951. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  12952. Passing zero timeout disables this.
  12953. **NOTE** `element.dblclick()` dispatches two `click` events and a single `dblclick` event.
  12954. Parameters
  12955. ----------
  12956. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  12957. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  12958. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  12959. "Control" on Windows and Linux and to "Meta" on macOS.
  12960. position : Union[{x: float, y: float}, None]
  12961. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  12962. the element.
  12963. delay : Union[float, None]
  12964. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  12965. button : Union["left", "middle", "right", None]
  12966. Defaults to `left`.
  12967. timeout : Union[float, None]
  12968. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12969. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12970. force : Union[bool, None]
  12971. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  12972. no_wait_after : Union[bool, None]
  12973. This option has no effect.
  12974. Deprecated: This option has no effect.
  12975. trial : Union[bool, None]
  12976. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  12977. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  12978. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  12979. are pressed.
  12980. steps : Union[int, None]
  12981. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  12982. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  12983. """
  12984. return mapping.from_maybe_impl(
  12985. self._sync(
  12986. self._impl_obj.dblclick(
  12987. modifiers=mapping.to_impl(modifiers),
  12988. position=position,
  12989. delay=delay,
  12990. button=button,
  12991. timeout=timeout,
  12992. force=force,
  12993. noWaitAfter=no_wait_after,
  12994. trial=trial,
  12995. steps=steps,
  12996. )
  12997. )
  12998. )
  12999. def dispatch_event(
  13000. self,
  13001. type: str,
  13002. event_init: typing.Optional[typing.Dict] = None,
  13003. *,
  13004. timeout: typing.Optional[float] = None,
  13005. ) -> None:
  13006. """Locator.dispatch_event
  13007. Programmatically dispatch an event on the matching element.
  13008. **Usage**
  13009. ```py
  13010. locator.dispatch_event(\"click\")
  13011. ```
  13012. **Details**
  13013. The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
  13014. `click` is dispatched. This is equivalent to calling
  13015. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  13016. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  13017. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  13018. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  13019. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  13020. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  13021. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  13022. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  13023. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  13024. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  13025. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  13026. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  13027. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  13028. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  13029. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  13030. ```py
  13031. data_transfer = page.evaluate_handle(\"new DataTransfer()\")
  13032. locator.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
  13033. ```
  13034. Parameters
  13035. ----------
  13036. type : str
  13037. DOM event type: `"click"`, `"dragstart"`, etc.
  13038. event_init : Union[Dict, None]
  13039. Optional event-specific initialization properties.
  13040. timeout : Union[float, None]
  13041. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13042. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13043. """
  13044. return mapping.from_maybe_impl(
  13045. self._sync(
  13046. self._impl_obj.dispatch_event(
  13047. type=type, eventInit=mapping.to_impl(event_init), timeout=timeout
  13048. )
  13049. )
  13050. )
  13051. def evaluate(
  13052. self,
  13053. expression: str,
  13054. arg: typing.Optional[typing.Any] = None,
  13055. *,
  13056. timeout: typing.Optional[float] = None,
  13057. ) -> typing.Any:
  13058. """Locator.evaluate
  13059. Execute JavaScript code in the page, taking the matching element as an argument.
  13060. **Details**
  13061. Returns the return value of `expression`, called with the matching element as a first argument, and `arg` as a
  13062. second argument.
  13063. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  13064. If `expression` throws or rejects, this method throws.
  13065. **Usage**
  13066. Passing argument to `expression`:
  13067. ```py
  13068. result = page.get_by_testid(\"myId\").evaluate(\"(element, [x, y]) => element.textContent + ' ' + x * y\", [7, 8])
  13069. print(result) # prints \"myId text 56\"
  13070. ```
  13071. Parameters
  13072. ----------
  13073. expression : str
  13074. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  13075. function is automatically invoked.
  13076. arg : Union[Any, None]
  13077. Optional argument to pass to `expression`.
  13078. timeout : Union[float, None]
  13079. Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
  13080. evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  13081. Returns
  13082. -------
  13083. Any
  13084. """
  13085. return mapping.from_maybe_impl(
  13086. self._sync(
  13087. self._impl_obj.evaluate(
  13088. expression=expression, arg=mapping.to_impl(arg), timeout=timeout
  13089. )
  13090. )
  13091. )
  13092. def evaluate_all(
  13093. self, expression: str, arg: typing.Optional[typing.Any] = None
  13094. ) -> typing.Any:
  13095. """Locator.evaluate_all
  13096. Execute JavaScript code in the page, taking all matching elements as an argument.
  13097. **Details**
  13098. Returns the return value of `expression`, called with an array of all matching elements as a first argument, and
  13099. `arg` as a second argument.
  13100. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  13101. If `expression` throws or rejects, this method throws.
  13102. **Usage**
  13103. ```py
  13104. locator = page.locator(\"div\")
  13105. more_than_ten = locator.evaluate_all(\"(divs, min) => divs.length > min\", 10)
  13106. ```
  13107. Parameters
  13108. ----------
  13109. expression : str
  13110. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  13111. function is automatically invoked.
  13112. arg : Union[Any, None]
  13113. Optional argument to pass to `expression`.
  13114. Returns
  13115. -------
  13116. Any
  13117. """
  13118. return mapping.from_maybe_impl(
  13119. self._sync(
  13120. self._impl_obj.evaluate_all(
  13121. expression=expression, arg=mapping.to_impl(arg)
  13122. )
  13123. )
  13124. )
  13125. def evaluate_handle(
  13126. self,
  13127. expression: str,
  13128. arg: typing.Optional[typing.Any] = None,
  13129. *,
  13130. timeout: typing.Optional[float] = None,
  13131. ) -> "JSHandle":
  13132. """Locator.evaluate_handle
  13133. Execute JavaScript code in the page, taking the matching element as an argument, and return a `JSHandle` with the
  13134. result.
  13135. **Details**
  13136. Returns the return value of `expression` as a`JSHandle`, called with the matching element as a first argument, and
  13137. `arg` as a second argument.
  13138. The only difference between `locator.evaluate()` and `locator.evaluate_handle()` is that
  13139. `locator.evaluate_handle()` returns `JSHandle`.
  13140. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  13141. If `expression` throws or rejects, this method throws.
  13142. See `page.evaluate_handle()` for more details.
  13143. Parameters
  13144. ----------
  13145. expression : str
  13146. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  13147. function is automatically invoked.
  13148. arg : Union[Any, None]
  13149. Optional argument to pass to `expression`.
  13150. timeout : Union[float, None]
  13151. Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
  13152. evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  13153. Returns
  13154. -------
  13155. JSHandle
  13156. """
  13157. return mapping.from_impl(
  13158. self._sync(
  13159. self._impl_obj.evaluate_handle(
  13160. expression=expression, arg=mapping.to_impl(arg), timeout=timeout
  13161. )
  13162. )
  13163. )
  13164. def fill(
  13165. self,
  13166. value: str,
  13167. *,
  13168. timeout: typing.Optional[float] = None,
  13169. no_wait_after: typing.Optional[bool] = None,
  13170. force: typing.Optional[bool] = None,
  13171. ) -> None:
  13172. """Locator.fill
  13173. Set a value to the input field.
  13174. **Usage**
  13175. ```py
  13176. page.get_by_role(\"textbox\").fill(\"example value\")
  13177. ```
  13178. **Details**
  13179. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
  13180. `input` event after filling. Note that you can pass an empty string to clear the input field.
  13181. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  13182. error. However, if the element is inside the `<label>` element that has an associated
  13183. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  13184. instead.
  13185. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  13186. Parameters
  13187. ----------
  13188. value : str
  13189. Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
  13190. timeout : Union[float, None]
  13191. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13192. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13193. no_wait_after : Union[bool, None]
  13194. This option has no effect.
  13195. Deprecated: This option has no effect.
  13196. force : Union[bool, None]
  13197. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13198. """
  13199. return mapping.from_maybe_impl(
  13200. self._sync(
  13201. self._impl_obj.fill(
  13202. value=value, timeout=timeout, noWaitAfter=no_wait_after, force=force
  13203. )
  13204. )
  13205. )
  13206. def clear(
  13207. self,
  13208. *,
  13209. timeout: typing.Optional[float] = None,
  13210. no_wait_after: typing.Optional[bool] = None,
  13211. force: typing.Optional[bool] = None,
  13212. ) -> None:
  13213. """Locator.clear
  13214. Clear the input field.
  13215. **Details**
  13216. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, clears it and triggers an
  13217. `input` event after clearing.
  13218. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  13219. error. However, if the element is inside the `<label>` element that has an associated
  13220. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
  13221. instead.
  13222. **Usage**
  13223. ```py
  13224. page.get_by_role(\"textbox\").clear()
  13225. ```
  13226. Parameters
  13227. ----------
  13228. timeout : Union[float, None]
  13229. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13230. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13231. no_wait_after : Union[bool, None]
  13232. This option has no effect.
  13233. Deprecated: This option has no effect.
  13234. force : Union[bool, None]
  13235. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13236. """
  13237. return mapping.from_maybe_impl(
  13238. self._sync(
  13239. self._impl_obj.clear(
  13240. timeout=timeout, noWaitAfter=no_wait_after, force=force
  13241. )
  13242. )
  13243. )
  13244. def locator(
  13245. self,
  13246. selector_or_locator: typing.Union[str, "Locator"],
  13247. *,
  13248. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13249. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13250. has: typing.Optional["Locator"] = None,
  13251. has_not: typing.Optional["Locator"] = None,
  13252. ) -> "Locator":
  13253. """Locator.locator
  13254. The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
  13255. options, similar to `locator.filter()` method.
  13256. [Learn more about locators](https://playwright.dev/python/docs/locators).
  13257. Parameters
  13258. ----------
  13259. selector_or_locator : Union[Locator, str]
  13260. A selector or locator to use when resolving DOM element.
  13261. has_text : Union[Pattern[str], str, None]
  13262. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  13263. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  13264. `<article><div>Playwright</div></article>`.
  13265. has_not_text : Union[Pattern[str], str, None]
  13266. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  13267. When passed a [string], matching is case-insensitive and searches for a substring.
  13268. has : Union[Locator, None]
  13269. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  13270. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  13271. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  13272. the document root. For example, you can find `content` that has `div` in
  13273. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  13274. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  13275. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13276. has_not : Union[Locator, None]
  13277. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  13278. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  13279. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13280. Returns
  13281. -------
  13282. Locator
  13283. """
  13284. return mapping.from_impl(
  13285. self._impl_obj.locator(
  13286. selectorOrLocator=selector_or_locator,
  13287. hasText=has_text,
  13288. hasNotText=has_not_text,
  13289. has=has._impl_obj if has else None,
  13290. hasNot=has_not._impl_obj if has_not else None,
  13291. )
  13292. )
  13293. def get_by_alt_text(
  13294. self,
  13295. text: typing.Union[str, typing.Pattern[str]],
  13296. *,
  13297. exact: typing.Optional[bool] = None,
  13298. ) -> "Locator":
  13299. """Locator.get_by_alt_text
  13300. Allows locating elements by their alt text.
  13301. **Usage**
  13302. For example, this method will find the image by alt text \"Playwright logo\":
  13303. ```html
  13304. <img alt='Playwright logo'>
  13305. ```
  13306. ```py
  13307. page.get_by_alt_text(\"Playwright logo\").click()
  13308. ```
  13309. Parameters
  13310. ----------
  13311. text : Union[Pattern[str], str]
  13312. Text to locate the element for.
  13313. exact : Union[bool, None]
  13314. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13315. regular expression. Note that exact match still trims whitespace.
  13316. Returns
  13317. -------
  13318. Locator
  13319. """
  13320. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  13321. def get_by_label(
  13322. self,
  13323. text: typing.Union[str, typing.Pattern[str]],
  13324. *,
  13325. exact: typing.Optional[bool] = None,
  13326. ) -> "Locator":
  13327. """Locator.get_by_label
  13328. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  13329. `aria-label` attribute.
  13330. **Usage**
  13331. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  13332. ```html
  13333. <input aria-label=\"Username\">
  13334. <label for=\"password-input\">Password:</label>
  13335. <input id=\"password-input\">
  13336. ```
  13337. ```py
  13338. page.get_by_label(\"Username\").fill(\"john\")
  13339. page.get_by_label(\"Password\").fill(\"secret\")
  13340. ```
  13341. Parameters
  13342. ----------
  13343. text : Union[Pattern[str], str]
  13344. Text to locate the element for.
  13345. exact : Union[bool, None]
  13346. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13347. regular expression. Note that exact match still trims whitespace.
  13348. Returns
  13349. -------
  13350. Locator
  13351. """
  13352. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  13353. def get_by_placeholder(
  13354. self,
  13355. text: typing.Union[str, typing.Pattern[str]],
  13356. *,
  13357. exact: typing.Optional[bool] = None,
  13358. ) -> "Locator":
  13359. """Locator.get_by_placeholder
  13360. Allows locating input elements by the placeholder text.
  13361. **Usage**
  13362. For example, consider the following DOM structure.
  13363. ```html
  13364. <input type=\"email\" placeholder=\"name@example.com\" />
  13365. ```
  13366. You can fill the input after locating it by the placeholder text:
  13367. ```py
  13368. page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  13369. ```
  13370. Parameters
  13371. ----------
  13372. text : Union[Pattern[str], str]
  13373. Text to locate the element for.
  13374. exact : Union[bool, None]
  13375. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13376. regular expression. Note that exact match still trims whitespace.
  13377. Returns
  13378. -------
  13379. Locator
  13380. """
  13381. return mapping.from_impl(
  13382. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  13383. )
  13384. def get_by_role(
  13385. self,
  13386. role: Literal[
  13387. "alert",
  13388. "alertdialog",
  13389. "application",
  13390. "article",
  13391. "banner",
  13392. "blockquote",
  13393. "button",
  13394. "caption",
  13395. "cell",
  13396. "checkbox",
  13397. "code",
  13398. "columnheader",
  13399. "combobox",
  13400. "complementary",
  13401. "contentinfo",
  13402. "definition",
  13403. "deletion",
  13404. "dialog",
  13405. "directory",
  13406. "document",
  13407. "emphasis",
  13408. "feed",
  13409. "figure",
  13410. "form",
  13411. "generic",
  13412. "grid",
  13413. "gridcell",
  13414. "group",
  13415. "heading",
  13416. "img",
  13417. "insertion",
  13418. "link",
  13419. "list",
  13420. "listbox",
  13421. "listitem",
  13422. "log",
  13423. "main",
  13424. "marquee",
  13425. "math",
  13426. "menu",
  13427. "menubar",
  13428. "menuitem",
  13429. "menuitemcheckbox",
  13430. "menuitemradio",
  13431. "meter",
  13432. "navigation",
  13433. "none",
  13434. "note",
  13435. "option",
  13436. "paragraph",
  13437. "presentation",
  13438. "progressbar",
  13439. "radio",
  13440. "radiogroup",
  13441. "region",
  13442. "row",
  13443. "rowgroup",
  13444. "rowheader",
  13445. "scrollbar",
  13446. "search",
  13447. "searchbox",
  13448. "separator",
  13449. "slider",
  13450. "spinbutton",
  13451. "status",
  13452. "strong",
  13453. "subscript",
  13454. "superscript",
  13455. "switch",
  13456. "tab",
  13457. "table",
  13458. "tablist",
  13459. "tabpanel",
  13460. "term",
  13461. "textbox",
  13462. "time",
  13463. "timer",
  13464. "toolbar",
  13465. "tooltip",
  13466. "tree",
  13467. "treegrid",
  13468. "treeitem",
  13469. ],
  13470. *,
  13471. checked: typing.Optional[bool] = None,
  13472. disabled: typing.Optional[bool] = None,
  13473. expanded: typing.Optional[bool] = None,
  13474. include_hidden: typing.Optional[bool] = None,
  13475. level: typing.Optional[int] = None,
  13476. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13477. pressed: typing.Optional[bool] = None,
  13478. selected: typing.Optional[bool] = None,
  13479. exact: typing.Optional[bool] = None,
  13480. ) -> "Locator":
  13481. """Locator.get_by_role
  13482. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  13483. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  13484. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  13485. **Usage**
  13486. Consider the following DOM structure.
  13487. ```html
  13488. <h3>Sign up</h3>
  13489. <label>
  13490. <input type=\"checkbox\" /> Subscribe
  13491. </label>
  13492. <br/>
  13493. <button>Submit</button>
  13494. ```
  13495. You can locate each element by it's implicit role:
  13496. ```py
  13497. expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  13498. page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  13499. page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  13500. ```
  13501. **Details**
  13502. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  13503. about the ARIA guidelines.
  13504. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  13505. that is recognized by the role selector. You can find all the
  13506. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  13507. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  13508. Parameters
  13509. ----------
  13510. role : Union["alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"]
  13511. Required aria role.
  13512. checked : Union[bool, None]
  13513. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  13514. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  13515. disabled : Union[bool, None]
  13516. An attribute that is usually set by `aria-disabled` or `disabled`.
  13517. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  13518. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  13519. expanded : Union[bool, None]
  13520. An attribute that is usually set by `aria-expanded`.
  13521. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  13522. include_hidden : Union[bool, None]
  13523. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  13524. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  13525. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  13526. level : Union[int, None]
  13527. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  13528. for `<h1>-<h6>` elements.
  13529. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  13530. name : Union[Pattern[str], str, None]
  13531. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  13532. case-insensitive and searches for a substring, use `exact` to control this behavior.
  13533. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  13534. pressed : Union[bool, None]
  13535. An attribute that is usually set by `aria-pressed`.
  13536. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  13537. selected : Union[bool, None]
  13538. An attribute that is usually set by `aria-selected`.
  13539. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  13540. exact : Union[bool, None]
  13541. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  13542. regular expression. Note that exact match still trims whitespace.
  13543. Returns
  13544. -------
  13545. Locator
  13546. """
  13547. return mapping.from_impl(
  13548. self._impl_obj.get_by_role(
  13549. role=role,
  13550. checked=checked,
  13551. disabled=disabled,
  13552. expanded=expanded,
  13553. includeHidden=include_hidden,
  13554. level=level,
  13555. name=name,
  13556. pressed=pressed,
  13557. selected=selected,
  13558. exact=exact,
  13559. )
  13560. )
  13561. def get_by_test_id(
  13562. self, test_id: typing.Union[str, typing.Pattern[str]]
  13563. ) -> "Locator":
  13564. """Locator.get_by_test_id
  13565. Locate element by the test id.
  13566. **Usage**
  13567. Consider the following DOM structure.
  13568. ```html
  13569. <button data-testid=\"directions\">Itinéraire</button>
  13570. ```
  13571. You can locate the element by it's test id:
  13572. ```py
  13573. page.get_by_test_id(\"directions\").click()
  13574. ```
  13575. **Details**
  13576. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  13577. configure a different test id attribute if necessary.
  13578. Parameters
  13579. ----------
  13580. test_id : Union[Pattern[str], str]
  13581. Id to locate the element by.
  13582. Returns
  13583. -------
  13584. Locator
  13585. """
  13586. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  13587. def get_by_text(
  13588. self,
  13589. text: typing.Union[str, typing.Pattern[str]],
  13590. *,
  13591. exact: typing.Optional[bool] = None,
  13592. ) -> "Locator":
  13593. """Locator.get_by_text
  13594. Allows locating elements that contain given text.
  13595. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  13596. filter by the text content.
  13597. **Usage**
  13598. Consider the following DOM structure:
  13599. ```html
  13600. <div>Hello <span>world</span></div>
  13601. <div>Hello</div>
  13602. ```
  13603. You can locate by text substring, exact string, or a regular expression:
  13604. ```py
  13605. # Matches <span>
  13606. page.get_by_text(\"world\")
  13607. # Matches first <div>
  13608. page.get_by_text(\"Hello world\")
  13609. # Matches second <div>
  13610. page.get_by_text(\"Hello\", exact=True)
  13611. # Matches both <div>s
  13612. page.get_by_text(re.compile(\"Hello\"))
  13613. # Matches second <div>
  13614. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  13615. ```
  13616. **Details**
  13617. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  13618. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  13619. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  13620. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  13621. Parameters
  13622. ----------
  13623. text : Union[Pattern[str], str]
  13624. Text to locate the element for.
  13625. exact : Union[bool, None]
  13626. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13627. regular expression. Note that exact match still trims whitespace.
  13628. Returns
  13629. -------
  13630. Locator
  13631. """
  13632. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  13633. def get_by_title(
  13634. self,
  13635. text: typing.Union[str, typing.Pattern[str]],
  13636. *,
  13637. exact: typing.Optional[bool] = None,
  13638. ) -> "Locator":
  13639. """Locator.get_by_title
  13640. Allows locating elements by their title attribute.
  13641. **Usage**
  13642. Consider the following DOM structure.
  13643. ```html
  13644. <span title='Issues count'>25 issues</span>
  13645. ```
  13646. You can check the issues count after locating it by the title text:
  13647. ```py
  13648. expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  13649. ```
  13650. Parameters
  13651. ----------
  13652. text : Union[Pattern[str], str]
  13653. Text to locate the element for.
  13654. exact : Union[bool, None]
  13655. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13656. regular expression. Note that exact match still trims whitespace.
  13657. Returns
  13658. -------
  13659. Locator
  13660. """
  13661. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  13662. def frame_locator(self, selector: str) -> "FrameLocator":
  13663. """Locator.frame_locator
  13664. When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
  13665. that iframe:
  13666. **Usage**
  13667. ```py
  13668. locator = page.frame_locator(\"iframe\").get_by_text(\"Submit\")
  13669. locator.click()
  13670. ```
  13671. Parameters
  13672. ----------
  13673. selector : str
  13674. A selector to use when resolving DOM element.
  13675. Returns
  13676. -------
  13677. FrameLocator
  13678. """
  13679. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  13680. def element_handle(
  13681. self, *, timeout: typing.Optional[float] = None
  13682. ) -> "ElementHandle":
  13683. """Locator.element_handle
  13684. Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
  13685. multiple elements match the locator, throws.
  13686. Parameters
  13687. ----------
  13688. timeout : Union[float, None]
  13689. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13690. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13691. Returns
  13692. -------
  13693. ElementHandle
  13694. """
  13695. return mapping.from_impl(
  13696. self._sync(self._impl_obj.element_handle(timeout=timeout))
  13697. )
  13698. def element_handles(self) -> typing.List["ElementHandle"]:
  13699. """Locator.element_handles
  13700. Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
  13701. Returns
  13702. -------
  13703. List[ElementHandle]
  13704. """
  13705. return mapping.from_impl_list(self._sync(self._impl_obj.element_handles()))
  13706. def nth(self, index: int) -> "Locator":
  13707. """Locator.nth
  13708. Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
  13709. **Usage**
  13710. ```py
  13711. banana = page.get_by_role(\"listitem\").nth(2)
  13712. ```
  13713. Parameters
  13714. ----------
  13715. index : int
  13716. Returns
  13717. -------
  13718. Locator
  13719. """
  13720. return mapping.from_impl(self._impl_obj.nth(index=index))
  13721. def describe(self, description: str) -> "Locator":
  13722. """Locator.describe
  13723. Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the
  13724. same element.
  13725. **Usage**
  13726. ```py
  13727. button = page.get_by_test_id(\"btn-sub\").describe(\"Subscribe button\")
  13728. button.click()
  13729. ```
  13730. Parameters
  13731. ----------
  13732. description : str
  13733. Locator description.
  13734. Returns
  13735. -------
  13736. Locator
  13737. """
  13738. return mapping.from_impl(self._impl_obj.describe(description=description))
  13739. def filter(
  13740. self,
  13741. *,
  13742. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13743. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13744. has: typing.Optional["Locator"] = None,
  13745. has_not: typing.Optional["Locator"] = None,
  13746. visible: typing.Optional[bool] = None,
  13747. ) -> "Locator":
  13748. """Locator.filter
  13749. This method narrows existing locator according to the options, for example filters by text. It can be chained to
  13750. filter multiple times.
  13751. **Usage**
  13752. ```py
  13753. row_locator = page.locator(\"tr\")
  13754. # ...
  13755. row_locator.filter(has_text=\"text in column 1\").filter(
  13756. has=page.get_by_role(\"button\", name=\"column 2 button\")
  13757. ).screenshot()
  13758. ```
  13759. Parameters
  13760. ----------
  13761. has_text : Union[Pattern[str], str, None]
  13762. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  13763. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  13764. `<article><div>Playwright</div></article>`.
  13765. has_not_text : Union[Pattern[str], str, None]
  13766. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  13767. When passed a [string], matching is case-insensitive and searches for a substring.
  13768. has : Union[Locator, None]
  13769. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  13770. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  13771. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  13772. the document root. For example, you can find `content` that has `div` in
  13773. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  13774. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  13775. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13776. has_not : Union[Locator, None]
  13777. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  13778. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  13779. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13780. visible : Union[bool, None]
  13781. Only matches visible or invisible elements.
  13782. Returns
  13783. -------
  13784. Locator
  13785. """
  13786. return mapping.from_impl(
  13787. self._impl_obj.filter(
  13788. hasText=has_text,
  13789. hasNotText=has_not_text,
  13790. has=has._impl_obj if has else None,
  13791. hasNot=has_not._impl_obj if has_not else None,
  13792. visible=visible,
  13793. )
  13794. )
  13795. def or_(self, locator: "Locator") -> "Locator":
  13796. """Locator.or_
  13797. Creates a locator matching all elements that match one or both of the two locators.
  13798. Note that when both locators match something, the resulting locator will have multiple matches, potentially causing
  13799. a [locator strictness](https://playwright.dev/python/docs/locators#strictness) violation.
  13800. **Usage**
  13801. Consider a scenario where you'd like to click on a \"New email\" button, but sometimes a security settings dialog
  13802. shows up instead. In this case, you can wait for either a \"New email\" button, or a dialog and act accordingly.
  13803. **NOTE** If both \"New email\" button and security dialog appear on screen, the \"or\" locator will match both of them,
  13804. possibly throwing the [\"strict mode violation\" error](https://playwright.dev/python/docs/locators#strictness). In this case, you can use
  13805. `locator.first()` to only match one of them.
  13806. ```py
  13807. new_email = page.get_by_role(\"button\", name=\"New\")
  13808. dialog = page.get_by_text(\"Confirm security settings\")
  13809. expect(new_email.or_(dialog).first).to_be_visible()
  13810. if (dialog.is_visible()):
  13811. page.get_by_role(\"button\", name=\"Dismiss\").click()
  13812. new_email.click()
  13813. ```
  13814. Parameters
  13815. ----------
  13816. locator : Locator
  13817. Alternative locator to match.
  13818. Returns
  13819. -------
  13820. Locator
  13821. """
  13822. return mapping.from_impl(self._impl_obj.or_(locator=locator._impl_obj))
  13823. def and_(self, locator: "Locator") -> "Locator":
  13824. """Locator.and_
  13825. Creates a locator that matches both this locator and the argument locator.
  13826. **Usage**
  13827. The following example finds a button with a specific title.
  13828. ```py
  13829. button = page.get_by_role(\"button\").and_(page.get_by_title(\"Subscribe\"))
  13830. ```
  13831. Parameters
  13832. ----------
  13833. locator : Locator
  13834. Additional locator to match.
  13835. Returns
  13836. -------
  13837. Locator
  13838. """
  13839. return mapping.from_impl(self._impl_obj.and_(locator=locator._impl_obj))
  13840. def focus(self, *, timeout: typing.Optional[float] = None) -> None:
  13841. """Locator.focus
  13842. Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
  13843. Parameters
  13844. ----------
  13845. timeout : Union[float, None]
  13846. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13847. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13848. """
  13849. return mapping.from_maybe_impl(
  13850. self._sync(self._impl_obj.focus(timeout=timeout))
  13851. )
  13852. def blur(self, *, timeout: typing.Optional[float] = None) -> None:
  13853. """Locator.blur
  13854. Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur) on the element.
  13855. Parameters
  13856. ----------
  13857. timeout : Union[float, None]
  13858. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13859. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13860. """
  13861. return mapping.from_maybe_impl(self._sync(self._impl_obj.blur(timeout=timeout)))
  13862. def all(self) -> typing.List["Locator"]:
  13863. """Locator.all
  13864. When the locator points to a list of elements, this returns an array of locators, pointing to their respective
  13865. elements.
  13866. **NOTE** `locator.all()` does not wait for elements to match the locator, and instead immediately returns
  13867. whatever is present in the page.
  13868. When the list of elements changes dynamically, `locator.all()` will produce unpredictable and flaky
  13869. results.
  13870. When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before
  13871. calling `locator.all()`.
  13872. **Usage**
  13873. ```py
  13874. for li in page.get_by_role('listitem').all():
  13875. li.click();
  13876. ```
  13877. Returns
  13878. -------
  13879. List[Locator]
  13880. """
  13881. return mapping.from_impl_list(self._sync(self._impl_obj.all()))
  13882. def count(self) -> int:
  13883. """Locator.count
  13884. Returns the number of elements matching the locator.
  13885. **NOTE** If you need to assert the number of elements on the page, prefer `locator_assertions.to_have_count()`
  13886. to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  13887. **Usage**
  13888. ```py
  13889. count = page.get_by_role(\"listitem\").count()
  13890. ```
  13891. Returns
  13892. -------
  13893. int
  13894. """
  13895. return mapping.from_maybe_impl(self._sync(self._impl_obj.count()))
  13896. def drag_to(
  13897. self,
  13898. target: "Locator",
  13899. *,
  13900. force: typing.Optional[bool] = None,
  13901. no_wait_after: typing.Optional[bool] = None,
  13902. timeout: typing.Optional[float] = None,
  13903. trial: typing.Optional[bool] = None,
  13904. source_position: typing.Optional[Position] = None,
  13905. target_position: typing.Optional[Position] = None,
  13906. steps: typing.Optional[int] = None,
  13907. ) -> None:
  13908. """Locator.drag_to
  13909. Drag the source element towards the target element and drop it.
  13910. **Details**
  13911. This method drags the locator to another target locator or target position. It will first move to the source
  13912. element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
  13913. **Usage**
  13914. ```py
  13915. source = page.locator(\"#source\")
  13916. target = page.locator(\"#target\")
  13917. source.drag_to(target)
  13918. # or specify exact positions relative to the top-left corners of the elements:
  13919. source.drag_to(
  13920. target,
  13921. source_position={\"x\": 34, \"y\": 7},
  13922. target_position={\"x\": 10, \"y\": 20}
  13923. )
  13924. ```
  13925. Parameters
  13926. ----------
  13927. target : Locator
  13928. Locator of the element to drag to.
  13929. force : Union[bool, None]
  13930. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13931. no_wait_after : Union[bool, None]
  13932. This option has no effect.
  13933. Deprecated: This option has no effect.
  13934. timeout : Union[float, None]
  13935. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13936. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13937. trial : Union[bool, None]
  13938. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  13939. to `false`. Useful to wait until the element is ready for the action without performing it.
  13940. source_position : Union[{x: float, y: float}, None]
  13941. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  13942. specified, some visible point of the element is used.
  13943. target_position : Union[{x: float, y: float}, None]
  13944. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  13945. specified, some visible point of the element is used.
  13946. steps : Union[int, None]
  13947. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  13948. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  13949. """
  13950. return mapping.from_maybe_impl(
  13951. self._sync(
  13952. self._impl_obj.drag_to(
  13953. target=target._impl_obj,
  13954. force=force,
  13955. noWaitAfter=no_wait_after,
  13956. timeout=timeout,
  13957. trial=trial,
  13958. sourcePosition=source_position,
  13959. targetPosition=target_position,
  13960. steps=steps,
  13961. )
  13962. )
  13963. )
  13964. def get_attribute(
  13965. self, name: str, *, timeout: typing.Optional[float] = None
  13966. ) -> typing.Optional[str]:
  13967. """Locator.get_attribute
  13968. Returns the matching element's attribute value.
  13969. **NOTE** If you need to assert an element's attribute, prefer `locator_assertions.to_have_attribute()` to
  13970. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  13971. Parameters
  13972. ----------
  13973. name : str
  13974. Attribute name to get the value for.
  13975. timeout : Union[float, None]
  13976. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13977. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13978. Returns
  13979. -------
  13980. Union[str, None]
  13981. """
  13982. return mapping.from_maybe_impl(
  13983. self._sync(self._impl_obj.get_attribute(name=name, timeout=timeout))
  13984. )
  13985. def hover(
  13986. self,
  13987. *,
  13988. modifiers: typing.Optional[
  13989. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  13990. ] = None,
  13991. position: typing.Optional[Position] = None,
  13992. timeout: typing.Optional[float] = None,
  13993. no_wait_after: typing.Optional[bool] = None,
  13994. force: typing.Optional[bool] = None,
  13995. trial: typing.Optional[bool] = None,
  13996. ) -> None:
  13997. """Locator.hover
  13998. Hover over the matching element.
  13999. **Usage**
  14000. ```py
  14001. page.get_by_role(\"link\").hover()
  14002. ```
  14003. **Details**
  14004. This method hovers over the element by performing the following steps:
  14005. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14006. 1. Scroll the element into view if needed.
  14007. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  14008. If the element is detached from the DOM at any moment during the action, this method throws.
  14009. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14010. Passing zero timeout disables this.
  14011. Parameters
  14012. ----------
  14013. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  14014. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  14015. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  14016. "Control" on Windows and Linux and to "Meta" on macOS.
  14017. position : Union[{x: float, y: float}, None]
  14018. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14019. the element.
  14020. timeout : Union[float, None]
  14021. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14022. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14023. no_wait_after : Union[bool, None]
  14024. This option has no effect.
  14025. Deprecated: This option has no effect.
  14026. force : Union[bool, None]
  14027. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14028. trial : Union[bool, None]
  14029. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14030. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  14031. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  14032. are pressed.
  14033. """
  14034. return mapping.from_maybe_impl(
  14035. self._sync(
  14036. self._impl_obj.hover(
  14037. modifiers=mapping.to_impl(modifiers),
  14038. position=position,
  14039. timeout=timeout,
  14040. noWaitAfter=no_wait_after,
  14041. force=force,
  14042. trial=trial,
  14043. )
  14044. )
  14045. )
  14046. def inner_html(self, *, timeout: typing.Optional[float] = None) -> str:
  14047. """Locator.inner_html
  14048. Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
  14049. Parameters
  14050. ----------
  14051. timeout : Union[float, None]
  14052. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14053. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14054. Returns
  14055. -------
  14056. str
  14057. """
  14058. return mapping.from_maybe_impl(
  14059. self._sync(self._impl_obj.inner_html(timeout=timeout))
  14060. )
  14061. def inner_text(self, *, timeout: typing.Optional[float] = None) -> str:
  14062. """Locator.inner_text
  14063. Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
  14064. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
  14065. `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14066. Parameters
  14067. ----------
  14068. timeout : Union[float, None]
  14069. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14070. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14071. Returns
  14072. -------
  14073. str
  14074. """
  14075. return mapping.from_maybe_impl(
  14076. self._sync(self._impl_obj.inner_text(timeout=timeout))
  14077. )
  14078. def input_value(self, *, timeout: typing.Optional[float] = None) -> str:
  14079. """Locator.input_value
  14080. Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
  14081. **NOTE** If you need to assert input value, prefer `locator_assertions.to_have_value()` to avoid flakiness.
  14082. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14083. **Usage**
  14084. ```py
  14085. value = page.get_by_role(\"textbox\").input_value()
  14086. ```
  14087. **Details**
  14088. Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
  14089. element that has an associated
  14090. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  14091. control.
  14092. Parameters
  14093. ----------
  14094. timeout : Union[float, None]
  14095. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14096. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14097. Returns
  14098. -------
  14099. str
  14100. """
  14101. return mapping.from_maybe_impl(
  14102. self._sync(self._impl_obj.input_value(timeout=timeout))
  14103. )
  14104. def is_checked(self, *, timeout: typing.Optional[float] = None) -> bool:
  14105. """Locator.is_checked
  14106. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  14107. **NOTE** If you need to assert that checkbox is checked, prefer `locator_assertions.to_be_checked()` to avoid
  14108. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14109. **Usage**
  14110. ```py
  14111. checked = page.get_by_role(\"checkbox\").is_checked()
  14112. ```
  14113. Parameters
  14114. ----------
  14115. timeout : Union[float, None]
  14116. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14117. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14118. Returns
  14119. -------
  14120. bool
  14121. """
  14122. return mapping.from_maybe_impl(
  14123. self._sync(self._impl_obj.is_checked(timeout=timeout))
  14124. )
  14125. def is_disabled(self, *, timeout: typing.Optional[float] = None) -> bool:
  14126. """Locator.is_disabled
  14127. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  14128. **NOTE** If you need to assert that an element is disabled, prefer `locator_assertions.to_be_disabled()` to
  14129. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14130. **Usage**
  14131. ```py
  14132. disabled = page.get_by_role(\"button\").is_disabled()
  14133. ```
  14134. Parameters
  14135. ----------
  14136. timeout : Union[float, None]
  14137. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14138. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14139. Returns
  14140. -------
  14141. bool
  14142. """
  14143. return mapping.from_maybe_impl(
  14144. self._sync(self._impl_obj.is_disabled(timeout=timeout))
  14145. )
  14146. def is_editable(self, *, timeout: typing.Optional[float] = None) -> bool:
  14147. """Locator.is_editable
  14148. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable). If the target element is not an `<input>`,
  14149. `<textarea>`, `<select>`, `[contenteditable]` and does not have a role allowing `[aria-readonly]`, this method
  14150. throws an error.
  14151. **NOTE** If you need to assert that an element is editable, prefer `locator_assertions.to_be_editable()` to
  14152. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14153. **Usage**
  14154. ```py
  14155. editable = page.get_by_role(\"textbox\").is_editable()
  14156. ```
  14157. Parameters
  14158. ----------
  14159. timeout : Union[float, None]
  14160. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14161. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14162. Returns
  14163. -------
  14164. bool
  14165. """
  14166. return mapping.from_maybe_impl(
  14167. self._sync(self._impl_obj.is_editable(timeout=timeout))
  14168. )
  14169. def is_enabled(self, *, timeout: typing.Optional[float] = None) -> bool:
  14170. """Locator.is_enabled
  14171. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  14172. **NOTE** If you need to assert that an element is enabled, prefer `locator_assertions.to_be_enabled()` to
  14173. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14174. **Usage**
  14175. ```py
  14176. enabled = page.get_by_role(\"button\").is_enabled()
  14177. ```
  14178. Parameters
  14179. ----------
  14180. timeout : Union[float, None]
  14181. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14182. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14183. Returns
  14184. -------
  14185. bool
  14186. """
  14187. return mapping.from_maybe_impl(
  14188. self._sync(self._impl_obj.is_enabled(timeout=timeout))
  14189. )
  14190. def is_hidden(self, *, timeout: typing.Optional[float] = None) -> bool:
  14191. """Locator.is_hidden
  14192. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
  14193. **NOTE** If you need to assert that element is hidden, prefer `locator_assertions.to_be_hidden()` to avoid
  14194. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14195. **Usage**
  14196. ```py
  14197. hidden = page.get_by_role(\"button\").is_hidden()
  14198. ```
  14199. Parameters
  14200. ----------
  14201. timeout : Union[float, None]
  14202. Deprecated: This option is ignored. `locator.is_hidden()` does not wait for the element to become hidden and returns immediately.
  14203. Returns
  14204. -------
  14205. bool
  14206. """
  14207. return mapping.from_maybe_impl(
  14208. self._sync(self._impl_obj.is_hidden(timeout=timeout))
  14209. )
  14210. def is_visible(self, *, timeout: typing.Optional[float] = None) -> bool:
  14211. """Locator.is_visible
  14212. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  14213. **NOTE** If you need to assert that element is visible, prefer `locator_assertions.to_be_visible()` to avoid
  14214. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14215. **Usage**
  14216. ```py
  14217. visible = page.get_by_role(\"button\").is_visible()
  14218. ```
  14219. Parameters
  14220. ----------
  14221. timeout : Union[float, None]
  14222. Deprecated: This option is ignored. `locator.is_visible()` does not wait for the element to become visible and returns immediately.
  14223. Returns
  14224. -------
  14225. bool
  14226. """
  14227. return mapping.from_maybe_impl(
  14228. self._sync(self._impl_obj.is_visible(timeout=timeout))
  14229. )
  14230. def press(
  14231. self,
  14232. key: str,
  14233. *,
  14234. delay: typing.Optional[float] = None,
  14235. timeout: typing.Optional[float] = None,
  14236. no_wait_after: typing.Optional[bool] = None,
  14237. ) -> None:
  14238. """Locator.press
  14239. Focuses the matching element and presses a combination of the keys.
  14240. **Usage**
  14241. ```py
  14242. page.get_by_role(\"textbox\").press(\"Backspace\")
  14243. ```
  14244. **Details**
  14245. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  14246. `key` can specify the intended
  14247. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  14248. to generate the text for. A superset of the `key` values can be found
  14249. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  14250. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  14251. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  14252. etc.
  14253. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  14254. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  14255. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  14256. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  14257. texts.
  14258. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  14259. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  14260. Parameters
  14261. ----------
  14262. key : str
  14263. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  14264. delay : Union[float, None]
  14265. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  14266. timeout : Union[float, None]
  14267. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14268. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14269. no_wait_after : Union[bool, None]
  14270. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  14271. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  14272. navigating to inaccessible pages. Defaults to `false`.
  14273. Deprecated: This option will default to `true` in the future.
  14274. """
  14275. return mapping.from_maybe_impl(
  14276. self._sync(
  14277. self._impl_obj.press(
  14278. key=key, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  14279. )
  14280. )
  14281. )
  14282. def screenshot(
  14283. self,
  14284. *,
  14285. timeout: typing.Optional[float] = None,
  14286. type: typing.Optional[Literal["jpeg", "png"]] = None,
  14287. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  14288. quality: typing.Optional[int] = None,
  14289. omit_background: typing.Optional[bool] = None,
  14290. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  14291. caret: typing.Optional[Literal["hide", "initial"]] = None,
  14292. scale: typing.Optional[Literal["css", "device"]] = None,
  14293. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  14294. mask_color: typing.Optional[str] = None,
  14295. style: typing.Optional[str] = None,
  14296. ) -> bytes:
  14297. """Locator.screenshot
  14298. Take a screenshot of the element matching the locator.
  14299. **Usage**
  14300. ```py
  14301. page.get_by_role(\"link\").screenshot()
  14302. ```
  14303. Disable animations and save screenshot to a file:
  14304. ```py
  14305. page.get_by_role(\"link\").screenshot(animations=\"disabled\", path=\"link.png\")
  14306. ```
  14307. **Details**
  14308. This method captures a screenshot of the page, clipped to the size and position of a particular element matching
  14309. the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
  14310. element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
  14311. This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
  14312. a screenshot. If the element is detached from DOM, the method throws an error.
  14313. Returns the buffer with the captured screenshot.
  14314. Parameters
  14315. ----------
  14316. timeout : Union[float, None]
  14317. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14318. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14319. type : Union["jpeg", "png", None]
  14320. Specify screenshot type, defaults to `png`.
  14321. path : Union[pathlib.Path, str, None]
  14322. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  14323. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  14324. won't be saved to the disk.
  14325. quality : Union[int, None]
  14326. The quality of the image, between 0-100. Not applicable to `png` images.
  14327. omit_background : Union[bool, None]
  14328. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  14329. Defaults to `false`.
  14330. animations : Union["allow", "disabled", None]
  14331. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  14332. treatment depending on their duration:
  14333. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  14334. - infinite animations are canceled to initial state, and then played over after the screenshot.
  14335. Defaults to `"allow"` that leaves animations untouched.
  14336. caret : Union["hide", "initial", None]
  14337. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  14338. changed. Defaults to `"hide"`.
  14339. scale : Union["css", "device", None]
  14340. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  14341. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  14342. screenshots of high-dpi devices will be twice as large or even larger.
  14343. Defaults to `"device"`.
  14344. mask : Union[Sequence[Locator], None]
  14345. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  14346. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  14347. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  14348. that.
  14349. mask_color : Union[str, None]
  14350. Specify the color of the overlay box for masked elements, in
  14351. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  14352. style : Union[str, None]
  14353. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  14354. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  14355. the Shadow DOM and applies to the inner frames.
  14356. Returns
  14357. -------
  14358. bytes
  14359. """
  14360. return mapping.from_maybe_impl(
  14361. self._sync(
  14362. self._impl_obj.screenshot(
  14363. timeout=timeout,
  14364. type=type,
  14365. path=path,
  14366. quality=quality,
  14367. omitBackground=omit_background,
  14368. animations=animations,
  14369. caret=caret,
  14370. scale=scale,
  14371. mask=mapping.to_impl(mask),
  14372. maskColor=mask_color,
  14373. style=style,
  14374. )
  14375. )
  14376. )
  14377. def aria_snapshot(self, *, timeout: typing.Optional[float] = None) -> str:
  14378. """Locator.aria_snapshot
  14379. Captures the aria snapshot of the given element. Read more about [aria snapshots](https://playwright.dev/python/docs/aria-snapshots) and
  14380. `locator_assertions.to_match_aria_snapshot()` for the corresponding assertion.
  14381. **Usage**
  14382. ```py
  14383. page.get_by_role(\"link\").aria_snapshot()
  14384. ```
  14385. **Details**
  14386. This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of
  14387. the element and its children. The snapshot can be used to assert the state of the element in the test, or to
  14388. compare it to state in the future.
  14389. The ARIA snapshot is represented using [YAML](https://yaml.org/spec/1.2.2/) markup language:
  14390. - The keys of the objects are the roles and optional accessible names of the elements.
  14391. - The values are either text content or an array of child elements.
  14392. - Generic static text can be represented with the `text` key.
  14393. Below is the HTML markup and the respective ARIA snapshot:
  14394. ```html
  14395. <ul aria-label=\"Links\">
  14396. <li><a href=\"/\">Home</a></li>
  14397. <li><a href=\"/about\">About</a></li>
  14398. <ul>
  14399. ```
  14400. ```yml
  14401. - list \"Links\":
  14402. - listitem:
  14403. - link \"Home\"
  14404. - listitem:
  14405. - link \"About\"
  14406. ```
  14407. Parameters
  14408. ----------
  14409. timeout : Union[float, None]
  14410. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14411. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14412. Returns
  14413. -------
  14414. str
  14415. """
  14416. return mapping.from_maybe_impl(
  14417. self._sync(self._impl_obj.aria_snapshot(timeout=timeout))
  14418. )
  14419. def scroll_into_view_if_needed(
  14420. self, *, timeout: typing.Optional[float] = None
  14421. ) -> None:
  14422. """Locator.scroll_into_view_if_needed
  14423. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
  14424. it is completely visible as defined by
  14425. [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
  14426. See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  14427. Parameters
  14428. ----------
  14429. timeout : Union[float, None]
  14430. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14431. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14432. """
  14433. return mapping.from_maybe_impl(
  14434. self._sync(self._impl_obj.scroll_into_view_if_needed(timeout=timeout))
  14435. )
  14436. def select_option(
  14437. self,
  14438. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  14439. *,
  14440. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  14441. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  14442. element: typing.Optional[
  14443. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  14444. ] = None,
  14445. timeout: typing.Optional[float] = None,
  14446. no_wait_after: typing.Optional[bool] = None,
  14447. force: typing.Optional[bool] = None,
  14448. ) -> typing.List[str]:
  14449. """Locator.select_option
  14450. Selects option or options in `<select>`.
  14451. **Details**
  14452. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
  14453. the `<select>` element and selects these options.
  14454. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  14455. the `<label>` element that has an associated
  14456. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  14457. instead.
  14458. Returns the array of option values that have been successfully selected.
  14459. Triggers a `change` and `input` event once all the provided options have been selected.
  14460. **Usage**
  14461. ```html
  14462. <select multiple>
  14463. <option value=\"red\">Red</option>
  14464. <option value=\"green\">Green</option>
  14465. <option value=\"blue\">Blue</option>
  14466. </select>
  14467. ```
  14468. ```py
  14469. # single selection matching the value or label
  14470. element.select_option(\"blue\")
  14471. # single selection matching the label
  14472. element.select_option(label=\"blue\")
  14473. # multiple selection for blue, red and second option
  14474. element.select_option(value=[\"red\", \"green\", \"blue\"])
  14475. ```
  14476. Parameters
  14477. ----------
  14478. value : Union[Sequence[str], str, None]
  14479. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  14480. otherwise only the first option matching one of the passed options is selected. Optional.
  14481. index : Union[Sequence[int], int, None]
  14482. Options to select by index. Optional.
  14483. label : Union[Sequence[str], str, None]
  14484. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  14485. otherwise only the first option matching one of the passed options is selected. Optional.
  14486. element : Union[ElementHandle, Sequence[ElementHandle], None]
  14487. Option elements to select. Optional.
  14488. timeout : Union[float, None]
  14489. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14490. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14491. no_wait_after : Union[bool, None]
  14492. This option has no effect.
  14493. Deprecated: This option has no effect.
  14494. force : Union[bool, None]
  14495. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14496. Returns
  14497. -------
  14498. List[str]
  14499. """
  14500. return mapping.from_maybe_impl(
  14501. self._sync(
  14502. self._impl_obj.select_option(
  14503. value=mapping.to_impl(value),
  14504. index=mapping.to_impl(index),
  14505. label=mapping.to_impl(label),
  14506. element=mapping.to_impl(element),
  14507. timeout=timeout,
  14508. noWaitAfter=no_wait_after,
  14509. force=force,
  14510. )
  14511. )
  14512. )
  14513. def select_text(
  14514. self,
  14515. *,
  14516. force: typing.Optional[bool] = None,
  14517. timeout: typing.Optional[float] = None,
  14518. ) -> None:
  14519. """Locator.select_text
  14520. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
  14521. text content.
  14522. If the element is inside the `<label>` element that has an associated
  14523. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
  14524. the control instead.
  14525. Parameters
  14526. ----------
  14527. force : Union[bool, None]
  14528. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14529. timeout : Union[float, None]
  14530. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14531. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14532. """
  14533. return mapping.from_maybe_impl(
  14534. self._sync(self._impl_obj.select_text(force=force, timeout=timeout))
  14535. )
  14536. def set_input_files(
  14537. self,
  14538. files: typing.Union[
  14539. str,
  14540. pathlib.Path,
  14541. FilePayload,
  14542. typing.Sequence[typing.Union[str, pathlib.Path]],
  14543. typing.Sequence[FilePayload],
  14544. ],
  14545. *,
  14546. timeout: typing.Optional[float] = None,
  14547. no_wait_after: typing.Optional[bool] = None,
  14548. ) -> None:
  14549. """Locator.set_input_files
  14550. Upload file or multiple files into `<input type=file>`. For inputs with a `[webkitdirectory]` attribute, only a
  14551. single directory path is supported.
  14552. **Usage**
  14553. ```py
  14554. # Select one file
  14555. page.get_by_label(\"Upload file\").set_input_files('myfile.pdf')
  14556. # Select multiple files
  14557. page.get_by_label(\"Upload files\").set_input_files(['file1.txt', 'file2.txt'])
  14558. # Select a directory
  14559. page.get_by_label(\"Upload directory\").set_input_files('mydir')
  14560. # Remove all the selected files
  14561. page.get_by_label(\"Upload file\").set_input_files([])
  14562. # Upload buffer from memory
  14563. page.get_by_label(\"Upload file\").set_input_files(
  14564. files=[
  14565. {\"name\": \"test.txt\", \"mimeType\": \"text/plain\", \"buffer\": b\"this is a test\"}
  14566. ],
  14567. )
  14568. ```
  14569. **Details**
  14570. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  14571. they are resolved relative to the current working directory. For empty array, clears the selected files.
  14572. This method expects `Locator` to point to an
  14573. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  14574. the `<label>` element that has an associated
  14575. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  14576. Parameters
  14577. ----------
  14578. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  14579. timeout : Union[float, None]
  14580. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14581. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14582. no_wait_after : Union[bool, None]
  14583. This option has no effect.
  14584. Deprecated: This option has no effect.
  14585. """
  14586. return mapping.from_maybe_impl(
  14587. self._sync(
  14588. self._impl_obj.set_input_files(
  14589. files=mapping.to_impl(files),
  14590. timeout=timeout,
  14591. noWaitAfter=no_wait_after,
  14592. )
  14593. )
  14594. )
  14595. def tap(
  14596. self,
  14597. *,
  14598. modifiers: typing.Optional[
  14599. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  14600. ] = None,
  14601. position: typing.Optional[Position] = None,
  14602. timeout: typing.Optional[float] = None,
  14603. force: typing.Optional[bool] = None,
  14604. no_wait_after: typing.Optional[bool] = None,
  14605. trial: typing.Optional[bool] = None,
  14606. ) -> None:
  14607. """Locator.tap
  14608. Perform a tap gesture on the element matching the locator. For examples of emulating other gestures by manually
  14609. dispatching touch events, see the [emulating legacy touch events](https://playwright.dev/python/docs/touch-events) page.
  14610. **Details**
  14611. This method taps the element by performing the following steps:
  14612. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14613. 1. Scroll the element into view if needed.
  14614. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  14615. If the element is detached from the DOM at any moment during the action, this method throws.
  14616. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14617. Passing zero timeout disables this.
  14618. **NOTE** `element.tap()` requires that the `hasTouch` option of the browser context be set to true.
  14619. Parameters
  14620. ----------
  14621. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  14622. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  14623. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  14624. "Control" on Windows and Linux and to "Meta" on macOS.
  14625. position : Union[{x: float, y: float}, None]
  14626. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14627. the element.
  14628. timeout : Union[float, None]
  14629. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14630. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14631. force : Union[bool, None]
  14632. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14633. no_wait_after : Union[bool, None]
  14634. This option has no effect.
  14635. Deprecated: This option has no effect.
  14636. trial : Union[bool, None]
  14637. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14638. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  14639. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  14640. are pressed.
  14641. """
  14642. return mapping.from_maybe_impl(
  14643. self._sync(
  14644. self._impl_obj.tap(
  14645. modifiers=mapping.to_impl(modifiers),
  14646. position=position,
  14647. timeout=timeout,
  14648. force=force,
  14649. noWaitAfter=no_wait_after,
  14650. trial=trial,
  14651. )
  14652. )
  14653. )
  14654. def text_content(
  14655. self, *, timeout: typing.Optional[float] = None
  14656. ) -> typing.Optional[str]:
  14657. """Locator.text_content
  14658. Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
  14659. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
  14660. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14661. Parameters
  14662. ----------
  14663. timeout : Union[float, None]
  14664. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14665. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14666. Returns
  14667. -------
  14668. Union[str, None]
  14669. """
  14670. return mapping.from_maybe_impl(
  14671. self._sync(self._impl_obj.text_content(timeout=timeout))
  14672. )
  14673. def type(
  14674. self,
  14675. text: str,
  14676. *,
  14677. delay: typing.Optional[float] = None,
  14678. timeout: typing.Optional[float] = None,
  14679. no_wait_after: typing.Optional[bool] = None,
  14680. ) -> None:
  14681. """Locator.type
  14682. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  14683. text.
  14684. To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
  14685. **Usage**
  14686. Parameters
  14687. ----------
  14688. text : str
  14689. A text to type into a focused element.
  14690. delay : Union[float, None]
  14691. Time to wait between key presses in milliseconds. Defaults to 0.
  14692. timeout : Union[float, None]
  14693. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14694. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14695. no_wait_after : Union[bool, None]
  14696. This option has no effect.
  14697. Deprecated: This option has no effect.
  14698. """
  14699. return mapping.from_maybe_impl(
  14700. self._sync(
  14701. self._impl_obj.type(
  14702. text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  14703. )
  14704. )
  14705. )
  14706. def press_sequentially(
  14707. self,
  14708. text: str,
  14709. *,
  14710. delay: typing.Optional[float] = None,
  14711. timeout: typing.Optional[float] = None,
  14712. no_wait_after: typing.Optional[bool] = None,
  14713. ) -> None:
  14714. """Locator.press_sequentially
  14715. **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
  14716. there is special keyboard handling on the page.
  14717. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  14718. text.
  14719. To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
  14720. **Usage**
  14721. ```py
  14722. locator.press_sequentially(\"hello\") # types instantly
  14723. locator.press_sequentially(\"world\", delay=100) # types slower, like a user
  14724. ```
  14725. An example of typing into a text field and then submitting the form:
  14726. ```py
  14727. locator = page.get_by_label(\"Password\")
  14728. locator.press_sequentially(\"my password\")
  14729. locator.press(\"Enter\")
  14730. ```
  14731. Parameters
  14732. ----------
  14733. text : str
  14734. String of characters to sequentially press into a focused element.
  14735. delay : Union[float, None]
  14736. Time to wait between key presses in milliseconds. Defaults to 0.
  14737. timeout : Union[float, None]
  14738. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14739. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14740. no_wait_after : Union[bool, None]
  14741. This option has no effect.
  14742. Deprecated: This option has no effect.
  14743. """
  14744. return mapping.from_maybe_impl(
  14745. self._sync(
  14746. self._impl_obj.press_sequentially(
  14747. text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  14748. )
  14749. )
  14750. )
  14751. def uncheck(
  14752. self,
  14753. *,
  14754. position: typing.Optional[Position] = None,
  14755. timeout: typing.Optional[float] = None,
  14756. force: typing.Optional[bool] = None,
  14757. no_wait_after: typing.Optional[bool] = None,
  14758. trial: typing.Optional[bool] = None,
  14759. ) -> None:
  14760. """Locator.uncheck
  14761. Ensure that checkbox or radio element is unchecked.
  14762. **Usage**
  14763. ```py
  14764. page.get_by_role(\"checkbox\").uncheck()
  14765. ```
  14766. **Details**
  14767. This method unchecks the element by performing the following steps:
  14768. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  14769. unchecked, this method returns immediately.
  14770. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14771. 1. Scroll the element into view if needed.
  14772. 1. Use `page.mouse` to click in the center of the element.
  14773. 1. Ensure that the element is now unchecked. If not, this method throws.
  14774. If the element is detached from the DOM at any moment during the action, this method throws.
  14775. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14776. Passing zero timeout disables this.
  14777. Parameters
  14778. ----------
  14779. position : Union[{x: float, y: float}, None]
  14780. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14781. the element.
  14782. timeout : Union[float, None]
  14783. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14784. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14785. force : Union[bool, None]
  14786. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14787. no_wait_after : Union[bool, None]
  14788. This option has no effect.
  14789. Deprecated: This option has no effect.
  14790. trial : Union[bool, None]
  14791. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14792. to `false`. Useful to wait until the element is ready for the action without performing it.
  14793. """
  14794. return mapping.from_maybe_impl(
  14795. self._sync(
  14796. self._impl_obj.uncheck(
  14797. position=position,
  14798. timeout=timeout,
  14799. force=force,
  14800. noWaitAfter=no_wait_after,
  14801. trial=trial,
  14802. )
  14803. )
  14804. )
  14805. def all_inner_texts(self) -> typing.List[str]:
  14806. """Locator.all_inner_texts
  14807. Returns an array of `node.innerText` values for all matching nodes.
  14808. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
  14809. `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14810. **Usage**
  14811. ```py
  14812. texts = page.get_by_role(\"link\").all_inner_texts()
  14813. ```
  14814. Returns
  14815. -------
  14816. List[str]
  14817. """
  14818. return mapping.from_maybe_impl(self._sync(self._impl_obj.all_inner_texts()))
  14819. def all_text_contents(self) -> typing.List[str]:
  14820. """Locator.all_text_contents
  14821. Returns an array of `node.textContent` values for all matching nodes.
  14822. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
  14823. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14824. **Usage**
  14825. ```py
  14826. texts = page.get_by_role(\"link\").all_text_contents()
  14827. ```
  14828. Returns
  14829. -------
  14830. List[str]
  14831. """
  14832. return mapping.from_maybe_impl(self._sync(self._impl_obj.all_text_contents()))
  14833. def wait_for(
  14834. self,
  14835. *,
  14836. timeout: typing.Optional[float] = None,
  14837. state: typing.Optional[
  14838. Literal["attached", "detached", "hidden", "visible"]
  14839. ] = None,
  14840. ) -> None:
  14841. """Locator.wait_for
  14842. Returns when element specified by locator satisfies the `state` option.
  14843. If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
  14844. `timeout` milliseconds until the condition is met.
  14845. **Usage**
  14846. ```py
  14847. order_sent = page.locator(\"#order-sent\")
  14848. order_sent.wait_for()
  14849. ```
  14850. Parameters
  14851. ----------
  14852. timeout : Union[float, None]
  14853. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14854. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14855. state : Union["attached", "detached", "hidden", "visible", None]
  14856. Defaults to `'visible'`. Can be either:
  14857. - `'attached'` - wait for element to be present in DOM.
  14858. - `'detached'` - wait for element to not be present in DOM.
  14859. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  14860. without any content or with `display:none` has an empty bounding box and is not considered visible.
  14861. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  14862. `visibility:hidden`. This is opposite to the `'visible'` option.
  14863. """
  14864. return mapping.from_maybe_impl(
  14865. self._sync(self._impl_obj.wait_for(timeout=timeout, state=state))
  14866. )
  14867. def set_checked(
  14868. self,
  14869. checked: bool,
  14870. *,
  14871. position: typing.Optional[Position] = None,
  14872. timeout: typing.Optional[float] = None,
  14873. force: typing.Optional[bool] = None,
  14874. no_wait_after: typing.Optional[bool] = None,
  14875. trial: typing.Optional[bool] = None,
  14876. ) -> None:
  14877. """Locator.set_checked
  14878. Set the state of a checkbox or a radio element.
  14879. **Usage**
  14880. ```py
  14881. page.get_by_role(\"checkbox\").set_checked(True)
  14882. ```
  14883. **Details**
  14884. This method checks or unchecks an element by performing the following steps:
  14885. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  14886. 1. If the element already has the right checked state, this method returns immediately.
  14887. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  14888. the element is detached during the checks, the whole action is retried.
  14889. 1. Scroll the element into view if needed.
  14890. 1. Use `page.mouse` to click in the center of the element.
  14891. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  14892. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14893. Passing zero timeout disables this.
  14894. Parameters
  14895. ----------
  14896. checked : bool
  14897. Whether to check or uncheck the checkbox.
  14898. position : Union[{x: float, y: float}, None]
  14899. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14900. the element.
  14901. timeout : Union[float, None]
  14902. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14903. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14904. force : Union[bool, None]
  14905. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14906. no_wait_after : Union[bool, None]
  14907. This option has no effect.
  14908. Deprecated: This option has no effect.
  14909. trial : Union[bool, None]
  14910. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14911. to `false`. Useful to wait until the element is ready for the action without performing it.
  14912. """
  14913. return mapping.from_maybe_impl(
  14914. self._sync(
  14915. self._impl_obj.set_checked(
  14916. checked=checked,
  14917. position=position,
  14918. timeout=timeout,
  14919. force=force,
  14920. noWaitAfter=no_wait_after,
  14921. trial=trial,
  14922. )
  14923. )
  14924. )
  14925. def highlight(self) -> None:
  14926. """Locator.highlight
  14927. Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
  14928. `locator.highlight()`.
  14929. """
  14930. return mapping.from_maybe_impl(self._sync(self._impl_obj.highlight()))
  14931. mapping.register(LocatorImpl, Locator)
  14932. class APIResponse(SyncBase):
  14933. @property
  14934. def ok(self) -> bool:
  14935. """APIResponse.ok
  14936. Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
  14937. Returns
  14938. -------
  14939. bool
  14940. """
  14941. return mapping.from_maybe_impl(self._impl_obj.ok)
  14942. @property
  14943. def url(self) -> str:
  14944. """APIResponse.url
  14945. Contains the URL of the response.
  14946. Returns
  14947. -------
  14948. str
  14949. """
  14950. return mapping.from_maybe_impl(self._impl_obj.url)
  14951. @property
  14952. def status(self) -> int:
  14953. """APIResponse.status
  14954. Contains the status code of the response (e.g., 200 for a success).
  14955. Returns
  14956. -------
  14957. int
  14958. """
  14959. return mapping.from_maybe_impl(self._impl_obj.status)
  14960. @property
  14961. def status_text(self) -> str:
  14962. """APIResponse.status_text
  14963. Contains the status text of the response (e.g. usually an \"OK\" for a success).
  14964. Returns
  14965. -------
  14966. str
  14967. """
  14968. return mapping.from_maybe_impl(self._impl_obj.status_text)
  14969. @property
  14970. def headers(self) -> typing.Dict[str, str]:
  14971. """APIResponse.headers
  14972. An object with all the response HTTP headers associated with this response.
  14973. Returns
  14974. -------
  14975. Dict[str, str]
  14976. """
  14977. return mapping.from_maybe_impl(self._impl_obj.headers)
  14978. @property
  14979. def headers_array(self) -> typing.List[NameValue]:
  14980. """APIResponse.headers_array
  14981. An array with all the response HTTP headers associated with this response. Header names are not lower-cased.
  14982. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.
  14983. Returns
  14984. -------
  14985. List[{name: str, value: str}]
  14986. """
  14987. return mapping.from_impl_list(self._impl_obj.headers_array)
  14988. def body(self) -> bytes:
  14989. """APIResponse.body
  14990. Returns the buffer with response body.
  14991. Returns
  14992. -------
  14993. bytes
  14994. """
  14995. return mapping.from_maybe_impl(self._sync(self._impl_obj.body()))
  14996. def text(self) -> str:
  14997. """APIResponse.text
  14998. Returns the text representation of response body.
  14999. Returns
  15000. -------
  15001. str
  15002. """
  15003. return mapping.from_maybe_impl(self._sync(self._impl_obj.text()))
  15004. def json(self) -> typing.Any:
  15005. """APIResponse.json
  15006. Returns the JSON representation of response body.
  15007. This method will throw if the response body is not parsable via `JSON.parse`.
  15008. Returns
  15009. -------
  15010. Any
  15011. """
  15012. return mapping.from_maybe_impl(self._sync(self._impl_obj.json()))
  15013. def dispose(self) -> None:
  15014. """APIResponse.dispose
  15015. Disposes the body of this response. If not called then the body will stay in memory until the context closes.
  15016. """
  15017. return mapping.from_maybe_impl(self._sync(self._impl_obj.dispose()))
  15018. mapping.register(APIResponseImpl, APIResponse)
  15019. class APIRequestContext(SyncBase):
  15020. def dispose(self, *, reason: typing.Optional[str] = None) -> None:
  15021. """APIRequestContext.dispose
  15022. All responses returned by `a_pi_request_context.get()` and similar methods are stored in the memory, so that
  15023. you can later call `a_pi_response.body()`.This method discards all its resources, calling any method on
  15024. disposed `APIRequestContext` will throw an exception.
  15025. Parameters
  15026. ----------
  15027. reason : Union[str, None]
  15028. The reason to be reported to the operations interrupted by the context disposal.
  15029. """
  15030. return mapping.from_maybe_impl(
  15031. self._sync(self._impl_obj.dispose(reason=reason))
  15032. )
  15033. def delete(
  15034. self,
  15035. url: str,
  15036. *,
  15037. params: typing.Optional[
  15038. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15039. ] = None,
  15040. headers: typing.Optional[typing.Dict[str, str]] = None,
  15041. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15042. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15043. multipart: typing.Optional[
  15044. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15045. ] = None,
  15046. timeout: typing.Optional[float] = None,
  15047. fail_on_status_code: typing.Optional[bool] = None,
  15048. ignore_https_errors: typing.Optional[bool] = None,
  15049. max_redirects: typing.Optional[int] = None,
  15050. max_retries: typing.Optional[int] = None,
  15051. ) -> "APIResponse":
  15052. """APIRequestContext.delete
  15053. Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
  15054. response. The method will populate request cookies from the context and update context cookies from the response.
  15055. The method will automatically follow redirects.
  15056. Parameters
  15057. ----------
  15058. url : str
  15059. Target URL.
  15060. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15061. Query parameters to be sent with the URL.
  15062. headers : Union[Dict[str, str], None]
  15063. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15064. it.
  15065. data : Union[Any, bytes, str, None]
  15066. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15067. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15068. header will be set to `application/octet-stream` if not explicitly set.
  15069. form : Union[Dict[str, Union[bool, float, str]], None]
  15070. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15071. as this request body. If this parameter is specified `content-type` header will be set to
  15072. `application/x-www-form-urlencoded` unless explicitly provided.
  15073. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15074. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15075. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15076. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15077. timeout : Union[float, None]
  15078. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15079. fail_on_status_code : Union[bool, None]
  15080. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15081. codes.
  15082. ignore_https_errors : Union[bool, None]
  15083. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15084. max_redirects : Union[int, None]
  15085. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15086. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15087. max_retries : Union[int, None]
  15088. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15089. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15090. Returns
  15091. -------
  15092. APIResponse
  15093. """
  15094. return mapping.from_impl(
  15095. self._sync(
  15096. self._impl_obj.delete(
  15097. url=url,
  15098. params=mapping.to_impl(params),
  15099. headers=mapping.to_impl(headers),
  15100. data=mapping.to_impl(data),
  15101. form=mapping.to_impl(form),
  15102. multipart=mapping.to_impl(multipart),
  15103. timeout=timeout,
  15104. failOnStatusCode=fail_on_status_code,
  15105. ignoreHTTPSErrors=ignore_https_errors,
  15106. maxRedirects=max_redirects,
  15107. maxRetries=max_retries,
  15108. )
  15109. )
  15110. )
  15111. def head(
  15112. self,
  15113. url: str,
  15114. *,
  15115. params: typing.Optional[
  15116. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15117. ] = None,
  15118. headers: typing.Optional[typing.Dict[str, str]] = None,
  15119. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15120. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15121. multipart: typing.Optional[
  15122. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15123. ] = None,
  15124. timeout: typing.Optional[float] = None,
  15125. fail_on_status_code: typing.Optional[bool] = None,
  15126. ignore_https_errors: typing.Optional[bool] = None,
  15127. max_redirects: typing.Optional[int] = None,
  15128. max_retries: typing.Optional[int] = None,
  15129. ) -> "APIResponse":
  15130. """APIRequestContext.head
  15131. Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its
  15132. response. The method will populate request cookies from the context and update context cookies from the response.
  15133. The method will automatically follow redirects.
  15134. Parameters
  15135. ----------
  15136. url : str
  15137. Target URL.
  15138. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15139. Query parameters to be sent with the URL.
  15140. headers : Union[Dict[str, str], None]
  15141. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15142. it.
  15143. data : Union[Any, bytes, str, None]
  15144. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15145. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15146. header will be set to `application/octet-stream` if not explicitly set.
  15147. form : Union[Dict[str, Union[bool, float, str]], None]
  15148. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15149. as this request body. If this parameter is specified `content-type` header will be set to
  15150. `application/x-www-form-urlencoded` unless explicitly provided.
  15151. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15152. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15153. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15154. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15155. timeout : Union[float, None]
  15156. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15157. fail_on_status_code : Union[bool, None]
  15158. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15159. codes.
  15160. ignore_https_errors : Union[bool, None]
  15161. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15162. max_redirects : Union[int, None]
  15163. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15164. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15165. max_retries : Union[int, None]
  15166. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15167. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15168. Returns
  15169. -------
  15170. APIResponse
  15171. """
  15172. return mapping.from_impl(
  15173. self._sync(
  15174. self._impl_obj.head(
  15175. url=url,
  15176. params=mapping.to_impl(params),
  15177. headers=mapping.to_impl(headers),
  15178. data=mapping.to_impl(data),
  15179. form=mapping.to_impl(form),
  15180. multipart=mapping.to_impl(multipart),
  15181. timeout=timeout,
  15182. failOnStatusCode=fail_on_status_code,
  15183. ignoreHTTPSErrors=ignore_https_errors,
  15184. maxRedirects=max_redirects,
  15185. maxRetries=max_retries,
  15186. )
  15187. )
  15188. )
  15189. def get(
  15190. self,
  15191. url: str,
  15192. *,
  15193. params: typing.Optional[
  15194. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15195. ] = None,
  15196. headers: typing.Optional[typing.Dict[str, str]] = None,
  15197. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15198. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15199. multipart: typing.Optional[
  15200. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15201. ] = None,
  15202. timeout: typing.Optional[float] = None,
  15203. fail_on_status_code: typing.Optional[bool] = None,
  15204. ignore_https_errors: typing.Optional[bool] = None,
  15205. max_redirects: typing.Optional[int] = None,
  15206. max_retries: typing.Optional[int] = None,
  15207. ) -> "APIResponse":
  15208. """APIRequestContext.get
  15209. Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its
  15210. response. The method will populate request cookies from the context and update context cookies from the response.
  15211. The method will automatically follow redirects.
  15212. **Usage**
  15213. Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
  15214. ```python
  15215. query_params = {
  15216. \"isbn\": \"1234\",
  15217. \"page\": \"23\"
  15218. }
  15219. api_request_context.get(\"https://example.com/api/getText\", params=query_params)
  15220. ```
  15221. Parameters
  15222. ----------
  15223. url : str
  15224. Target URL.
  15225. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15226. Query parameters to be sent with the URL.
  15227. headers : Union[Dict[str, str], None]
  15228. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15229. it.
  15230. data : Union[Any, bytes, str, None]
  15231. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15232. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15233. header will be set to `application/octet-stream` if not explicitly set.
  15234. form : Union[Dict[str, Union[bool, float, str]], None]
  15235. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15236. as this request body. If this parameter is specified `content-type` header will be set to
  15237. `application/x-www-form-urlencoded` unless explicitly provided.
  15238. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15239. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15240. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15241. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15242. timeout : Union[float, None]
  15243. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15244. fail_on_status_code : Union[bool, None]
  15245. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15246. codes.
  15247. ignore_https_errors : Union[bool, None]
  15248. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15249. max_redirects : Union[int, None]
  15250. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15251. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15252. max_retries : Union[int, None]
  15253. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15254. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15255. Returns
  15256. -------
  15257. APIResponse
  15258. """
  15259. return mapping.from_impl(
  15260. self._sync(
  15261. self._impl_obj.get(
  15262. url=url,
  15263. params=mapping.to_impl(params),
  15264. headers=mapping.to_impl(headers),
  15265. data=mapping.to_impl(data),
  15266. form=mapping.to_impl(form),
  15267. multipart=mapping.to_impl(multipart),
  15268. timeout=timeout,
  15269. failOnStatusCode=fail_on_status_code,
  15270. ignoreHTTPSErrors=ignore_https_errors,
  15271. maxRedirects=max_redirects,
  15272. maxRetries=max_retries,
  15273. )
  15274. )
  15275. )
  15276. def patch(
  15277. self,
  15278. url: str,
  15279. *,
  15280. params: typing.Optional[
  15281. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15282. ] = None,
  15283. headers: typing.Optional[typing.Dict[str, str]] = None,
  15284. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15285. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15286. multipart: typing.Optional[
  15287. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15288. ] = None,
  15289. timeout: typing.Optional[float] = None,
  15290. fail_on_status_code: typing.Optional[bool] = None,
  15291. ignore_https_errors: typing.Optional[bool] = None,
  15292. max_redirects: typing.Optional[int] = None,
  15293. max_retries: typing.Optional[int] = None,
  15294. ) -> "APIResponse":
  15295. """APIRequestContext.patch
  15296. Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its
  15297. response. The method will populate request cookies from the context and update context cookies from the response.
  15298. The method will automatically follow redirects.
  15299. Parameters
  15300. ----------
  15301. url : str
  15302. Target URL.
  15303. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15304. Query parameters to be sent with the URL.
  15305. headers : Union[Dict[str, str], None]
  15306. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15307. it.
  15308. data : Union[Any, bytes, str, None]
  15309. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15310. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15311. header will be set to `application/octet-stream` if not explicitly set.
  15312. form : Union[Dict[str, Union[bool, float, str]], None]
  15313. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15314. as this request body. If this parameter is specified `content-type` header will be set to
  15315. `application/x-www-form-urlencoded` unless explicitly provided.
  15316. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15317. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15318. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15319. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15320. timeout : Union[float, None]
  15321. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15322. fail_on_status_code : Union[bool, None]
  15323. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15324. codes.
  15325. ignore_https_errors : Union[bool, None]
  15326. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15327. max_redirects : Union[int, None]
  15328. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15329. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15330. max_retries : Union[int, None]
  15331. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15332. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15333. Returns
  15334. -------
  15335. APIResponse
  15336. """
  15337. return mapping.from_impl(
  15338. self._sync(
  15339. self._impl_obj.patch(
  15340. url=url,
  15341. params=mapping.to_impl(params),
  15342. headers=mapping.to_impl(headers),
  15343. data=mapping.to_impl(data),
  15344. form=mapping.to_impl(form),
  15345. multipart=mapping.to_impl(multipart),
  15346. timeout=timeout,
  15347. failOnStatusCode=fail_on_status_code,
  15348. ignoreHTTPSErrors=ignore_https_errors,
  15349. maxRedirects=max_redirects,
  15350. maxRetries=max_retries,
  15351. )
  15352. )
  15353. )
  15354. def put(
  15355. self,
  15356. url: str,
  15357. *,
  15358. params: typing.Optional[
  15359. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15360. ] = None,
  15361. headers: typing.Optional[typing.Dict[str, str]] = None,
  15362. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15363. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15364. multipart: typing.Optional[
  15365. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15366. ] = None,
  15367. timeout: typing.Optional[float] = None,
  15368. fail_on_status_code: typing.Optional[bool] = None,
  15369. ignore_https_errors: typing.Optional[bool] = None,
  15370. max_redirects: typing.Optional[int] = None,
  15371. max_retries: typing.Optional[int] = None,
  15372. ) -> "APIResponse":
  15373. """APIRequestContext.put
  15374. Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its
  15375. response. The method will populate request cookies from the context and update context cookies from the response.
  15376. The method will automatically follow redirects.
  15377. Parameters
  15378. ----------
  15379. url : str
  15380. Target URL.
  15381. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15382. Query parameters to be sent with the URL.
  15383. headers : Union[Dict[str, str], None]
  15384. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15385. it.
  15386. data : Union[Any, bytes, str, None]
  15387. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15388. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15389. header will be set to `application/octet-stream` if not explicitly set.
  15390. form : Union[Dict[str, Union[bool, float, str]], None]
  15391. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15392. as this request body. If this parameter is specified `content-type` header will be set to
  15393. `application/x-www-form-urlencoded` unless explicitly provided.
  15394. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15395. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15396. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15397. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15398. timeout : Union[float, None]
  15399. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15400. fail_on_status_code : Union[bool, None]
  15401. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15402. codes.
  15403. ignore_https_errors : Union[bool, None]
  15404. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15405. max_redirects : Union[int, None]
  15406. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15407. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15408. max_retries : Union[int, None]
  15409. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15410. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15411. Returns
  15412. -------
  15413. APIResponse
  15414. """
  15415. return mapping.from_impl(
  15416. self._sync(
  15417. self._impl_obj.put(
  15418. url=url,
  15419. params=mapping.to_impl(params),
  15420. headers=mapping.to_impl(headers),
  15421. data=mapping.to_impl(data),
  15422. form=mapping.to_impl(form),
  15423. multipart=mapping.to_impl(multipart),
  15424. timeout=timeout,
  15425. failOnStatusCode=fail_on_status_code,
  15426. ignoreHTTPSErrors=ignore_https_errors,
  15427. maxRedirects=max_redirects,
  15428. maxRetries=max_retries,
  15429. )
  15430. )
  15431. )
  15432. def post(
  15433. self,
  15434. url: str,
  15435. *,
  15436. params: typing.Optional[
  15437. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15438. ] = None,
  15439. headers: typing.Optional[typing.Dict[str, str]] = None,
  15440. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15441. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15442. multipart: typing.Optional[
  15443. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15444. ] = None,
  15445. timeout: typing.Optional[float] = None,
  15446. fail_on_status_code: typing.Optional[bool] = None,
  15447. ignore_https_errors: typing.Optional[bool] = None,
  15448. max_redirects: typing.Optional[int] = None,
  15449. max_retries: typing.Optional[int] = None,
  15450. ) -> "APIResponse":
  15451. """APIRequestContext.post
  15452. Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its
  15453. response. The method will populate request cookies from the context and update context cookies from the response.
  15454. The method will automatically follow redirects.
  15455. **Usage**
  15456. JSON objects can be passed directly to the request:
  15457. To send form data to the server use `form` option. Its value will be encoded into the request body with
  15458. `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send
  15459. files):
  15460. ```python
  15461. formData = {
  15462. \"title\": \"Book Title\",
  15463. \"body\": \"John Doe\",
  15464. }
  15465. api_request_context.post(\"https://example.com/api/findBook\", form=formData)
  15466. ```
  15467. The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
  15468. encoding. Use `FormData` to construct request body and pass it to the request as `multipart` parameter:
  15469. ```python
  15470. api_request_context.post(
  15471. \"https://example.com/api/uploadScript'\",
  15472. multipart={
  15473. \"fileField\": {
  15474. \"name\": \"f.js\",
  15475. \"mimeType\": \"text/javascript\",
  15476. \"buffer\": b\"console.log(2022);\",
  15477. },
  15478. })
  15479. ```
  15480. Parameters
  15481. ----------
  15482. url : str
  15483. Target URL.
  15484. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15485. Query parameters to be sent with the URL.
  15486. headers : Union[Dict[str, str], None]
  15487. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15488. it.
  15489. data : Union[Any, bytes, str, None]
  15490. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15491. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15492. header will be set to `application/octet-stream` if not explicitly set.
  15493. form : Union[Dict[str, Union[bool, float, str]], None]
  15494. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15495. as this request body. If this parameter is specified `content-type` header will be set to
  15496. `application/x-www-form-urlencoded` unless explicitly provided.
  15497. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15498. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15499. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15500. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15501. timeout : Union[float, None]
  15502. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15503. fail_on_status_code : Union[bool, None]
  15504. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15505. codes.
  15506. ignore_https_errors : Union[bool, None]
  15507. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15508. max_redirects : Union[int, None]
  15509. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15510. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15511. max_retries : Union[int, None]
  15512. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15513. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15514. Returns
  15515. -------
  15516. APIResponse
  15517. """
  15518. return mapping.from_impl(
  15519. self._sync(
  15520. self._impl_obj.post(
  15521. url=url,
  15522. params=mapping.to_impl(params),
  15523. headers=mapping.to_impl(headers),
  15524. data=mapping.to_impl(data),
  15525. form=mapping.to_impl(form),
  15526. multipart=mapping.to_impl(multipart),
  15527. timeout=timeout,
  15528. failOnStatusCode=fail_on_status_code,
  15529. ignoreHTTPSErrors=ignore_https_errors,
  15530. maxRedirects=max_redirects,
  15531. maxRetries=max_retries,
  15532. )
  15533. )
  15534. )
  15535. def fetch(
  15536. self,
  15537. url_or_request: typing.Union[str, "Request"],
  15538. *,
  15539. params: typing.Optional[
  15540. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15541. ] = None,
  15542. method: typing.Optional[str] = None,
  15543. headers: typing.Optional[typing.Dict[str, str]] = None,
  15544. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15545. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15546. multipart: typing.Optional[
  15547. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15548. ] = None,
  15549. timeout: typing.Optional[float] = None,
  15550. fail_on_status_code: typing.Optional[bool] = None,
  15551. ignore_https_errors: typing.Optional[bool] = None,
  15552. max_redirects: typing.Optional[int] = None,
  15553. max_retries: typing.Optional[int] = None,
  15554. ) -> "APIResponse":
  15555. """APIRequestContext.fetch
  15556. Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
  15557. update context cookies from the response. The method will automatically follow redirects.
  15558. **Usage**
  15559. JSON objects can be passed directly to the request:
  15560. The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
  15561. encoding, by specifiying the `multipart` parameter:
  15562. ```python
  15563. api_request_context.fetch(
  15564. \"https://example.com/api/uploadScript\", method=\"post\",
  15565. multipart={
  15566. \"fileField\": {
  15567. \"name\": \"f.js\",
  15568. \"mimeType\": \"text/javascript\",
  15569. \"buffer\": b\"console.log(2022);\",
  15570. },
  15571. })
  15572. ```
  15573. Parameters
  15574. ----------
  15575. url_or_request : Union[Request, str]
  15576. Target URL or Request to get all parameters from.
  15577. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15578. Query parameters to be sent with the URL.
  15579. method : Union[str, None]
  15580. If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or
  15581. [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.
  15582. headers : Union[Dict[str, str], None]
  15583. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15584. it.
  15585. data : Union[Any, bytes, str, None]
  15586. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15587. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15588. header will be set to `application/octet-stream` if not explicitly set.
  15589. form : Union[Dict[str, Union[bool, float, str]], None]
  15590. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15591. as this request body. If this parameter is specified `content-type` header will be set to
  15592. `application/x-www-form-urlencoded` unless explicitly provided.
  15593. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15594. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15595. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15596. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15597. timeout : Union[float, None]
  15598. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15599. fail_on_status_code : Union[bool, None]
  15600. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15601. codes.
  15602. ignore_https_errors : Union[bool, None]
  15603. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15604. max_redirects : Union[int, None]
  15605. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15606. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15607. max_retries : Union[int, None]
  15608. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15609. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15610. Returns
  15611. -------
  15612. APIResponse
  15613. """
  15614. return mapping.from_impl(
  15615. self._sync(
  15616. self._impl_obj.fetch(
  15617. urlOrRequest=url_or_request,
  15618. params=mapping.to_impl(params),
  15619. method=method,
  15620. headers=mapping.to_impl(headers),
  15621. data=mapping.to_impl(data),
  15622. form=mapping.to_impl(form),
  15623. multipart=mapping.to_impl(multipart),
  15624. timeout=timeout,
  15625. failOnStatusCode=fail_on_status_code,
  15626. ignoreHTTPSErrors=ignore_https_errors,
  15627. maxRedirects=max_redirects,
  15628. maxRetries=max_retries,
  15629. )
  15630. )
  15631. )
  15632. def storage_state(
  15633. self,
  15634. *,
  15635. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  15636. indexed_db: typing.Optional[bool] = None,
  15637. ) -> StorageState:
  15638. """APIRequestContext.storage_state
  15639. Returns storage state for this request context, contains current cookies and local storage snapshot if it was
  15640. passed to the constructor.
  15641. Parameters
  15642. ----------
  15643. path : Union[pathlib.Path, str, None]
  15644. The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
  15645. working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
  15646. indexed_db : Union[bool, None]
  15647. Set to `true` to include IndexedDB in the storage state snapshot.
  15648. Returns
  15649. -------
  15650. {cookies: List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: List[{origin: str, localStorage: List[{name: str, value: str}]}]}
  15651. """
  15652. return mapping.from_impl(
  15653. self._sync(self._impl_obj.storage_state(path=path, indexedDB=indexed_db))
  15654. )
  15655. mapping.register(APIRequestContextImpl, APIRequestContext)
  15656. class APIRequest(SyncBase):
  15657. def new_context(
  15658. self,
  15659. *,
  15660. base_url: typing.Optional[str] = None,
  15661. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  15662. http_credentials: typing.Optional[HttpCredentials] = None,
  15663. ignore_https_errors: typing.Optional[bool] = None,
  15664. proxy: typing.Optional[ProxySettings] = None,
  15665. user_agent: typing.Optional[str] = None,
  15666. timeout: typing.Optional[float] = None,
  15667. storage_state: typing.Optional[
  15668. typing.Union[StorageState, str, pathlib.Path]
  15669. ] = None,
  15670. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  15671. fail_on_status_code: typing.Optional[bool] = None,
  15672. max_redirects: typing.Optional[int] = None,
  15673. ) -> "APIRequestContext":
  15674. """APIRequest.new_context
  15675. Creates new instances of `APIRequestContext`.
  15676. Parameters
  15677. ----------
  15678. base_url : Union[str, None]
  15679. Methods like `a_pi_request_context.get()` take the base URL into consideration by using the
  15680. [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
  15681. Examples:
  15682. - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`
  15683. - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in
  15684. `http://localhost:3000/foo/bar.html`
  15685. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  15686. `http://localhost:3000/bar.html`
  15687. extra_http_headers : Union[Dict[str, str], None]
  15688. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  15689. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  15690. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  15691. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  15692. ignore_https_errors : Union[bool, None]
  15693. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15694. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  15695. Network proxy settings.
  15696. user_agent : Union[str, None]
  15697. Specific user agent to use in this context.
  15698. timeout : Union[float, None]
  15699. Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable
  15700. timeout.
  15701. storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}, None]
  15702. Populates context with given storage state. This option can be used to initialize context with logged-in
  15703. information obtained via `browser_context.storage_state()` or `a_pi_request_context.storage_state()`.
  15704. Either a path to the file with saved storage, or the value returned by one of
  15705. `browser_context.storage_state()` or `a_pi_request_context.storage_state()` methods.
  15706. client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None]
  15707. TLS Client Authentication allows the server to request a client certificate and verify it.
  15708. **Details**
  15709. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  15710. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  15711. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  15712. with an exact match to the request origin that the certificate is valid for.
  15713. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  15714. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  15715. does not match any of the domains you plan to visit.
  15716. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  15717. work by replacing `localhost` with `local.playwright`.
  15718. fail_on_status_code : Union[bool, None]
  15719. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15720. codes.
  15721. max_redirects : Union[int, None]
  15722. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15723. exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request
  15724. individually.
  15725. Returns
  15726. -------
  15727. APIRequestContext
  15728. """
  15729. return mapping.from_impl(
  15730. self._sync(
  15731. self._impl_obj.new_context(
  15732. baseURL=base_url,
  15733. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  15734. httpCredentials=http_credentials,
  15735. ignoreHTTPSErrors=ignore_https_errors,
  15736. proxy=proxy,
  15737. userAgent=user_agent,
  15738. timeout=timeout,
  15739. storageState=storage_state,
  15740. clientCertificates=client_certificates,
  15741. failOnStatusCode=fail_on_status_code,
  15742. maxRedirects=max_redirects,
  15743. )
  15744. )
  15745. )
  15746. mapping.register(APIRequestImpl, APIRequest)
  15747. class PageAssertions(SyncBase):
  15748. def to_have_title(
  15749. self,
  15750. title_or_reg_exp: typing.Union[typing.Pattern[str], str],
  15751. *,
  15752. timeout: typing.Optional[float] = None,
  15753. ) -> None:
  15754. """PageAssertions.to_have_title
  15755. Ensures the page has the given title.
  15756. **Usage**
  15757. ```py
  15758. import re
  15759. from playwright.sync_api import expect
  15760. # ...
  15761. expect(page).to_have_title(re.compile(r\".*checkout\"))
  15762. ```
  15763. Parameters
  15764. ----------
  15765. title_or_reg_exp : Union[Pattern[str], str]
  15766. Expected title or RegExp.
  15767. timeout : Union[float, None]
  15768. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15769. """
  15770. __tracebackhide__ = True
  15771. return mapping.from_maybe_impl(
  15772. self._sync(
  15773. self._impl_obj.to_have_title(
  15774. titleOrRegExp=title_or_reg_exp, timeout=timeout
  15775. )
  15776. )
  15777. )
  15778. def not_to_have_title(
  15779. self,
  15780. title_or_reg_exp: typing.Union[typing.Pattern[str], str],
  15781. *,
  15782. timeout: typing.Optional[float] = None,
  15783. ) -> None:
  15784. """PageAssertions.not_to_have_title
  15785. The opposite of `page_assertions.to_have_title()`.
  15786. Parameters
  15787. ----------
  15788. title_or_reg_exp : Union[Pattern[str], str]
  15789. Expected title or RegExp.
  15790. timeout : Union[float, None]
  15791. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15792. """
  15793. __tracebackhide__ = True
  15794. return mapping.from_maybe_impl(
  15795. self._sync(
  15796. self._impl_obj.not_to_have_title(
  15797. titleOrRegExp=title_or_reg_exp, timeout=timeout
  15798. )
  15799. )
  15800. )
  15801. def to_have_url(
  15802. self,
  15803. url_or_reg_exp: typing.Union[str, typing.Pattern[str]],
  15804. *,
  15805. timeout: typing.Optional[float] = None,
  15806. ignore_case: typing.Optional[bool] = None,
  15807. ) -> None:
  15808. """PageAssertions.to_have_url
  15809. Ensures the page is navigated to the given URL.
  15810. **Usage**
  15811. ```py
  15812. import re
  15813. from playwright.sync_api import expect
  15814. # ...
  15815. expect(page).to_have_url(re.compile(\".*checkout\"))
  15816. ```
  15817. Parameters
  15818. ----------
  15819. url_or_reg_exp : Union[Pattern[str], str]
  15820. Expected URL string or RegExp.
  15821. timeout : Union[float, None]
  15822. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15823. ignore_case : Union[bool, None]
  15824. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15825. expression parameter if specified. A provided predicate ignores this flag.
  15826. """
  15827. __tracebackhide__ = True
  15828. return mapping.from_maybe_impl(
  15829. self._sync(
  15830. self._impl_obj.to_have_url(
  15831. urlOrRegExp=url_or_reg_exp, timeout=timeout, ignoreCase=ignore_case
  15832. )
  15833. )
  15834. )
  15835. def not_to_have_url(
  15836. self,
  15837. url_or_reg_exp: typing.Union[typing.Pattern[str], str],
  15838. *,
  15839. timeout: typing.Optional[float] = None,
  15840. ignore_case: typing.Optional[bool] = None,
  15841. ) -> None:
  15842. """PageAssertions.not_to_have_url
  15843. The opposite of `page_assertions.to_have_url()`.
  15844. Parameters
  15845. ----------
  15846. url_or_reg_exp : Union[Pattern[str], str]
  15847. Expected URL string or RegExp.
  15848. timeout : Union[float, None]
  15849. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15850. ignore_case : Union[bool, None]
  15851. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15852. expression flag if specified.
  15853. """
  15854. __tracebackhide__ = True
  15855. return mapping.from_maybe_impl(
  15856. self._sync(
  15857. self._impl_obj.not_to_have_url(
  15858. urlOrRegExp=url_or_reg_exp, timeout=timeout, ignoreCase=ignore_case
  15859. )
  15860. )
  15861. )
  15862. mapping.register(PageAssertionsImpl, PageAssertions)
  15863. class LocatorAssertions(SyncBase):
  15864. def to_contain_text(
  15865. self,
  15866. expected: typing.Union[
  15867. typing.Sequence[str],
  15868. typing.Sequence[typing.Pattern[str]],
  15869. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  15870. typing.Pattern[str],
  15871. str,
  15872. ],
  15873. *,
  15874. use_inner_text: typing.Optional[bool] = None,
  15875. timeout: typing.Optional[float] = None,
  15876. ignore_case: typing.Optional[bool] = None,
  15877. ) -> None:
  15878. """LocatorAssertions.to_contain_text
  15879. Ensures the `Locator` points to an element that contains the given text. All nested elements will be considered
  15880. when computing the text content of the element. You can use regular expressions for the value as well.
  15881. **Details**
  15882. When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
  15883. text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
  15884. **Usage**
  15885. ```py
  15886. import re
  15887. from playwright.sync_api import expect
  15888. locator = page.locator('.title')
  15889. expect(locator).to_contain_text(\"substring\")
  15890. expect(locator).to_contain_text(re.compile(r\"\\d messages\"))
  15891. ```
  15892. If you pass an array as an expected value, the expectations are:
  15893. 1. Locator resolves to a list of elements.
  15894. 1. Elements from a **subset** of this list contain text from the expected array, respectively.
  15895. 1. The matching subset of elements has the same order as the expected array.
  15896. 1. Each text value from the expected array is matched by some element from the list.
  15897. For example, consider the following list:
  15898. ```html
  15899. <ul>
  15900. <li>Item Text 1</li>
  15901. <li>Item Text 2</li>
  15902. <li>Item Text 3</li>
  15903. </ul>
  15904. ```
  15905. Let's see how we can use the assertion:
  15906. ```py
  15907. from playwright.sync_api import expect
  15908. # ✓ Contains the right items in the right order
  15909. expect(page.locator(\"ul > li\")).to_contain_text([\"Text 1\", \"Text 3\"])
  15910. # ✖ Wrong order
  15911. expect(page.locator(\"ul > li\")).to_contain_text([\"Text 3\", \"Text 2\"])
  15912. # ✖ No item contains this text
  15913. expect(page.locator(\"ul > li\")).to_contain_text([\"Some 33\"])
  15914. # ✖ Locator points to the outer list element, not to the list items
  15915. expect(page.locator(\"ul\")).to_contain_text([\"Text 3\"])
  15916. ```
  15917. Parameters
  15918. ----------
  15919. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  15920. Expected substring or RegExp or a list of those.
  15921. use_inner_text : Union[bool, None]
  15922. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  15923. timeout : Union[float, None]
  15924. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15925. ignore_case : Union[bool, None]
  15926. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15927. expression flag if specified.
  15928. """
  15929. __tracebackhide__ = True
  15930. return mapping.from_maybe_impl(
  15931. self._sync(
  15932. self._impl_obj.to_contain_text(
  15933. expected=mapping.to_impl(expected),
  15934. useInnerText=use_inner_text,
  15935. timeout=timeout,
  15936. ignoreCase=ignore_case,
  15937. )
  15938. )
  15939. )
  15940. def not_to_contain_text(
  15941. self,
  15942. expected: typing.Union[
  15943. typing.Sequence[str],
  15944. typing.Sequence[typing.Pattern[str]],
  15945. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  15946. typing.Pattern[str],
  15947. str,
  15948. ],
  15949. *,
  15950. use_inner_text: typing.Optional[bool] = None,
  15951. timeout: typing.Optional[float] = None,
  15952. ignore_case: typing.Optional[bool] = None,
  15953. ) -> None:
  15954. """LocatorAssertions.not_to_contain_text
  15955. The opposite of `locator_assertions.to_contain_text()`.
  15956. Parameters
  15957. ----------
  15958. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  15959. Expected substring or RegExp or a list of those.
  15960. use_inner_text : Union[bool, None]
  15961. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  15962. timeout : Union[float, None]
  15963. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15964. ignore_case : Union[bool, None]
  15965. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15966. expression flag if specified.
  15967. """
  15968. __tracebackhide__ = True
  15969. return mapping.from_maybe_impl(
  15970. self._sync(
  15971. self._impl_obj.not_to_contain_text(
  15972. expected=mapping.to_impl(expected),
  15973. useInnerText=use_inner_text,
  15974. timeout=timeout,
  15975. ignoreCase=ignore_case,
  15976. )
  15977. )
  15978. )
  15979. def to_have_attribute(
  15980. self,
  15981. name: str,
  15982. value: typing.Union[str, typing.Pattern[str]],
  15983. *,
  15984. ignore_case: typing.Optional[bool] = None,
  15985. timeout: typing.Optional[float] = None,
  15986. ) -> None:
  15987. """LocatorAssertions.to_have_attribute
  15988. Ensures the `Locator` points to an element with given attribute.
  15989. **Usage**
  15990. ```py
  15991. from playwright.sync_api import expect
  15992. locator = page.locator(\"input\")
  15993. expect(locator).to_have_attribute(\"type\", \"text\")
  15994. ```
  15995. Parameters
  15996. ----------
  15997. name : str
  15998. Attribute name.
  15999. value : Union[Pattern[str], str]
  16000. Expected attribute value.
  16001. ignore_case : Union[bool, None]
  16002. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16003. expression flag if specified.
  16004. timeout : Union[float, None]
  16005. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16006. """
  16007. __tracebackhide__ = True
  16008. return mapping.from_maybe_impl(
  16009. self._sync(
  16010. self._impl_obj.to_have_attribute(
  16011. name=name, value=value, ignoreCase=ignore_case, timeout=timeout
  16012. )
  16013. )
  16014. )
  16015. def not_to_have_attribute(
  16016. self,
  16017. name: str,
  16018. value: typing.Union[str, typing.Pattern[str]],
  16019. *,
  16020. ignore_case: typing.Optional[bool] = None,
  16021. timeout: typing.Optional[float] = None,
  16022. ) -> None:
  16023. """LocatorAssertions.not_to_have_attribute
  16024. The opposite of `locator_assertions.to_have_attribute()`.
  16025. Parameters
  16026. ----------
  16027. name : str
  16028. Attribute name.
  16029. value : Union[Pattern[str], str]
  16030. Expected attribute value.
  16031. ignore_case : Union[bool, None]
  16032. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16033. expression flag if specified.
  16034. timeout : Union[float, None]
  16035. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16036. """
  16037. __tracebackhide__ = True
  16038. return mapping.from_maybe_impl(
  16039. self._sync(
  16040. self._impl_obj.not_to_have_attribute(
  16041. name=name, value=value, ignoreCase=ignore_case, timeout=timeout
  16042. )
  16043. )
  16044. )
  16045. def to_have_class(
  16046. self,
  16047. expected: typing.Union[
  16048. typing.Sequence[str],
  16049. typing.Sequence[typing.Pattern[str]],
  16050. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16051. typing.Pattern[str],
  16052. str,
  16053. ],
  16054. *,
  16055. timeout: typing.Optional[float] = None,
  16056. ) -> None:
  16057. """LocatorAssertions.to_have_class
  16058. Ensures the `Locator` points to an element with given CSS classes. When a string is provided, it must fully match
  16059. the element's `class` attribute. To match individual classes use `locator_assertions.to_contain_class()`.
  16060. **Usage**
  16061. ```html
  16062. <div class='middle selected row' id='component'></div>
  16063. ```
  16064. ```py
  16065. from playwright.sync_api import expect
  16066. locator = page.locator(\"#component\")
  16067. expect(locator).to_have_class(\"middle selected row\")
  16068. expect(locator).to_have_class(re.compile(r\"(^|\\\\s)selected(\\\\s|$)\"))
  16069. ```
  16070. When an array is passed, the method asserts that the list of elements located matches the corresponding list of
  16071. expected class values. Each element's class attribute is matched against the corresponding string or regular
  16072. expression in the array:
  16073. ```py
  16074. from playwright.sync_api import expect
  16075. locator = page.locator(\".list > .component\")
  16076. expect(locator).to_have_class([\"component\", \"component selected\", \"component\"])
  16077. ```
  16078. Parameters
  16079. ----------
  16080. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  16081. Expected class or RegExp or a list of those.
  16082. timeout : Union[float, None]
  16083. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16084. """
  16085. __tracebackhide__ = True
  16086. return mapping.from_maybe_impl(
  16087. self._sync(
  16088. self._impl_obj.to_have_class(
  16089. expected=mapping.to_impl(expected), timeout=timeout
  16090. )
  16091. )
  16092. )
  16093. def not_to_have_class(
  16094. self,
  16095. expected: typing.Union[
  16096. typing.Sequence[str],
  16097. typing.Sequence[typing.Pattern[str]],
  16098. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16099. typing.Pattern[str],
  16100. str,
  16101. ],
  16102. *,
  16103. timeout: typing.Optional[float] = None,
  16104. ) -> None:
  16105. """LocatorAssertions.not_to_have_class
  16106. The opposite of `locator_assertions.to_have_class()`.
  16107. Parameters
  16108. ----------
  16109. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  16110. Expected class or RegExp or a list of those.
  16111. timeout : Union[float, None]
  16112. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16113. """
  16114. __tracebackhide__ = True
  16115. return mapping.from_maybe_impl(
  16116. self._sync(
  16117. self._impl_obj.not_to_have_class(
  16118. expected=mapping.to_impl(expected), timeout=timeout
  16119. )
  16120. )
  16121. )
  16122. def to_contain_class(
  16123. self,
  16124. expected: typing.Union[typing.Sequence[str], str],
  16125. *,
  16126. timeout: typing.Optional[float] = None,
  16127. ) -> None:
  16128. """LocatorAssertions.to_contain_class
  16129. Ensures the `Locator` points to an element with given CSS classes. All classes from the asserted value, separated
  16130. by spaces, must be present in the
  16131. [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) in any order.
  16132. **Usage**
  16133. ```html
  16134. <div class='middle selected row' id='component'></div>
  16135. ```
  16136. ```py
  16137. from playwright.sync_api import expect
  16138. locator = page.locator(\"#component\")
  16139. expect(locator).to_contain_class(\"middle selected row\")
  16140. expect(locator).to_contain_class(\"selected\")
  16141. expect(locator).to_contain_class(\"row middle\")
  16142. ```
  16143. When an array is passed, the method asserts that the list of elements located matches the corresponding list of
  16144. expected class lists. Each element's class attribute is matched against the corresponding class in the array:
  16145. ```html
  16146. <div class='list'>
  16147. <div class='component inactive'></div>
  16148. <div class='component active'></div>
  16149. <div class='component inactive'></div>
  16150. </div>
  16151. ```
  16152. ```py
  16153. from playwright.sync_api import expect
  16154. locator = page.locator(\".list > .component\")
  16155. await expect(locator).to_contain_class([\"inactive\", \"active\", \"inactive\"])
  16156. ```
  16157. Parameters
  16158. ----------
  16159. expected : Union[Sequence[str], str]
  16160. A string containing expected class names, separated by spaces, or a list of such strings to assert multiple
  16161. elements.
  16162. timeout : Union[float, None]
  16163. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16164. """
  16165. __tracebackhide__ = True
  16166. return mapping.from_maybe_impl(
  16167. self._sync(
  16168. self._impl_obj.to_contain_class(
  16169. expected=mapping.to_impl(expected), timeout=timeout
  16170. )
  16171. )
  16172. )
  16173. def not_to_contain_class(
  16174. self,
  16175. expected: typing.Union[typing.Sequence[str], str],
  16176. *,
  16177. timeout: typing.Optional[float] = None,
  16178. ) -> None:
  16179. """LocatorAssertions.not_to_contain_class
  16180. The opposite of `locator_assertions.to_contain_class()`.
  16181. Parameters
  16182. ----------
  16183. expected : Union[Sequence[str], str]
  16184. Expected class or RegExp or a list of those.
  16185. timeout : Union[float, None]
  16186. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16187. """
  16188. __tracebackhide__ = True
  16189. return mapping.from_maybe_impl(
  16190. self._sync(
  16191. self._impl_obj.not_to_contain_class(
  16192. expected=mapping.to_impl(expected), timeout=timeout
  16193. )
  16194. )
  16195. )
  16196. def to_have_count(
  16197. self, count: int, *, timeout: typing.Optional[float] = None
  16198. ) -> None:
  16199. """LocatorAssertions.to_have_count
  16200. Ensures the `Locator` resolves to an exact number of DOM nodes.
  16201. **Usage**
  16202. ```py
  16203. from playwright.sync_api import expect
  16204. locator = page.locator(\"list > .component\")
  16205. expect(locator).to_have_count(3)
  16206. ```
  16207. Parameters
  16208. ----------
  16209. count : int
  16210. Expected count.
  16211. timeout : Union[float, None]
  16212. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16213. """
  16214. __tracebackhide__ = True
  16215. return mapping.from_maybe_impl(
  16216. self._sync(self._impl_obj.to_have_count(count=count, timeout=timeout))
  16217. )
  16218. def not_to_have_count(
  16219. self, count: int, *, timeout: typing.Optional[float] = None
  16220. ) -> None:
  16221. """LocatorAssertions.not_to_have_count
  16222. The opposite of `locator_assertions.to_have_count()`.
  16223. Parameters
  16224. ----------
  16225. count : int
  16226. Expected count.
  16227. timeout : Union[float, None]
  16228. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16229. """
  16230. __tracebackhide__ = True
  16231. return mapping.from_maybe_impl(
  16232. self._sync(self._impl_obj.not_to_have_count(count=count, timeout=timeout))
  16233. )
  16234. def to_have_css(
  16235. self,
  16236. name: str,
  16237. value: typing.Union[str, typing.Pattern[str]],
  16238. *,
  16239. timeout: typing.Optional[float] = None,
  16240. ) -> None:
  16241. """LocatorAssertions.to_have_css
  16242. Ensures the `Locator` resolves to an element with the given computed CSS style.
  16243. **Usage**
  16244. ```py
  16245. from playwright.sync_api import expect
  16246. locator = page.get_by_role(\"button\")
  16247. expect(locator).to_have_css(\"display\", \"flex\")
  16248. ```
  16249. Parameters
  16250. ----------
  16251. name : str
  16252. CSS property name.
  16253. value : Union[Pattern[str], str]
  16254. CSS property value.
  16255. timeout : Union[float, None]
  16256. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16257. """
  16258. __tracebackhide__ = True
  16259. return mapping.from_maybe_impl(
  16260. self._sync(
  16261. self._impl_obj.to_have_css(name=name, value=value, timeout=timeout)
  16262. )
  16263. )
  16264. def not_to_have_css(
  16265. self,
  16266. name: str,
  16267. value: typing.Union[str, typing.Pattern[str]],
  16268. *,
  16269. timeout: typing.Optional[float] = None,
  16270. ) -> None:
  16271. """LocatorAssertions.not_to_have_css
  16272. The opposite of `locator_assertions.to_have_css()`.
  16273. Parameters
  16274. ----------
  16275. name : str
  16276. CSS property name.
  16277. value : Union[Pattern[str], str]
  16278. CSS property value.
  16279. timeout : Union[float, None]
  16280. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16281. """
  16282. __tracebackhide__ = True
  16283. return mapping.from_maybe_impl(
  16284. self._sync(
  16285. self._impl_obj.not_to_have_css(name=name, value=value, timeout=timeout)
  16286. )
  16287. )
  16288. def to_have_id(
  16289. self,
  16290. id: typing.Union[str, typing.Pattern[str]],
  16291. *,
  16292. timeout: typing.Optional[float] = None,
  16293. ) -> None:
  16294. """LocatorAssertions.to_have_id
  16295. Ensures the `Locator` points to an element with the given DOM Node ID.
  16296. **Usage**
  16297. ```py
  16298. from playwright.sync_api import expect
  16299. locator = page.get_by_role(\"textbox\")
  16300. expect(locator).to_have_id(\"lastname\")
  16301. ```
  16302. Parameters
  16303. ----------
  16304. id : Union[Pattern[str], str]
  16305. Element id.
  16306. timeout : Union[float, None]
  16307. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16308. """
  16309. __tracebackhide__ = True
  16310. return mapping.from_maybe_impl(
  16311. self._sync(self._impl_obj.to_have_id(id=id, timeout=timeout))
  16312. )
  16313. def not_to_have_id(
  16314. self,
  16315. id: typing.Union[str, typing.Pattern[str]],
  16316. *,
  16317. timeout: typing.Optional[float] = None,
  16318. ) -> None:
  16319. """LocatorAssertions.not_to_have_id
  16320. The opposite of `locator_assertions.to_have_id()`.
  16321. Parameters
  16322. ----------
  16323. id : Union[Pattern[str], str]
  16324. Element id.
  16325. timeout : Union[float, None]
  16326. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16327. """
  16328. __tracebackhide__ = True
  16329. return mapping.from_maybe_impl(
  16330. self._sync(self._impl_obj.not_to_have_id(id=id, timeout=timeout))
  16331. )
  16332. def to_have_js_property(
  16333. self, name: str, value: typing.Any, *, timeout: typing.Optional[float] = None
  16334. ) -> None:
  16335. """LocatorAssertions.to_have_js_property
  16336. Ensures the `Locator` points to an element with given JavaScript property. Note that this property can be of a
  16337. primitive type as well as a plain serializable JavaScript object.
  16338. **Usage**
  16339. ```py
  16340. from playwright.sync_api import expect
  16341. locator = page.locator(\".component\")
  16342. expect(locator).to_have_js_property(\"loaded\", True)
  16343. ```
  16344. Parameters
  16345. ----------
  16346. name : str
  16347. Property name.
  16348. value : Any
  16349. Property value.
  16350. timeout : Union[float, None]
  16351. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16352. """
  16353. __tracebackhide__ = True
  16354. return mapping.from_maybe_impl(
  16355. self._sync(
  16356. self._impl_obj.to_have_js_property(
  16357. name=name, value=mapping.to_impl(value), timeout=timeout
  16358. )
  16359. )
  16360. )
  16361. def not_to_have_js_property(
  16362. self, name: str, value: typing.Any, *, timeout: typing.Optional[float] = None
  16363. ) -> None:
  16364. """LocatorAssertions.not_to_have_js_property
  16365. The opposite of `locator_assertions.to_have_js_property()`.
  16366. Parameters
  16367. ----------
  16368. name : str
  16369. Property name.
  16370. value : Any
  16371. Property value.
  16372. timeout : Union[float, None]
  16373. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16374. """
  16375. __tracebackhide__ = True
  16376. return mapping.from_maybe_impl(
  16377. self._sync(
  16378. self._impl_obj.not_to_have_js_property(
  16379. name=name, value=mapping.to_impl(value), timeout=timeout
  16380. )
  16381. )
  16382. )
  16383. def to_have_value(
  16384. self,
  16385. value: typing.Union[str, typing.Pattern[str]],
  16386. *,
  16387. timeout: typing.Optional[float] = None,
  16388. ) -> None:
  16389. """LocatorAssertions.to_have_value
  16390. Ensures the `Locator` points to an element with the given input value. You can use regular expressions for the
  16391. value as well.
  16392. **Usage**
  16393. ```py
  16394. import re
  16395. from playwright.sync_api import expect
  16396. locator = page.locator(\"input[type=number]\")
  16397. expect(locator).to_have_value(re.compile(r\"[0-9]\"))
  16398. ```
  16399. Parameters
  16400. ----------
  16401. value : Union[Pattern[str], str]
  16402. Expected value.
  16403. timeout : Union[float, None]
  16404. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16405. """
  16406. __tracebackhide__ = True
  16407. return mapping.from_maybe_impl(
  16408. self._sync(self._impl_obj.to_have_value(value=value, timeout=timeout))
  16409. )
  16410. def not_to_have_value(
  16411. self,
  16412. value: typing.Union[str, typing.Pattern[str]],
  16413. *,
  16414. timeout: typing.Optional[float] = None,
  16415. ) -> None:
  16416. """LocatorAssertions.not_to_have_value
  16417. The opposite of `locator_assertions.to_have_value()`.
  16418. Parameters
  16419. ----------
  16420. value : Union[Pattern[str], str]
  16421. Expected value.
  16422. timeout : Union[float, None]
  16423. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16424. """
  16425. __tracebackhide__ = True
  16426. return mapping.from_maybe_impl(
  16427. self._sync(self._impl_obj.not_to_have_value(value=value, timeout=timeout))
  16428. )
  16429. def to_have_values(
  16430. self,
  16431. values: typing.Union[
  16432. typing.Sequence[str],
  16433. typing.Sequence[typing.Pattern[str]],
  16434. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16435. ],
  16436. *,
  16437. timeout: typing.Optional[float] = None,
  16438. ) -> None:
  16439. """LocatorAssertions.to_have_values
  16440. Ensures the `Locator` points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the
  16441. specified values are selected.
  16442. **Usage**
  16443. For example, given the following element:
  16444. ```html
  16445. <select id=\"favorite-colors\" multiple>
  16446. <option value=\"R\">Red</option>
  16447. <option value=\"G\">Green</option>
  16448. <option value=\"B\">Blue</option>
  16449. </select>
  16450. ```
  16451. ```py
  16452. import re
  16453. from playwright.sync_api import expect
  16454. locator = page.locator(\"id=favorite-colors\")
  16455. locator.select_option([\"R\", \"G\"])
  16456. expect(locator).to_have_values([re.compile(r\"R\"), re.compile(r\"G\")])
  16457. ```
  16458. Parameters
  16459. ----------
  16460. values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
  16461. Expected options currently selected.
  16462. timeout : Union[float, None]
  16463. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16464. """
  16465. __tracebackhide__ = True
  16466. return mapping.from_maybe_impl(
  16467. self._sync(
  16468. self._impl_obj.to_have_values(
  16469. values=mapping.to_impl(values), timeout=timeout
  16470. )
  16471. )
  16472. )
  16473. def not_to_have_values(
  16474. self,
  16475. values: typing.Union[
  16476. typing.Sequence[str],
  16477. typing.Sequence[typing.Pattern[str]],
  16478. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16479. ],
  16480. *,
  16481. timeout: typing.Optional[float] = None,
  16482. ) -> None:
  16483. """LocatorAssertions.not_to_have_values
  16484. The opposite of `locator_assertions.to_have_values()`.
  16485. Parameters
  16486. ----------
  16487. values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
  16488. Expected options currently selected.
  16489. timeout : Union[float, None]
  16490. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16491. """
  16492. __tracebackhide__ = True
  16493. return mapping.from_maybe_impl(
  16494. self._sync(
  16495. self._impl_obj.not_to_have_values(
  16496. values=mapping.to_impl(values), timeout=timeout
  16497. )
  16498. )
  16499. )
  16500. def to_have_text(
  16501. self,
  16502. expected: typing.Union[
  16503. typing.Sequence[str],
  16504. typing.Sequence[typing.Pattern[str]],
  16505. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16506. typing.Pattern[str],
  16507. str,
  16508. ],
  16509. *,
  16510. use_inner_text: typing.Optional[bool] = None,
  16511. timeout: typing.Optional[float] = None,
  16512. ignore_case: typing.Optional[bool] = None,
  16513. ) -> None:
  16514. """LocatorAssertions.to_have_text
  16515. Ensures the `Locator` points to an element with the given text. All nested elements will be considered when
  16516. computing the text content of the element. You can use regular expressions for the value as well.
  16517. **Details**
  16518. When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
  16519. text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
  16520. **Usage**
  16521. ```py
  16522. import re
  16523. from playwright.sync_api import expect
  16524. locator = page.locator(\".title\")
  16525. expect(locator).to_have_text(re.compile(r\"Welcome, Test User\"))
  16526. expect(locator).to_have_text(re.compile(r\"Welcome, .*\"))
  16527. ```
  16528. If you pass an array as an expected value, the expectations are:
  16529. 1. Locator resolves to a list of elements.
  16530. 1. The number of elements equals the number of expected values in the array.
  16531. 1. Elements from the list have text matching expected array values, one by one, in order.
  16532. For example, consider the following list:
  16533. ```html
  16534. <ul>
  16535. <li>Text 1</li>
  16536. <li>Text 2</li>
  16537. <li>Text 3</li>
  16538. </ul>
  16539. ```
  16540. Let's see how we can use the assertion:
  16541. ```py
  16542. from playwright.sync_api import expect
  16543. # ✓ Has the right items in the right order
  16544. expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
  16545. # ✖ Wrong order
  16546. expect(page.locator(\"ul > li\")).to_have_text([\"Text 3\", \"Text 2\", \"Text 1\"])
  16547. # ✖ Last item does not match
  16548. expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text\"])
  16549. # ✖ Locator points to the outer list element, not to the list items
  16550. expect(page.locator(\"ul\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
  16551. ```
  16552. Parameters
  16553. ----------
  16554. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  16555. Expected string or RegExp or a list of those.
  16556. use_inner_text : Union[bool, None]
  16557. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  16558. timeout : Union[float, None]
  16559. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16560. ignore_case : Union[bool, None]
  16561. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16562. expression flag if specified.
  16563. """
  16564. __tracebackhide__ = True
  16565. return mapping.from_maybe_impl(
  16566. self._sync(
  16567. self._impl_obj.to_have_text(
  16568. expected=mapping.to_impl(expected),
  16569. useInnerText=use_inner_text,
  16570. timeout=timeout,
  16571. ignoreCase=ignore_case,
  16572. )
  16573. )
  16574. )
  16575. def not_to_have_text(
  16576. self,
  16577. expected: typing.Union[
  16578. typing.Sequence[str],
  16579. typing.Sequence[typing.Pattern[str]],
  16580. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16581. typing.Pattern[str],
  16582. str,
  16583. ],
  16584. *,
  16585. use_inner_text: typing.Optional[bool] = None,
  16586. timeout: typing.Optional[float] = None,
  16587. ignore_case: typing.Optional[bool] = None,
  16588. ) -> None:
  16589. """LocatorAssertions.not_to_have_text
  16590. The opposite of `locator_assertions.to_have_text()`.
  16591. Parameters
  16592. ----------
  16593. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  16594. Expected string or RegExp or a list of those.
  16595. use_inner_text : Union[bool, None]
  16596. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  16597. timeout : Union[float, None]
  16598. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16599. ignore_case : Union[bool, None]
  16600. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16601. expression flag if specified.
  16602. """
  16603. __tracebackhide__ = True
  16604. return mapping.from_maybe_impl(
  16605. self._sync(
  16606. self._impl_obj.not_to_have_text(
  16607. expected=mapping.to_impl(expected),
  16608. useInnerText=use_inner_text,
  16609. timeout=timeout,
  16610. ignoreCase=ignore_case,
  16611. )
  16612. )
  16613. )
  16614. def to_be_attached(
  16615. self,
  16616. *,
  16617. attached: typing.Optional[bool] = None,
  16618. timeout: typing.Optional[float] = None,
  16619. ) -> None:
  16620. """LocatorAssertions.to_be_attached
  16621. Ensures that `Locator` points to an element that is
  16622. [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
  16623. **Usage**
  16624. ```py
  16625. expect(page.get_by_text(\"Hidden text\")).to_be_attached()
  16626. ```
  16627. Parameters
  16628. ----------
  16629. attached : Union[bool, None]
  16630. timeout : Union[float, None]
  16631. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16632. """
  16633. __tracebackhide__ = True
  16634. return mapping.from_maybe_impl(
  16635. self._sync(
  16636. self._impl_obj.to_be_attached(attached=attached, timeout=timeout)
  16637. )
  16638. )
  16639. def to_be_checked(
  16640. self,
  16641. *,
  16642. timeout: typing.Optional[float] = None,
  16643. checked: typing.Optional[bool] = None,
  16644. indeterminate: typing.Optional[bool] = None,
  16645. ) -> None:
  16646. """LocatorAssertions.to_be_checked
  16647. Ensures the `Locator` points to a checked input.
  16648. **Usage**
  16649. ```py
  16650. from playwright.sync_api import expect
  16651. locator = page.get_by_label(\"Subscribe to newsletter\")
  16652. expect(locator).to_be_checked()
  16653. ```
  16654. Parameters
  16655. ----------
  16656. timeout : Union[float, None]
  16657. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16658. checked : Union[bool, None]
  16659. Provides state to assert for. Asserts for input to be checked by default. This option can't be used when
  16660. `indeterminate` is set to true.
  16661. indeterminate : Union[bool, None]
  16662. Asserts that the element is in the indeterminate (mixed) state. Only supported for checkboxes and radio buttons.
  16663. This option can't be true when `checked` is provided.
  16664. """
  16665. __tracebackhide__ = True
  16666. return mapping.from_maybe_impl(
  16667. self._sync(
  16668. self._impl_obj.to_be_checked(
  16669. timeout=timeout, checked=checked, indeterminate=indeterminate
  16670. )
  16671. )
  16672. )
  16673. def not_to_be_attached(
  16674. self,
  16675. *,
  16676. attached: typing.Optional[bool] = None,
  16677. timeout: typing.Optional[float] = None,
  16678. ) -> None:
  16679. """LocatorAssertions.not_to_be_attached
  16680. The opposite of `locator_assertions.to_be_attached()`.
  16681. Parameters
  16682. ----------
  16683. attached : Union[bool, None]
  16684. timeout : Union[float, None]
  16685. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16686. """
  16687. __tracebackhide__ = True
  16688. return mapping.from_maybe_impl(
  16689. self._sync(
  16690. self._impl_obj.not_to_be_attached(attached=attached, timeout=timeout)
  16691. )
  16692. )
  16693. def not_to_be_checked(self, *, timeout: typing.Optional[float] = None) -> None:
  16694. """LocatorAssertions.not_to_be_checked
  16695. The opposite of `locator_assertions.to_be_checked()`.
  16696. Parameters
  16697. ----------
  16698. timeout : Union[float, None]
  16699. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16700. """
  16701. __tracebackhide__ = True
  16702. return mapping.from_maybe_impl(
  16703. self._sync(self._impl_obj.not_to_be_checked(timeout=timeout))
  16704. )
  16705. def to_be_disabled(self, *, timeout: typing.Optional[float] = None) -> None:
  16706. """LocatorAssertions.to_be_disabled
  16707. Ensures the `Locator` points to a disabled element. Element is disabled if it has \"disabled\" attribute or is
  16708. disabled via
  16709. ['aria-disabled'](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled). Note
  16710. that only native control elements such as HTML `button`, `input`, `select`, `textarea`, `option`, `optgroup` can be
  16711. disabled by setting \"disabled\" attribute. \"disabled\" attribute on other elements is ignored by the browser.
  16712. **Usage**
  16713. ```py
  16714. from playwright.sync_api import expect
  16715. locator = page.locator(\"button.submit\")
  16716. expect(locator).to_be_disabled()
  16717. ```
  16718. Parameters
  16719. ----------
  16720. timeout : Union[float, None]
  16721. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16722. """
  16723. __tracebackhide__ = True
  16724. return mapping.from_maybe_impl(
  16725. self._sync(self._impl_obj.to_be_disabled(timeout=timeout))
  16726. )
  16727. def not_to_be_disabled(self, *, timeout: typing.Optional[float] = None) -> None:
  16728. """LocatorAssertions.not_to_be_disabled
  16729. The opposite of `locator_assertions.to_be_disabled()`.
  16730. Parameters
  16731. ----------
  16732. timeout : Union[float, None]
  16733. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16734. """
  16735. __tracebackhide__ = True
  16736. return mapping.from_maybe_impl(
  16737. self._sync(self._impl_obj.not_to_be_disabled(timeout=timeout))
  16738. )
  16739. def to_be_editable(
  16740. self,
  16741. *,
  16742. editable: typing.Optional[bool] = None,
  16743. timeout: typing.Optional[float] = None,
  16744. ) -> None:
  16745. """LocatorAssertions.to_be_editable
  16746. Ensures the `Locator` points to an editable element.
  16747. **Usage**
  16748. ```py
  16749. from playwright.sync_api import expect
  16750. locator = page.get_by_role(\"textbox\")
  16751. expect(locator).to_be_editable()
  16752. ```
  16753. Parameters
  16754. ----------
  16755. editable : Union[bool, None]
  16756. timeout : Union[float, None]
  16757. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16758. """
  16759. __tracebackhide__ = True
  16760. return mapping.from_maybe_impl(
  16761. self._sync(
  16762. self._impl_obj.to_be_editable(editable=editable, timeout=timeout)
  16763. )
  16764. )
  16765. def not_to_be_editable(
  16766. self,
  16767. *,
  16768. editable: typing.Optional[bool] = None,
  16769. timeout: typing.Optional[float] = None,
  16770. ) -> None:
  16771. """LocatorAssertions.not_to_be_editable
  16772. The opposite of `locator_assertions.to_be_editable()`.
  16773. Parameters
  16774. ----------
  16775. editable : Union[bool, None]
  16776. timeout : Union[float, None]
  16777. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16778. """
  16779. __tracebackhide__ = True
  16780. return mapping.from_maybe_impl(
  16781. self._sync(
  16782. self._impl_obj.not_to_be_editable(editable=editable, timeout=timeout)
  16783. )
  16784. )
  16785. def to_be_empty(self, *, timeout: typing.Optional[float] = None) -> None:
  16786. """LocatorAssertions.to_be_empty
  16787. Ensures the `Locator` points to an empty editable element or to a DOM node that has no text.
  16788. **Usage**
  16789. ```py
  16790. from playwright.sync_api import expect
  16791. locator = page.locator(\"div.warning\")
  16792. expect(locator).to_be_empty()
  16793. ```
  16794. Parameters
  16795. ----------
  16796. timeout : Union[float, None]
  16797. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16798. """
  16799. __tracebackhide__ = True
  16800. return mapping.from_maybe_impl(
  16801. self._sync(self._impl_obj.to_be_empty(timeout=timeout))
  16802. )
  16803. def not_to_be_empty(self, *, timeout: typing.Optional[float] = None) -> None:
  16804. """LocatorAssertions.not_to_be_empty
  16805. The opposite of `locator_assertions.to_be_empty()`.
  16806. Parameters
  16807. ----------
  16808. timeout : Union[float, None]
  16809. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16810. """
  16811. __tracebackhide__ = True
  16812. return mapping.from_maybe_impl(
  16813. self._sync(self._impl_obj.not_to_be_empty(timeout=timeout))
  16814. )
  16815. def to_be_enabled(
  16816. self,
  16817. *,
  16818. enabled: typing.Optional[bool] = None,
  16819. timeout: typing.Optional[float] = None,
  16820. ) -> None:
  16821. """LocatorAssertions.to_be_enabled
  16822. Ensures the `Locator` points to an enabled element.
  16823. **Usage**
  16824. ```py
  16825. from playwright.sync_api import expect
  16826. locator = page.locator(\"button.submit\")
  16827. expect(locator).to_be_enabled()
  16828. ```
  16829. Parameters
  16830. ----------
  16831. enabled : Union[bool, None]
  16832. timeout : Union[float, None]
  16833. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16834. """
  16835. __tracebackhide__ = True
  16836. return mapping.from_maybe_impl(
  16837. self._sync(self._impl_obj.to_be_enabled(enabled=enabled, timeout=timeout))
  16838. )
  16839. def not_to_be_enabled(
  16840. self,
  16841. *,
  16842. enabled: typing.Optional[bool] = None,
  16843. timeout: typing.Optional[float] = None,
  16844. ) -> None:
  16845. """LocatorAssertions.not_to_be_enabled
  16846. The opposite of `locator_assertions.to_be_enabled()`.
  16847. Parameters
  16848. ----------
  16849. enabled : Union[bool, None]
  16850. timeout : Union[float, None]
  16851. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16852. """
  16853. __tracebackhide__ = True
  16854. return mapping.from_maybe_impl(
  16855. self._sync(
  16856. self._impl_obj.not_to_be_enabled(enabled=enabled, timeout=timeout)
  16857. )
  16858. )
  16859. def to_be_hidden(self, *, timeout: typing.Optional[float] = None) -> None:
  16860. """LocatorAssertions.to_be_hidden
  16861. Ensures that `Locator` either does not resolve to any DOM node, or resolves to a
  16862. [non-visible](https://playwright.dev/python/docs/actionability#visible) one.
  16863. **Usage**
  16864. ```py
  16865. from playwright.sync_api import expect
  16866. locator = page.locator('.my-element')
  16867. expect(locator).to_be_hidden()
  16868. ```
  16869. Parameters
  16870. ----------
  16871. timeout : Union[float, None]
  16872. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16873. """
  16874. __tracebackhide__ = True
  16875. return mapping.from_maybe_impl(
  16876. self._sync(self._impl_obj.to_be_hidden(timeout=timeout))
  16877. )
  16878. def not_to_be_hidden(self, *, timeout: typing.Optional[float] = None) -> None:
  16879. """LocatorAssertions.not_to_be_hidden
  16880. The opposite of `locator_assertions.to_be_hidden()`.
  16881. Parameters
  16882. ----------
  16883. timeout : Union[float, None]
  16884. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16885. """
  16886. __tracebackhide__ = True
  16887. return mapping.from_maybe_impl(
  16888. self._sync(self._impl_obj.not_to_be_hidden(timeout=timeout))
  16889. )
  16890. def to_be_visible(
  16891. self,
  16892. *,
  16893. visible: typing.Optional[bool] = None,
  16894. timeout: typing.Optional[float] = None,
  16895. ) -> None:
  16896. """LocatorAssertions.to_be_visible
  16897. Ensures that `Locator` points to an attached and [visible](https://playwright.dev/python/docs/actionability#visible) DOM node.
  16898. To check that at least one element from the list is visible, use `locator.first()`.
  16899. **Usage**
  16900. ```py
  16901. # A specific element is visible.
  16902. expect(page.get_by_text(\"Welcome\")).to_be_visible()
  16903. # At least one item in the list is visible.
  16904. expect(page.get_by_test_id(\"todo-item\").first).to_be_visible()
  16905. # At least one of the two elements is visible, possibly both.
  16906. expect(
  16907. page.get_by_role(\"button\", name=\"Sign in\")
  16908. .or_(page.get_by_role(\"button\", name=\"Sign up\"))
  16909. .first
  16910. ).to_be_visible()
  16911. ```
  16912. Parameters
  16913. ----------
  16914. visible : Union[bool, None]
  16915. timeout : Union[float, None]
  16916. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16917. """
  16918. __tracebackhide__ = True
  16919. return mapping.from_maybe_impl(
  16920. self._sync(self._impl_obj.to_be_visible(visible=visible, timeout=timeout))
  16921. )
  16922. def not_to_be_visible(
  16923. self,
  16924. *,
  16925. visible: typing.Optional[bool] = None,
  16926. timeout: typing.Optional[float] = None,
  16927. ) -> None:
  16928. """LocatorAssertions.not_to_be_visible
  16929. The opposite of `locator_assertions.to_be_visible()`.
  16930. Parameters
  16931. ----------
  16932. visible : Union[bool, None]
  16933. timeout : Union[float, None]
  16934. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16935. """
  16936. __tracebackhide__ = True
  16937. return mapping.from_maybe_impl(
  16938. self._sync(
  16939. self._impl_obj.not_to_be_visible(visible=visible, timeout=timeout)
  16940. )
  16941. )
  16942. def to_be_focused(self, *, timeout: typing.Optional[float] = None) -> None:
  16943. """LocatorAssertions.to_be_focused
  16944. Ensures the `Locator` points to a focused DOM node.
  16945. **Usage**
  16946. ```py
  16947. from playwright.sync_api import expect
  16948. locator = page.get_by_role(\"textbox\")
  16949. expect(locator).to_be_focused()
  16950. ```
  16951. Parameters
  16952. ----------
  16953. timeout : Union[float, None]
  16954. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16955. """
  16956. __tracebackhide__ = True
  16957. return mapping.from_maybe_impl(
  16958. self._sync(self._impl_obj.to_be_focused(timeout=timeout))
  16959. )
  16960. def not_to_be_focused(self, *, timeout: typing.Optional[float] = None) -> None:
  16961. """LocatorAssertions.not_to_be_focused
  16962. The opposite of `locator_assertions.to_be_focused()`.
  16963. Parameters
  16964. ----------
  16965. timeout : Union[float, None]
  16966. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16967. """
  16968. __tracebackhide__ = True
  16969. return mapping.from_maybe_impl(
  16970. self._sync(self._impl_obj.not_to_be_focused(timeout=timeout))
  16971. )
  16972. def to_be_in_viewport(
  16973. self,
  16974. *,
  16975. ratio: typing.Optional[float] = None,
  16976. timeout: typing.Optional[float] = None,
  16977. ) -> None:
  16978. """LocatorAssertions.to_be_in_viewport
  16979. Ensures the `Locator` points to an element that intersects viewport, according to the
  16980. [intersection observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
  16981. **Usage**
  16982. ```py
  16983. from playwright.sync_api import expect
  16984. locator = page.get_by_role(\"button\")
  16985. # Make sure at least some part of element intersects viewport.
  16986. expect(locator).to_be_in_viewport()
  16987. # Make sure element is fully outside of viewport.
  16988. expect(locator).not_to_be_in_viewport()
  16989. # Make sure that at least half of the element intersects viewport.
  16990. expect(locator).to_be_in_viewport(ratio=0.5)
  16991. ```
  16992. Parameters
  16993. ----------
  16994. ratio : Union[float, None]
  16995. The minimal ratio of the element to intersect viewport. If equals to `0`, then element should intersect viewport at
  16996. any positive ratio. Defaults to `0`.
  16997. timeout : Union[float, None]
  16998. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16999. """
  17000. __tracebackhide__ = True
  17001. return mapping.from_maybe_impl(
  17002. self._sync(self._impl_obj.to_be_in_viewport(ratio=ratio, timeout=timeout))
  17003. )
  17004. def not_to_be_in_viewport(
  17005. self,
  17006. *,
  17007. ratio: typing.Optional[float] = None,
  17008. timeout: typing.Optional[float] = None,
  17009. ) -> None:
  17010. """LocatorAssertions.not_to_be_in_viewport
  17011. The opposite of `locator_assertions.to_be_in_viewport()`.
  17012. Parameters
  17013. ----------
  17014. ratio : Union[float, None]
  17015. timeout : Union[float, None]
  17016. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17017. """
  17018. __tracebackhide__ = True
  17019. return mapping.from_maybe_impl(
  17020. self._sync(
  17021. self._impl_obj.not_to_be_in_viewport(ratio=ratio, timeout=timeout)
  17022. )
  17023. )
  17024. def to_have_accessible_description(
  17025. self,
  17026. description: typing.Union[str, typing.Pattern[str]],
  17027. *,
  17028. ignore_case: typing.Optional[bool] = None,
  17029. timeout: typing.Optional[float] = None,
  17030. ) -> None:
  17031. """LocatorAssertions.to_have_accessible_description
  17032. Ensures the `Locator` points to an element with a given
  17033. [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  17034. **Usage**
  17035. ```py
  17036. locator = page.get_by_test_id(\"save-button\")
  17037. expect(locator).to_have_accessible_description(\"Save results to disk\")
  17038. ```
  17039. Parameters
  17040. ----------
  17041. description : Union[Pattern[str], str]
  17042. Expected accessible description.
  17043. ignore_case : Union[bool, None]
  17044. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17045. expression flag if specified.
  17046. timeout : Union[float, None]
  17047. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17048. """
  17049. __tracebackhide__ = True
  17050. return mapping.from_maybe_impl(
  17051. self._sync(
  17052. self._impl_obj.to_have_accessible_description(
  17053. description=description, ignoreCase=ignore_case, timeout=timeout
  17054. )
  17055. )
  17056. )
  17057. def not_to_have_accessible_description(
  17058. self,
  17059. name: typing.Union[str, typing.Pattern[str]],
  17060. *,
  17061. ignore_case: typing.Optional[bool] = None,
  17062. timeout: typing.Optional[float] = None,
  17063. ) -> None:
  17064. """LocatorAssertions.not_to_have_accessible_description
  17065. The opposite of `locator_assertions.to_have_accessible_description()`.
  17066. Parameters
  17067. ----------
  17068. name : Union[Pattern[str], str]
  17069. Expected accessible description.
  17070. ignore_case : Union[bool, None]
  17071. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17072. expression flag if specified.
  17073. timeout : Union[float, None]
  17074. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17075. """
  17076. __tracebackhide__ = True
  17077. return mapping.from_maybe_impl(
  17078. self._sync(
  17079. self._impl_obj.not_to_have_accessible_description(
  17080. name=name, ignoreCase=ignore_case, timeout=timeout
  17081. )
  17082. )
  17083. )
  17084. def to_have_accessible_name(
  17085. self,
  17086. name: typing.Union[str, typing.Pattern[str]],
  17087. *,
  17088. ignore_case: typing.Optional[bool] = None,
  17089. timeout: typing.Optional[float] = None,
  17090. ) -> None:
  17091. """LocatorAssertions.to_have_accessible_name
  17092. Ensures the `Locator` points to an element with a given
  17093. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  17094. **Usage**
  17095. ```py
  17096. locator = page.get_by_test_id(\"save-button\")
  17097. expect(locator).to_have_accessible_name(\"Save to disk\")
  17098. ```
  17099. Parameters
  17100. ----------
  17101. name : Union[Pattern[str], str]
  17102. Expected accessible name.
  17103. ignore_case : Union[bool, None]
  17104. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17105. expression flag if specified.
  17106. timeout : Union[float, None]
  17107. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17108. """
  17109. __tracebackhide__ = True
  17110. return mapping.from_maybe_impl(
  17111. self._sync(
  17112. self._impl_obj.to_have_accessible_name(
  17113. name=name, ignoreCase=ignore_case, timeout=timeout
  17114. )
  17115. )
  17116. )
  17117. def not_to_have_accessible_name(
  17118. self,
  17119. name: typing.Union[str, typing.Pattern[str]],
  17120. *,
  17121. ignore_case: typing.Optional[bool] = None,
  17122. timeout: typing.Optional[float] = None,
  17123. ) -> None:
  17124. """LocatorAssertions.not_to_have_accessible_name
  17125. The opposite of `locator_assertions.to_have_accessible_name()`.
  17126. Parameters
  17127. ----------
  17128. name : Union[Pattern[str], str]
  17129. Expected accessible name.
  17130. ignore_case : Union[bool, None]
  17131. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17132. expression flag if specified.
  17133. timeout : Union[float, None]
  17134. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17135. """
  17136. __tracebackhide__ = True
  17137. return mapping.from_maybe_impl(
  17138. self._sync(
  17139. self._impl_obj.not_to_have_accessible_name(
  17140. name=name, ignoreCase=ignore_case, timeout=timeout
  17141. )
  17142. )
  17143. )
  17144. def to_have_role(
  17145. self,
  17146. role: Literal[
  17147. "alert",
  17148. "alertdialog",
  17149. "application",
  17150. "article",
  17151. "banner",
  17152. "blockquote",
  17153. "button",
  17154. "caption",
  17155. "cell",
  17156. "checkbox",
  17157. "code",
  17158. "columnheader",
  17159. "combobox",
  17160. "complementary",
  17161. "contentinfo",
  17162. "definition",
  17163. "deletion",
  17164. "dialog",
  17165. "directory",
  17166. "document",
  17167. "emphasis",
  17168. "feed",
  17169. "figure",
  17170. "form",
  17171. "generic",
  17172. "grid",
  17173. "gridcell",
  17174. "group",
  17175. "heading",
  17176. "img",
  17177. "insertion",
  17178. "link",
  17179. "list",
  17180. "listbox",
  17181. "listitem",
  17182. "log",
  17183. "main",
  17184. "marquee",
  17185. "math",
  17186. "menu",
  17187. "menubar",
  17188. "menuitem",
  17189. "menuitemcheckbox",
  17190. "menuitemradio",
  17191. "meter",
  17192. "navigation",
  17193. "none",
  17194. "note",
  17195. "option",
  17196. "paragraph",
  17197. "presentation",
  17198. "progressbar",
  17199. "radio",
  17200. "radiogroup",
  17201. "region",
  17202. "row",
  17203. "rowgroup",
  17204. "rowheader",
  17205. "scrollbar",
  17206. "search",
  17207. "searchbox",
  17208. "separator",
  17209. "slider",
  17210. "spinbutton",
  17211. "status",
  17212. "strong",
  17213. "subscript",
  17214. "superscript",
  17215. "switch",
  17216. "tab",
  17217. "table",
  17218. "tablist",
  17219. "tabpanel",
  17220. "term",
  17221. "textbox",
  17222. "time",
  17223. "timer",
  17224. "toolbar",
  17225. "tooltip",
  17226. "tree",
  17227. "treegrid",
  17228. "treeitem",
  17229. ],
  17230. *,
  17231. timeout: typing.Optional[float] = None,
  17232. ) -> None:
  17233. """LocatorAssertions.to_have_role
  17234. Ensures the `Locator` points to an element with a given [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles).
  17235. Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass
  17236. role `\"checkbox\"` on an element with a subclass role `\"switch\"` will fail.
  17237. **Usage**
  17238. ```py
  17239. locator = page.get_by_test_id(\"save-button\")
  17240. expect(locator).to_have_role(\"button\")
  17241. ```
  17242. Parameters
  17243. ----------
  17244. role : Union["alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"]
  17245. Required aria role.
  17246. timeout : Union[float, None]
  17247. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17248. """
  17249. __tracebackhide__ = True
  17250. return mapping.from_maybe_impl(
  17251. self._sync(self._impl_obj.to_have_role(role=role, timeout=timeout))
  17252. )
  17253. def to_have_accessible_error_message(
  17254. self,
  17255. error_message: typing.Union[str, typing.Pattern[str]],
  17256. *,
  17257. ignore_case: typing.Optional[bool] = None,
  17258. timeout: typing.Optional[float] = None,
  17259. ) -> None:
  17260. """LocatorAssertions.to_have_accessible_error_message
  17261. Ensures the `Locator` points to an element with a given
  17262. [aria errormessage](https://w3c.github.io/aria/#aria-errormessage).
  17263. **Usage**
  17264. ```py
  17265. locator = page.get_by_test_id(\"username-input\")
  17266. expect(locator).to_have_accessible_error_message(\"Username is required.\")
  17267. ```
  17268. Parameters
  17269. ----------
  17270. error_message : Union[Pattern[str], str]
  17271. Expected accessible error message.
  17272. ignore_case : Union[bool, None]
  17273. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17274. expression flag if specified.
  17275. timeout : Union[float, None]
  17276. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17277. """
  17278. __tracebackhide__ = True
  17279. return mapping.from_maybe_impl(
  17280. self._sync(
  17281. self._impl_obj.to_have_accessible_error_message(
  17282. errorMessage=error_message, ignoreCase=ignore_case, timeout=timeout
  17283. )
  17284. )
  17285. )
  17286. def not_to_have_accessible_error_message(
  17287. self,
  17288. error_message: typing.Union[str, typing.Pattern[str]],
  17289. *,
  17290. ignore_case: typing.Optional[bool] = None,
  17291. timeout: typing.Optional[float] = None,
  17292. ) -> None:
  17293. """LocatorAssertions.not_to_have_accessible_error_message
  17294. The opposite of `locator_assertions.to_have_accessible_error_message()`.
  17295. Parameters
  17296. ----------
  17297. error_message : Union[Pattern[str], str]
  17298. Expected accessible error message.
  17299. ignore_case : Union[bool, None]
  17300. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17301. expression flag if specified.
  17302. timeout : Union[float, None]
  17303. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17304. """
  17305. __tracebackhide__ = True
  17306. return mapping.from_maybe_impl(
  17307. self._sync(
  17308. self._impl_obj.not_to_have_accessible_error_message(
  17309. errorMessage=error_message, ignoreCase=ignore_case, timeout=timeout
  17310. )
  17311. )
  17312. )
  17313. def not_to_have_role(
  17314. self,
  17315. role: Literal[
  17316. "alert",
  17317. "alertdialog",
  17318. "application",
  17319. "article",
  17320. "banner",
  17321. "blockquote",
  17322. "button",
  17323. "caption",
  17324. "cell",
  17325. "checkbox",
  17326. "code",
  17327. "columnheader",
  17328. "combobox",
  17329. "complementary",
  17330. "contentinfo",
  17331. "definition",
  17332. "deletion",
  17333. "dialog",
  17334. "directory",
  17335. "document",
  17336. "emphasis",
  17337. "feed",
  17338. "figure",
  17339. "form",
  17340. "generic",
  17341. "grid",
  17342. "gridcell",
  17343. "group",
  17344. "heading",
  17345. "img",
  17346. "insertion",
  17347. "link",
  17348. "list",
  17349. "listbox",
  17350. "listitem",
  17351. "log",
  17352. "main",
  17353. "marquee",
  17354. "math",
  17355. "menu",
  17356. "menubar",
  17357. "menuitem",
  17358. "menuitemcheckbox",
  17359. "menuitemradio",
  17360. "meter",
  17361. "navigation",
  17362. "none",
  17363. "note",
  17364. "option",
  17365. "paragraph",
  17366. "presentation",
  17367. "progressbar",
  17368. "radio",
  17369. "radiogroup",
  17370. "region",
  17371. "row",
  17372. "rowgroup",
  17373. "rowheader",
  17374. "scrollbar",
  17375. "search",
  17376. "searchbox",
  17377. "separator",
  17378. "slider",
  17379. "spinbutton",
  17380. "status",
  17381. "strong",
  17382. "subscript",
  17383. "superscript",
  17384. "switch",
  17385. "tab",
  17386. "table",
  17387. "tablist",
  17388. "tabpanel",
  17389. "term",
  17390. "textbox",
  17391. "time",
  17392. "timer",
  17393. "toolbar",
  17394. "tooltip",
  17395. "tree",
  17396. "treegrid",
  17397. "treeitem",
  17398. ],
  17399. *,
  17400. timeout: typing.Optional[float] = None,
  17401. ) -> None:
  17402. """LocatorAssertions.not_to_have_role
  17403. The opposite of `locator_assertions.to_have_role()`.
  17404. Parameters
  17405. ----------
  17406. role : Union["alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "meter", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"]
  17407. Required aria role.
  17408. timeout : Union[float, None]
  17409. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17410. """
  17411. __tracebackhide__ = True
  17412. return mapping.from_maybe_impl(
  17413. self._sync(self._impl_obj.not_to_have_role(role=role, timeout=timeout))
  17414. )
  17415. def to_match_aria_snapshot(
  17416. self, expected: str, *, timeout: typing.Optional[float] = None
  17417. ) -> None:
  17418. """LocatorAssertions.to_match_aria_snapshot
  17419. Asserts that the target element matches the given [accessibility snapshot](https://playwright.dev/python/docs/aria-snapshots).
  17420. **Usage**
  17421. ```py
  17422. page.goto(\"https://demo.playwright.dev/todomvc/\")
  17423. expect(page.locator('body')).to_match_aria_snapshot('''
  17424. - heading \"todos\"
  17425. - textbox \"What needs to be done?\"
  17426. ''')
  17427. ```
  17428. Parameters
  17429. ----------
  17430. expected : str
  17431. timeout : Union[float, None]
  17432. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17433. """
  17434. __tracebackhide__ = True
  17435. return mapping.from_maybe_impl(
  17436. self._sync(
  17437. self._impl_obj.to_match_aria_snapshot(
  17438. expected=expected, timeout=timeout
  17439. )
  17440. )
  17441. )
  17442. def not_to_match_aria_snapshot(
  17443. self, expected: str, *, timeout: typing.Optional[float] = None
  17444. ) -> None:
  17445. """LocatorAssertions.not_to_match_aria_snapshot
  17446. The opposite of `locator_assertions.to_match_aria_snapshot()`.
  17447. Parameters
  17448. ----------
  17449. expected : str
  17450. timeout : Union[float, None]
  17451. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17452. """
  17453. __tracebackhide__ = True
  17454. return mapping.from_maybe_impl(
  17455. self._sync(
  17456. self._impl_obj.not_to_match_aria_snapshot(
  17457. expected=expected, timeout=timeout
  17458. )
  17459. )
  17460. )
  17461. mapping.register(LocatorAssertionsImpl, LocatorAssertions)
  17462. class APIResponseAssertions(SyncBase):
  17463. def to_be_ok(self) -> None:
  17464. """APIResponseAssertions.to_be_ok
  17465. Ensures the response status code is within `200..299` range.
  17466. **Usage**
  17467. ```py
  17468. import re
  17469. from playwright.sync_api import expect
  17470. # ...
  17471. expect(response).to_be_ok()
  17472. ```
  17473. """
  17474. __tracebackhide__ = True
  17475. return mapping.from_maybe_impl(self._sync(self._impl_obj.to_be_ok()))
  17476. def not_to_be_ok(self) -> None:
  17477. """APIResponseAssertions.not_to_be_ok
  17478. The opposite of `a_pi_response_assertions.to_be_ok()`.
  17479. """
  17480. __tracebackhide__ = True
  17481. return mapping.from_maybe_impl(self._sync(self._impl_obj.not_to_be_ok()))
  17482. mapping.register(APIResponseAssertionsImpl, APIResponseAssertions)