_generated.py 907 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297
  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. BrowserBindResult,
  20. ClientCertificate,
  21. Cookie,
  22. DebuggerLocation,
  23. DebuggerPausedDetails,
  24. DropPayload,
  25. FilePayload,
  26. FloatRect,
  27. Geolocation,
  28. HttpCredentials,
  29. NameValue,
  30. PdfMargins,
  31. Position,
  32. ProxySettings,
  33. RemoteAddr,
  34. RequestSizes,
  35. ResourceTiming,
  36. ScreencastFrame,
  37. SecurityDetails,
  38. SetCookieParam,
  39. SourceLocation,
  40. StorageState,
  41. TracingGroupLocation,
  42. ViewportSize,
  43. WebErrorLocation,
  44. )
  45. from playwright._impl._assertions import (
  46. APIResponseAssertions as APIResponseAssertionsImpl,
  47. )
  48. from playwright._impl._assertions import LocatorAssertions as LocatorAssertionsImpl
  49. from playwright._impl._assertions import PageAssertions as PageAssertionsImpl
  50. from playwright._impl._async_base import (
  51. AsyncBase,
  52. AsyncContextManager,
  53. AsyncEventContextManager,
  54. mapping,
  55. )
  56. from playwright._impl._browser import Browser as BrowserImpl
  57. from playwright._impl._browser_context import BrowserContext as BrowserContextImpl
  58. from playwright._impl._browser_type import BrowserType as BrowserTypeImpl
  59. from playwright._impl._cdp_session import CDPSession as CDPSessionImpl
  60. from playwright._impl._clock import Clock as ClockImpl
  61. from playwright._impl._console_message import ConsoleMessage as ConsoleMessageImpl
  62. from playwright._impl._debugger import Debugger as DebuggerImpl
  63. from playwright._impl._dialog import Dialog as DialogImpl
  64. from playwright._impl._disposable import Disposable as DisposableImpl
  65. from playwright._impl._download import Download as DownloadImpl
  66. from playwright._impl._element_handle import ElementHandle as ElementHandleImpl
  67. from playwright._impl._errors import Error
  68. from playwright._impl._fetch import APIRequest as APIRequestImpl
  69. from playwright._impl._fetch import APIRequestContext as APIRequestContextImpl
  70. from playwright._impl._fetch import APIResponse as APIResponseImpl
  71. from playwright._impl._file_chooser import FileChooser as FileChooserImpl
  72. from playwright._impl._form_data import FormData
  73. from playwright._impl._frame import Frame as FrameImpl
  74. from playwright._impl._helper import to_milliseconds
  75. from playwright._impl._input import Keyboard as KeyboardImpl
  76. from playwright._impl._input import Mouse as MouseImpl
  77. from playwright._impl._input import Touchscreen as TouchscreenImpl
  78. from playwright._impl._js_handle import JSHandle as JSHandleImpl
  79. from playwright._impl._locator import FrameLocator as FrameLocatorImpl
  80. from playwright._impl._locator import Locator as LocatorImpl
  81. from playwright._impl._network import Request as RequestImpl
  82. from playwright._impl._network import Response as ResponseImpl
  83. from playwright._impl._network import Route as RouteImpl
  84. from playwright._impl._network import WebSocket as WebSocketImpl
  85. from playwright._impl._network import WebSocketRoute as WebSocketRouteImpl
  86. from playwright._impl._page import Page as PageImpl
  87. from playwright._impl._page import Worker as WorkerImpl
  88. from playwright._impl._playwright import Playwright as PlaywrightImpl
  89. from playwright._impl._screencast import Screencast as ScreencastImpl
  90. from playwright._impl._selectors import Selectors as SelectorsImpl
  91. from playwright._impl._tracing import Tracing as TracingImpl
  92. from playwright._impl._video import Video as VideoImpl
  93. from playwright._impl._web_error import WebError as WebErrorImpl
  94. class Request(AsyncBase):
  95. @property
  96. def url(self) -> str:
  97. """Request.url
  98. URL of the request.
  99. Returns
  100. -------
  101. str
  102. """
  103. return mapping.from_maybe_impl(self._impl_obj.url)
  104. @property
  105. def resource_type(self) -> str:
  106. """Request.resource_type
  107. Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the
  108. following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,
  109. `eventsource`, `websocket`, `manifest`, `other`.
  110. Returns
  111. -------
  112. str
  113. """
  114. return mapping.from_maybe_impl(self._impl_obj.resource_type)
  115. @property
  116. def service_worker(self) -> typing.Optional["Worker"]:
  117. """Request.service_worker
  118. The Service `Worker` that is performing the request.
  119. **Details**
  120. This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.
  121. Requests originated in a Service Worker do not have a `request.frame()` available.
  122. Returns
  123. -------
  124. Union[Worker, None]
  125. """
  126. return mapping.from_impl_nullable(self._impl_obj.service_worker)
  127. @property
  128. def method(self) -> str:
  129. """Request.method
  130. Request's method (GET, POST, etc.)
  131. Returns
  132. -------
  133. str
  134. """
  135. return mapping.from_maybe_impl(self._impl_obj.method)
  136. @property
  137. def post_data(self) -> typing.Optional[str]:
  138. """Request.post_data
  139. Request's post body, if any.
  140. Returns
  141. -------
  142. Union[str, None]
  143. """
  144. return mapping.from_maybe_impl(self._impl_obj.post_data)
  145. @property
  146. def post_data_json(self) -> typing.Optional[typing.Any]:
  147. """Request.post_data_json
  148. Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.
  149. When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.
  150. Otherwise it will be parsed as JSON.
  151. Returns
  152. -------
  153. Union[Any, None]
  154. """
  155. return mapping.from_maybe_impl(self._impl_obj.post_data_json)
  156. @property
  157. def post_data_buffer(self) -> typing.Optional[bytes]:
  158. """Request.post_data_buffer
  159. Request's post body in a binary form, if any.
  160. Returns
  161. -------
  162. Union[bytes, None]
  163. """
  164. return mapping.from_maybe_impl(self._impl_obj.post_data_buffer)
  165. @property
  166. def existing_response(self) -> typing.Optional["Response"]:
  167. """Request.existing_response
  168. Returns the `Response` object if the response has already been received, `null` otherwise.
  169. Unlike `request.response()`, this method does not wait for the response to arrive. It returns immediately
  170. with the response object if the response has been received, or `null` if the response has not been received yet.
  171. Returns
  172. -------
  173. Union[Response, None]
  174. """
  175. return mapping.from_impl_nullable(self._impl_obj.existing_response)
  176. @property
  177. def frame(self) -> "Frame":
  178. """Request.frame
  179. Returns the `Frame` that initiated this request.
  180. **Usage**
  181. ```py
  182. frame_url = request.frame.url
  183. ```
  184. **Details**
  185. Note that in some cases the frame is not available, and this method will throw.
  186. - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.
  187. - When navigation request is issued before the corresponding frame is created. You can use
  188. `request.is_navigation_request()` to check that.
  189. Here is an example that handles all the cases:
  190. Returns
  191. -------
  192. Frame
  193. """
  194. return mapping.from_impl(self._impl_obj.frame)
  195. @property
  196. def redirected_from(self) -> typing.Optional["Request"]:
  197. """Request.redirected_from
  198. Request that was redirected by the server to this one, if any.
  199. When the server responds with a redirect, Playwright creates a new `Request` object. The two requests are connected
  200. by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
  201. construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
  202. **Usage**
  203. For example, if the website `http://example.com` redirects to `https://example.com`:
  204. ```py
  205. response = await page.goto(\"http://example.com\")
  206. print(response.request.redirected_from.url) # \"http://example.com\"
  207. ```
  208. If the website `https://google.com` has no redirects:
  209. ```py
  210. response = await page.goto(\"https://google.com\")
  211. print(response.request.redirected_from) # None
  212. ```
  213. Returns
  214. -------
  215. Union[Request, None]
  216. """
  217. return mapping.from_impl_nullable(self._impl_obj.redirected_from)
  218. @property
  219. def redirected_to(self) -> typing.Optional["Request"]:
  220. """Request.redirected_to
  221. New request issued by the browser if the server responded with redirect.
  222. **Usage**
  223. This method is the opposite of `request.redirected_from()`:
  224. ```py
  225. assert request.redirected_from.redirected_to == request
  226. ```
  227. Returns
  228. -------
  229. Union[Request, None]
  230. """
  231. return mapping.from_impl_nullable(self._impl_obj.redirected_to)
  232. @property
  233. def failure(self) -> typing.Optional[str]:
  234. """Request.failure
  235. The method returns `null` unless this request has failed, as reported by `requestfailed` event.
  236. **Usage**
  237. Example of logging of all the failed requests:
  238. ```py
  239. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure))
  240. ```
  241. Returns
  242. -------
  243. Union[str, None]
  244. """
  245. return mapping.from_maybe_impl(self._impl_obj.failure)
  246. @property
  247. def timing(self) -> ResourceTiming:
  248. """Request.timing
  249. Returns resource timing information for given request. Most of the timing values become available upon the
  250. response, `responseEnd` becomes available when request finishes. Find more information at
  251. [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
  252. **Usage**
  253. ```py
  254. async with page.expect_event(\"requestfinished\") as request_info:
  255. await page.goto(\"http://example.com\")
  256. request = await request_info.value
  257. print(request.timing)
  258. ```
  259. Returns
  260. -------
  261. {startTime: float, domainLookupStart: float, domainLookupEnd: float, connectStart: float, secureConnectionStart: float, connectEnd: float, requestStart: float, responseStart: float, responseEnd: float}
  262. """
  263. return mapping.from_impl(self._impl_obj.timing)
  264. @property
  265. def headers(self) -> typing.Dict[str, str]:
  266. """Request.headers
  267. An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return
  268. security-related headers, including cookie-related ones. You can use `request.all_headers()` for complete
  269. list of headers that include `cookie` information.
  270. Returns
  271. -------
  272. Dict[str, str]
  273. """
  274. return mapping.from_maybe_impl(self._impl_obj.headers)
  275. async def sizes(self) -> RequestSizes:
  276. """Request.sizes
  277. Returns resource size information for given request.
  278. Returns
  279. -------
  280. {requestBodySize: int, requestHeadersSize: int, responseBodySize: int, responseHeadersSize: int}
  281. """
  282. return mapping.from_impl(await self._impl_obj.sizes())
  283. async def response(self) -> typing.Optional["Response"]:
  284. """Request.response
  285. Returns the matching `Response` object, or `null` if the response was not received due to error.
  286. Returns
  287. -------
  288. Union[Response, None]
  289. """
  290. return mapping.from_impl_nullable(await self._impl_obj.response())
  291. def is_navigation_request(self) -> bool:
  292. """Request.is_navigation_request
  293. Whether this request is driving frame's navigation.
  294. Some navigation requests are issued before the corresponding frame is created, and therefore do not have
  295. `request.frame()` available.
  296. Returns
  297. -------
  298. bool
  299. """
  300. return mapping.from_maybe_impl(self._impl_obj.is_navigation_request())
  301. async def all_headers(self) -> typing.Dict[str, str]:
  302. """Request.all_headers
  303. An object with all the request HTTP headers associated with this request. The header names are lower-cased.
  304. Returns
  305. -------
  306. Dict[str, str]
  307. """
  308. return mapping.from_maybe_impl(await self._impl_obj.all_headers())
  309. async def headers_array(self) -> typing.List[NameValue]:
  310. """Request.headers_array
  311. An array with all the request HTTP headers associated with this request. Unlike `request.all_headers()`,
  312. header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
  313. times.
  314. Returns
  315. -------
  316. List[{name: str, value: str}]
  317. """
  318. return mapping.from_impl_list(await self._impl_obj.headers_array())
  319. async def header_value(self, name: str) -> typing.Optional[str]:
  320. """Request.header_value
  321. Returns the value of the header matching the name. The name is case-insensitive.
  322. Parameters
  323. ----------
  324. name : str
  325. Name of the header.
  326. Returns
  327. -------
  328. Union[str, None]
  329. """
  330. return mapping.from_maybe_impl(await self._impl_obj.header_value(name=name))
  331. mapping.register(RequestImpl, Request)
  332. class Response(AsyncBase):
  333. @property
  334. def url(self) -> str:
  335. """Response.url
  336. Contains the URL of the response.
  337. Returns
  338. -------
  339. str
  340. """
  341. return mapping.from_maybe_impl(self._impl_obj.url)
  342. @property
  343. def ok(self) -> bool:
  344. """Response.ok
  345. Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
  346. Returns
  347. -------
  348. bool
  349. """
  350. return mapping.from_maybe_impl(self._impl_obj.ok)
  351. @property
  352. def status(self) -> int:
  353. """Response.status
  354. Contains the status code of the response (e.g., 200 for a success).
  355. Returns
  356. -------
  357. int
  358. """
  359. return mapping.from_maybe_impl(self._impl_obj.status)
  360. @property
  361. def status_text(self) -> str:
  362. """Response.status_text
  363. Contains the status text of the response (e.g. usually an \"OK\" for a success).
  364. Returns
  365. -------
  366. str
  367. """
  368. return mapping.from_maybe_impl(self._impl_obj.status_text)
  369. @property
  370. def headers(self) -> typing.Dict[str, str]:
  371. """Response.headers
  372. An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return
  373. security-related headers, including cookie-related ones. You can use `response.all_headers()` for complete
  374. list of headers that include `cookie` information.
  375. Returns
  376. -------
  377. Dict[str, str]
  378. """
  379. return mapping.from_maybe_impl(self._impl_obj.headers)
  380. @property
  381. def from_service_worker(self) -> bool:
  382. """Response.from_service_worker
  383. Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via
  384. [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).
  385. Returns
  386. -------
  387. bool
  388. """
  389. return mapping.from_maybe_impl(self._impl_obj.from_service_worker)
  390. @property
  391. def request(self) -> "Request":
  392. """Response.request
  393. Returns the matching `Request` object.
  394. Returns
  395. -------
  396. Request
  397. """
  398. return mapping.from_impl(self._impl_obj.request)
  399. @property
  400. def frame(self) -> "Frame":
  401. """Response.frame
  402. Returns the `Frame` that initiated this response.
  403. Returns
  404. -------
  405. Frame
  406. """
  407. return mapping.from_impl(self._impl_obj.frame)
  408. async def all_headers(self) -> typing.Dict[str, str]:
  409. """Response.all_headers
  410. An object with all the response HTTP headers associated with this response.
  411. Returns
  412. -------
  413. Dict[str, str]
  414. """
  415. return mapping.from_maybe_impl(await self._impl_obj.all_headers())
  416. async def headers_array(self) -> typing.List[NameValue]:
  417. """Response.headers_array
  418. An array with all the request HTTP headers associated with this response. Unlike `response.all_headers()`,
  419. header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
  420. times.
  421. Returns
  422. -------
  423. List[{name: str, value: str}]
  424. """
  425. return mapping.from_impl_list(await self._impl_obj.headers_array())
  426. async def header_value(self, name: str) -> typing.Optional[str]:
  427. """Response.header_value
  428. Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same
  429. name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\\n` separator is
  430. used. If no headers are found, `null` is returned.
  431. Parameters
  432. ----------
  433. name : str
  434. Name of the header.
  435. Returns
  436. -------
  437. Union[str, None]
  438. """
  439. return mapping.from_maybe_impl(await self._impl_obj.header_value(name=name))
  440. async def header_values(self, name: str) -> typing.List[str]:
  441. """Response.header_values
  442. Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.
  443. Parameters
  444. ----------
  445. name : str
  446. Name of the header.
  447. Returns
  448. -------
  449. List[str]
  450. """
  451. return mapping.from_maybe_impl(await self._impl_obj.header_values(name=name))
  452. async def server_addr(self) -> typing.Optional[RemoteAddr]:
  453. """Response.server_addr
  454. Returns the IP address and port of the server.
  455. Returns
  456. -------
  457. Union[{ipAddress: str, port: int}, None]
  458. """
  459. return mapping.from_impl_nullable(await self._impl_obj.server_addr())
  460. async def security_details(self) -> typing.Optional[SecurityDetails]:
  461. """Response.security_details
  462. Returns SSL and other security information.
  463. Returns
  464. -------
  465. Union[{issuer: Union[str, None], protocol: Union[str, None], subjectName: Union[str, None], validFrom: Union[float, None], validTo: Union[float, None]}, None]
  466. """
  467. return mapping.from_impl_nullable(await self._impl_obj.security_details())
  468. async def http_version(self) -> str:
  469. """Response.http_version
  470. Returns the http version used by the response.
  471. Returns
  472. -------
  473. str
  474. """
  475. return mapping.from_maybe_impl(await self._impl_obj.http_version())
  476. async def finished(self) -> None:
  477. """Response.finished
  478. Waits for this response to finish, returns always `null`.
  479. """
  480. return mapping.from_maybe_impl(await self._impl_obj.finished())
  481. async def body(self) -> bytes:
  482. """Response.body
  483. Returns the buffer with response body.
  484. Returns
  485. -------
  486. bytes
  487. """
  488. return mapping.from_maybe_impl(await self._impl_obj.body())
  489. async def text(self) -> str:
  490. """Response.text
  491. Returns the text representation of response body.
  492. Returns
  493. -------
  494. str
  495. """
  496. return mapping.from_maybe_impl(await self._impl_obj.text())
  497. async def json(self) -> typing.Any:
  498. """Response.json
  499. Returns the JSON representation of response body.
  500. This method will throw if the response body is not parsable via `JSON.parse`.
  501. Returns
  502. -------
  503. Any
  504. """
  505. return mapping.from_maybe_impl(await self._impl_obj.json())
  506. mapping.register(ResponseImpl, Response)
  507. class Route(AsyncBase):
  508. @property
  509. def request(self) -> "Request":
  510. """Route.request
  511. A request to be routed.
  512. Returns
  513. -------
  514. Request
  515. """
  516. return mapping.from_impl(self._impl_obj.request)
  517. async def abort(self, error_code: typing.Optional[str] = None) -> None:
  518. """Route.abort
  519. Aborts the route's request.
  520. Parameters
  521. ----------
  522. error_code : Union[str, None]
  523. Optional error code. Defaults to `failed`, could be one of the following:
  524. - `'aborted'` - An operation was aborted (due to user action)
  525. - `'accessdenied'` - Permission to access a resource, other than the network, was denied
  526. - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the
  527. specified host or network.
  528. - `'blockedbyclient'` - The client chose to block the request.
  529. - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are
  530. not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
  531. - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
  532. - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
  533. - `'connectionfailed'` - A connection attempt failed.
  534. - `'connectionrefused'` - A connection attempt was refused.
  535. - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
  536. - `'internetdisconnected'` - The Internet connection has been lost.
  537. - `'namenotresolved'` - The host name could not be resolved.
  538. - `'timedout'` - An operation timed out.
  539. - `'failed'` - A generic failure occurred.
  540. """
  541. return mapping.from_maybe_impl(await self._impl_obj.abort(errorCode=error_code))
  542. async def fulfill(
  543. self,
  544. *,
  545. status: typing.Optional[int] = None,
  546. headers: typing.Optional[typing.Dict[str, str]] = None,
  547. body: typing.Optional[typing.Union[str, bytes]] = None,
  548. json: typing.Optional[typing.Any] = None,
  549. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  550. content_type: typing.Optional[str] = None,
  551. response: typing.Optional["APIResponse"] = None,
  552. ) -> None:
  553. """Route.fulfill
  554. Fulfills route's request with given response.
  555. **Usage**
  556. An example of fulfilling all requests with 404 responses:
  557. ```py
  558. await page.route(\"**/*\", lambda route: route.fulfill(
  559. status=404,
  560. content_type=\"text/plain\",
  561. body=\"not found!\"))
  562. ```
  563. An example of serving static file:
  564. ```py
  565. await page.route(\"**/xhr_endpoint\", lambda route: route.fulfill(path=\"mock_data.json\"))
  566. ```
  567. Parameters
  568. ----------
  569. status : Union[int, None]
  570. Response status code, defaults to `200`.
  571. headers : Union[Dict[str, str], None]
  572. Response headers. Header values will be converted to a string.
  573. body : Union[bytes, str, None]
  574. Response body.
  575. json : Union[Any, None]
  576. JSON response. This method will set the content type to `application/json` if not set.
  577. path : Union[pathlib.Path, str, None]
  578. File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,
  579. then it is resolved relative to the current working directory.
  580. content_type : Union[str, None]
  581. If set, equals to setting `Content-Type` response header.
  582. response : Union[APIResponse, None]
  583. `APIResponse` to fulfill route's request with. Individual fields of the response (such as headers) can be
  584. overridden using fulfill options.
  585. """
  586. return mapping.from_maybe_impl(
  587. await self._impl_obj.fulfill(
  588. status=status,
  589. headers=mapping.to_impl(headers),
  590. body=body,
  591. json=mapping.to_impl(json),
  592. path=path,
  593. contentType=content_type,
  594. response=response._impl_obj if response else None,
  595. )
  596. )
  597. async def fetch(
  598. self,
  599. *,
  600. url: typing.Optional[str] = None,
  601. method: typing.Optional[str] = None,
  602. headers: typing.Optional[typing.Dict[str, str]] = None,
  603. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  604. max_redirects: typing.Optional[int] = None,
  605. max_retries: typing.Optional[int] = None,
  606. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  607. ) -> "APIResponse":
  608. """Route.fetch
  609. Performs the request and fetches result without fulfilling it, so that the response could be modified and then
  610. fulfilled.
  611. **Usage**
  612. ```py
  613. async def handle(route):
  614. response = await route.fetch()
  615. json = await response.json()
  616. json[\"message\"][\"big_red_dog\"] = []
  617. await route.fulfill(response=response, json=json)
  618. await page.route(\"https://dog.ceo/api/breeds/list/all\", handle)
  619. ```
  620. **Details**
  621. Note that `headers` option will apply to the fetched request as well as any redirects initiated by it. If you want
  622. to only apply `headers` to the original request, but not to redirects, look into `route.continue_()`
  623. instead.
  624. Parameters
  625. ----------
  626. url : Union[str, None]
  627. If set changes the request URL. New URL must have same protocol as original one.
  628. method : Union[str, None]
  629. If set changes the request method (e.g. GET or POST).
  630. headers : Union[Dict[str, str], None]
  631. If set changes the request HTTP headers. Header values will be converted to a string.
  632. post_data : Union[Any, bytes, str, None]
  633. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  634. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  635. header will be set to `application/octet-stream` if not explicitly set.
  636. max_redirects : Union[int, None]
  637. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  638. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  639. max_retries : Union[int, None]
  640. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  641. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  642. timeout : Union[float, None]
  643. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  644. Returns
  645. -------
  646. APIResponse
  647. """
  648. return mapping.from_impl(
  649. await self._impl_obj.fetch(
  650. url=url,
  651. method=method,
  652. headers=mapping.to_impl(headers),
  653. postData=mapping.to_impl(post_data),
  654. maxRedirects=max_redirects,
  655. maxRetries=max_retries,
  656. timeout=to_milliseconds(timeout),
  657. )
  658. )
  659. async def fallback(
  660. self,
  661. *,
  662. url: typing.Optional[str] = None,
  663. method: typing.Optional[str] = None,
  664. headers: typing.Optional[typing.Dict[str, str]] = None,
  665. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  666. ) -> None:
  667. """Route.fallback
  668. Continues route's request with optional overrides. The method is similar to `route.continue_()` with the
  669. difference that other matching handlers will be invoked before sending the request.
  670. **Usage**
  671. When several routes match the given pattern, they run in the order opposite to their registration. That way the
  672. last registered route can always override all the previous ones. In the example below, request will be handled by
  673. the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
  674. registered route.
  675. ```py
  676. await page.route(\"**/*\", lambda route: route.abort()) # Runs last.
  677. await page.route(\"**/*\", lambda route: route.fallback()) # Runs second.
  678. await page.route(\"**/*\", lambda route: route.fallback()) # Runs first.
  679. ```
  680. Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for
  681. example API calls vs page resources or GET requests vs POST requests as in the example below.
  682. ```py
  683. # Handle GET requests.
  684. async def handle_get(route):
  685. if route.request.method != \"GET\":
  686. await route.fallback()
  687. return
  688. # Handling GET only.
  689. # ...
  690. # Handle POST requests.
  691. async def handle_post(route):
  692. if route.request.method != \"POST\":
  693. await route.fallback()
  694. return
  695. # Handling POST only.
  696. # ...
  697. await page.route(\"**/*\", handle_get)
  698. await page.route(\"**/*\", handle_post)
  699. ```
  700. One can also modify request while falling back to the subsequent handler, that way intermediate route handler can
  701. modify url, method, headers and postData of the request.
  702. ```py
  703. async def handle(route, request):
  704. # override headers
  705. headers = {
  706. **request.headers,
  707. \"foo\": \"foo-value\", # set \"foo\" header
  708. \"bar\": None # remove \"bar\" header
  709. }
  710. await route.fallback(headers=headers)
  711. await page.route(\"**/*\", handle)
  712. ```
  713. Use `route.continue_()` to immediately send the request to the network, other matching handlers won't be
  714. invoked in that case.
  715. Parameters
  716. ----------
  717. url : Union[str, None]
  718. If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the
  719. route matching, all the routes are matched using the original request URL.
  720. method : Union[str, None]
  721. If set changes the request method (e.g. GET or POST).
  722. headers : Union[Dict[str, str], None]
  723. If set changes the request HTTP headers. Header values will be converted to a string.
  724. post_data : Union[Any, bytes, str, None]
  725. If set changes the post data of request.
  726. """
  727. return mapping.from_maybe_impl(
  728. await self._impl_obj.fallback(
  729. url=url,
  730. method=method,
  731. headers=mapping.to_impl(headers),
  732. postData=mapping.to_impl(post_data),
  733. )
  734. )
  735. async def continue_(
  736. self,
  737. *,
  738. url: typing.Optional[str] = None,
  739. method: typing.Optional[str] = None,
  740. headers: typing.Optional[typing.Dict[str, str]] = None,
  741. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  742. ) -> None:
  743. """Route.continue_
  744. Sends route's request to the network with optional overrides.
  745. **Usage**
  746. ```py
  747. async def handle(route, request):
  748. # override headers
  749. headers = {
  750. **request.headers,
  751. \"foo\": \"foo-value\", # set \"foo\" header
  752. \"bar\": None # remove \"bar\" header
  753. }
  754. await route.continue_(headers=headers)
  755. await page.route(\"**/*\", handle)
  756. ```
  757. **Details**
  758. The `headers` option applies to both the routed request and any redirects it initiates. However, `url`, `method`,
  759. and `postData` only apply to the original request and are not carried over to redirected requests.
  760. `route.continue_()` will immediately send the request to the network, other matching handlers won't be
  761. invoked. Use `route.fallback()` If you want next matching handler in the chain to be invoked.
  762. **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,
  763. `Content-Length` and others, see
  764. [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an
  765. override is provided for a forbidden header, it will be ignored and the original request header will be used.
  766. To set custom cookies, use `browser_context.add_cookies()`.
  767. Parameters
  768. ----------
  769. url : Union[str, None]
  770. If set changes the request URL. New URL must have same protocol as original one.
  771. method : Union[str, None]
  772. If set changes the request method (e.g. GET or POST).
  773. headers : Union[Dict[str, str], None]
  774. If set changes the request HTTP headers. Header values will be converted to a string.
  775. post_data : Union[Any, bytes, str, None]
  776. If set changes the post data of request.
  777. """
  778. return mapping.from_maybe_impl(
  779. await self._impl_obj.continue_(
  780. url=url,
  781. method=method,
  782. headers=mapping.to_impl(headers),
  783. postData=mapping.to_impl(post_data),
  784. )
  785. )
  786. mapping.register(RouteImpl, Route)
  787. class WebSocket(AsyncBase):
  788. @typing.overload
  789. def on(
  790. self,
  791. event: Literal["close"],
  792. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  793. ) -> None:
  794. """
  795. Fired when the websocket closes."""
  796. @typing.overload
  797. def on(
  798. self,
  799. event: Literal["framereceived"],
  800. f: typing.Callable[
  801. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  802. ],
  803. ) -> None:
  804. """
  805. Fired when the websocket receives a frame."""
  806. @typing.overload
  807. def on(
  808. self,
  809. event: Literal["framesent"],
  810. f: typing.Callable[
  811. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  812. ],
  813. ) -> None:
  814. """
  815. Fired when the websocket sends a frame."""
  816. @typing.overload
  817. def on(
  818. self,
  819. event: Literal["socketerror"],
  820. f: typing.Callable[["str"], "typing.Union[typing.Awaitable[None], None]"],
  821. ) -> None:
  822. """
  823. Fired when the websocket has an error."""
  824. def on(
  825. self,
  826. event: str,
  827. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  828. ) -> None:
  829. return super().on(event=event, f=f)
  830. @typing.overload
  831. def once(
  832. self,
  833. event: Literal["close"],
  834. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  835. ) -> None:
  836. """
  837. Fired when the websocket closes."""
  838. @typing.overload
  839. def once(
  840. self,
  841. event: Literal["framereceived"],
  842. f: typing.Callable[
  843. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  844. ],
  845. ) -> None:
  846. """
  847. Fired when the websocket receives a frame."""
  848. @typing.overload
  849. def once(
  850. self,
  851. event: Literal["framesent"],
  852. f: typing.Callable[
  853. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  854. ],
  855. ) -> None:
  856. """
  857. Fired when the websocket sends a frame."""
  858. @typing.overload
  859. def once(
  860. self,
  861. event: Literal["socketerror"],
  862. f: typing.Callable[["str"], "typing.Union[typing.Awaitable[None], None]"],
  863. ) -> None:
  864. """
  865. Fired when the websocket has an error."""
  866. def once(
  867. self,
  868. event: str,
  869. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  870. ) -> None:
  871. return super().once(event=event, f=f)
  872. @property
  873. def url(self) -> str:
  874. """WebSocket.url
  875. Contains the URL of the WebSocket.
  876. Returns
  877. -------
  878. str
  879. """
  880. return mapping.from_maybe_impl(self._impl_obj.url)
  881. @typing.overload
  882. def expect_event(
  883. self,
  884. event: typing.Literal["close"],
  885. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  886. *,
  887. timeout: typing.Optional[float] = None,
  888. ) -> AsyncEventContextManager["WebSocket"]: ...
  889. @typing.overload
  890. def expect_event(
  891. self,
  892. event: typing.Literal["framereceived"],
  893. predicate: typing.Optional[
  894. typing.Callable[["typing.Union[bytes, str]"], bool]
  895. ] = None,
  896. *,
  897. timeout: typing.Optional[float] = None,
  898. ) -> AsyncEventContextManager["typing.Union[bytes, str]"]: ...
  899. @typing.overload
  900. def expect_event(
  901. self,
  902. event: typing.Literal["framesent"],
  903. predicate: typing.Optional[
  904. typing.Callable[["typing.Union[bytes, str]"], bool]
  905. ] = None,
  906. *,
  907. timeout: typing.Optional[float] = None,
  908. ) -> AsyncEventContextManager["typing.Union[bytes, str]"]: ...
  909. @typing.overload
  910. def expect_event(
  911. self,
  912. event: typing.Literal["socketerror"],
  913. predicate: typing.Optional[typing.Callable[["str"], bool]] = None,
  914. *,
  915. timeout: typing.Optional[float] = None,
  916. ) -> AsyncEventContextManager["str"]: ...
  917. @typing.overload
  918. def expect_event(
  919. self,
  920. event: str,
  921. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  922. *,
  923. timeout: typing.Optional[float] = None,
  924. ) -> AsyncEventContextManager[typing.Any]: ...
  925. def expect_event(
  926. self,
  927. event: str,
  928. predicate: typing.Optional[typing.Callable] = None,
  929. *,
  930. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  931. ) -> AsyncEventContextManager:
  932. """WebSocket.expect_event
  933. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  934. value. Will throw an error if the webSocket is closed before the event is fired. Returns the event data value.
  935. Parameters
  936. ----------
  937. event : str
  938. Event name, same one would pass into `webSocket.on(event)`.
  939. predicate : Union[Callable, None]
  940. Receives the event data and resolves to truthy value when the waiting should resolve.
  941. timeout : Union[float, None]
  942. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  943. default value can be changed by using the `browser_context.set_default_timeout()`.
  944. Returns
  945. -------
  946. EventContextManager
  947. """
  948. return AsyncEventContextManager(
  949. self._impl_obj.expect_event(
  950. event=event,
  951. predicate=self._wrap_handler(predicate),
  952. timeout=to_milliseconds(timeout),
  953. ).future
  954. )
  955. @typing.overload
  956. async def wait_for_event(
  957. self,
  958. event: typing.Literal["close"],
  959. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  960. *,
  961. timeout: typing.Optional[float] = None,
  962. ) -> "WebSocket": ...
  963. @typing.overload
  964. async def wait_for_event(
  965. self,
  966. event: typing.Literal["framereceived"],
  967. predicate: typing.Optional[
  968. typing.Callable[["typing.Union[bytes, str]"], bool]
  969. ] = None,
  970. *,
  971. timeout: typing.Optional[float] = None,
  972. ) -> "typing.Union[bytes, str]": ...
  973. @typing.overload
  974. async def wait_for_event(
  975. self,
  976. event: typing.Literal["framesent"],
  977. predicate: typing.Optional[
  978. typing.Callable[["typing.Union[bytes, str]"], bool]
  979. ] = None,
  980. *,
  981. timeout: typing.Optional[float] = None,
  982. ) -> "typing.Union[bytes, str]": ...
  983. @typing.overload
  984. async def wait_for_event(
  985. self,
  986. event: typing.Literal["socketerror"],
  987. predicate: typing.Optional[typing.Callable[["str"], bool]] = None,
  988. *,
  989. timeout: typing.Optional[float] = None,
  990. ) -> "str": ...
  991. @typing.overload
  992. async def wait_for_event(
  993. self,
  994. event: str,
  995. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  996. *,
  997. timeout: typing.Optional[float] = None,
  998. ) -> typing.Any: ...
  999. async def wait_for_event(
  1000. self,
  1001. event: str,
  1002. predicate: typing.Optional[typing.Callable] = None,
  1003. *,
  1004. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1005. ) -> typing.Any:
  1006. """WebSocket.wait_for_event
  1007. **NOTE** In most cases, you should use `web_socket.expect_event()`.
  1008. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  1009. and waits for `predicate(event)` to return a truthy value. Will throw an error if the socket is closed before the
  1010. `event` is fired.
  1011. Parameters
  1012. ----------
  1013. event : str
  1014. Event name, same one typically passed into `*.on(event)`.
  1015. predicate : Union[Callable, None]
  1016. Receives the event data and resolves to truthy value when the waiting should resolve.
  1017. timeout : Union[float, None]
  1018. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  1019. default value can be changed by using the `browser_context.set_default_timeout()`.
  1020. Returns
  1021. -------
  1022. Any
  1023. """
  1024. return mapping.from_maybe_impl(
  1025. await self._impl_obj.wait_for_event(
  1026. event=event,
  1027. predicate=self._wrap_handler(predicate),
  1028. timeout=to_milliseconds(timeout),
  1029. )
  1030. )
  1031. def is_closed(self) -> bool:
  1032. """WebSocket.is_closed
  1033. Indicates that the web socket has been closed.
  1034. Returns
  1035. -------
  1036. bool
  1037. """
  1038. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  1039. mapping.register(WebSocketImpl, WebSocket)
  1040. class WebSocketRoute(AsyncBase):
  1041. @property
  1042. def url(self) -> str:
  1043. """WebSocketRoute.url
  1044. URL of the WebSocket created in the page.
  1045. Returns
  1046. -------
  1047. str
  1048. """
  1049. return mapping.from_maybe_impl(self._impl_obj.url)
  1050. @property
  1051. def protocols(self) -> typing.List[str]:
  1052. """WebSocketRoute.protocols
  1053. The list of WebSocket subprotocols requested by the page, as passed via the second argument to the
  1054. [`WebSocket` constructor](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket). Corresponds to the
  1055. `Sec-WebSocket-Protocol` request header.
  1056. Returns an empty array if no protocols were specified.
  1057. **Usage**
  1058. ```py
  1059. async def handler(ws: WebSocketRoute):
  1060. if \"chat.v2\" in ws.protocols:
  1061. ws.on_message(lambda message: ws.send(f\"v2:{message}\"))
  1062. else:
  1063. await ws.close(code=1002, reason=\"Unsupported protocol\")
  1064. await page.route_web_socket(\"wss://example.com/ws\", handler)
  1065. ```
  1066. Returns
  1067. -------
  1068. List[str]
  1069. """
  1070. return mapping.from_maybe_impl(self._impl_obj.protocols)
  1071. async def close(
  1072. self, *, code: typing.Optional[int] = None, reason: typing.Optional[str] = None
  1073. ) -> None:
  1074. """WebSocketRoute.close
  1075. Closes one side of the WebSocket connection.
  1076. Parameters
  1077. ----------
  1078. code : Union[int, None]
  1079. Optional [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code).
  1080. reason : Union[str, None]
  1081. Optional [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
  1082. """
  1083. return mapping.from_maybe_impl(
  1084. await self._impl_obj.close(code=code, reason=reason)
  1085. )
  1086. def connect_to_server(self) -> "WebSocketRoute":
  1087. """WebSocketRoute.connect_to_server
  1088. By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This
  1089. method connects to the actual WebSocket server, and returns the server-side `WebSocketRoute` instance, giving the
  1090. ability to send and receive messages from the server.
  1091. Once connected to the server:
  1092. - Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless
  1093. `web_socket_route.on_message()` is called on the server-side `WebSocketRoute`.
  1094. - Messages sent by the [`WebSocket.send()`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) call
  1095. in the page will be **automatically forwarded** to the server, unless `web_socket_route.on_message()` is
  1096. called on the original `WebSocketRoute`.
  1097. See examples at the top for more details.
  1098. Returns
  1099. -------
  1100. WebSocketRoute
  1101. """
  1102. return mapping.from_impl(self._impl_obj.connect_to_server())
  1103. def send(self, message: typing.Union[str, bytes]) -> None:
  1104. """WebSocketRoute.send
  1105. Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called
  1106. on the result of `web_socket_route.connect_to_server()`, sends the message to the server. See examples at the
  1107. top for more details.
  1108. Parameters
  1109. ----------
  1110. message : Union[bytes, str]
  1111. Message to send.
  1112. """
  1113. return mapping.from_maybe_impl(self._impl_obj.send(message=message))
  1114. def on_message(
  1115. self, handler: typing.Callable[[typing.Union[str, bytes]], typing.Any]
  1116. ) -> None:
  1117. """WebSocketRoute.on_message
  1118. This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.
  1119. When called on the original WebSocket route, this method handles messages sent from the page. You can handle this
  1120. messages by responding to them with `web_socket_route.send()`, forwarding them to the server-side connection
  1121. returned by `web_socket_route.connect_to_server()` or do something else.
  1122. Once this method is called, messages are not automatically forwarded to the server or to the page - you should do
  1123. that manually by calling `web_socket_route.send()`. See examples at the top for more details.
  1124. Calling this method again will override the handler with a new one.
  1125. Parameters
  1126. ----------
  1127. handler : Callable[[Union[bytes, str]], Any]
  1128. Function that will handle messages.
  1129. """
  1130. return mapping.from_maybe_impl(
  1131. self._impl_obj.on_message(handler=self._wrap_handler(handler))
  1132. )
  1133. def on_close(
  1134. self,
  1135. handler: typing.Callable[
  1136. [typing.Optional[int], typing.Optional[str]], typing.Any
  1137. ],
  1138. ) -> None:
  1139. """WebSocketRoute.on_close
  1140. Allows to handle [`WebSocket.close`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close).
  1141. By default, closing one side of the connection, either in the page or on the server, will close the other side.
  1142. However, when `web_socket_route.on_close()` handler is set up, the default forwarding of closure is disabled,
  1143. and handler should take care of it.
  1144. Parameters
  1145. ----------
  1146. handler : Callable[[Union[int, None], Union[str, None]], Any]
  1147. Function that will handle WebSocket closure. Received an optional
  1148. [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code) and an optional
  1149. [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
  1150. """
  1151. return mapping.from_maybe_impl(
  1152. self._impl_obj.on_close(handler=self._wrap_handler(handler))
  1153. )
  1154. mapping.register(WebSocketRouteImpl, WebSocketRoute)
  1155. class Keyboard(AsyncBase):
  1156. async def down(self, key: str) -> None:
  1157. """Keyboard.down
  1158. Dispatches a `keydown` event.
  1159. `key` can specify the intended
  1160. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  1161. to generate the text for. A superset of the `key` values can be found
  1162. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  1163. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  1164. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  1165. etc.
  1166. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  1167. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  1168. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  1169. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  1170. texts.
  1171. If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that
  1172. modifier active. To release the modifier key, use `keyboard.up()`.
  1173. After the key is pressed once, subsequent calls to `keyboard.down()` will have
  1174. [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,
  1175. use `keyboard.up()`.
  1176. **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
  1177. Parameters
  1178. ----------
  1179. key : str
  1180. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1181. """
  1182. return mapping.from_maybe_impl(await self._impl_obj.down(key=key))
  1183. async def up(self, key: str) -> None:
  1184. """Keyboard.up
  1185. Dispatches a `keyup` event.
  1186. Parameters
  1187. ----------
  1188. key : str
  1189. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1190. """
  1191. return mapping.from_maybe_impl(await self._impl_obj.up(key=key))
  1192. async def insert_text(self, text: str) -> None:
  1193. """Keyboard.insert_text
  1194. Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
  1195. **Usage**
  1196. ```py
  1197. await page.keyboard.insert_text(\"嗨\")
  1198. ```
  1199. **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper
  1200. case.
  1201. Parameters
  1202. ----------
  1203. text : str
  1204. Sets input to the specified text value.
  1205. """
  1206. return mapping.from_maybe_impl(await self._impl_obj.insert_text(text=text))
  1207. async def type(self, text: str, *, delay: typing.Optional[float] = None) -> None:
  1208. """Keyboard.type
  1209. **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
  1210. there is special keyboard handling on the page - in this case use `locator.press_sequentially()`.
  1211. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
  1212. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  1213. **Usage**
  1214. ```py
  1215. await page.keyboard.type(\"Hello\") # types instantly
  1216. await page.keyboard.type(\"World\", delay=100) # types slower, like a user
  1217. ```
  1218. **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.
  1219. **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.
  1220. Parameters
  1221. ----------
  1222. text : str
  1223. A text to type into a focused element.
  1224. delay : Union[float, None]
  1225. Time to wait between key presses in milliseconds. Defaults to 0.
  1226. """
  1227. return mapping.from_maybe_impl(
  1228. await self._impl_obj.type(text=text, delay=delay)
  1229. )
  1230. async def press(self, key: str, *, delay: typing.Optional[float] = None) -> None:
  1231. """Keyboard.press
  1232. **NOTE** In most cases, you should use `locator.press()` instead.
  1233. `key` can specify the intended
  1234. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  1235. to generate the text for. A superset of the `key` values can be found
  1236. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  1237. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  1238. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  1239. etc.
  1240. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  1241. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  1242. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  1243. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  1244. texts.
  1245. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  1246. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  1247. **Usage**
  1248. ```py
  1249. page = await browser.new_page()
  1250. await page.goto(\"https://keycode.info\")
  1251. await page.keyboard.press(\"a\")
  1252. await page.screenshot(path=\"a.png\")
  1253. await page.keyboard.press(\"ArrowLeft\")
  1254. await page.screenshot(path=\"arrow_left.png\")
  1255. await page.keyboard.press(\"Shift+O\")
  1256. await page.screenshot(path=\"o.png\")
  1257. await browser.close()
  1258. ```
  1259. Shortcut for `keyboard.down()` and `keyboard.up()`.
  1260. Parameters
  1261. ----------
  1262. key : str
  1263. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1264. delay : Union[float, None]
  1265. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  1266. """
  1267. return mapping.from_maybe_impl(await self._impl_obj.press(key=key, delay=delay))
  1268. mapping.register(KeyboardImpl, Keyboard)
  1269. class Mouse(AsyncBase):
  1270. async def move(
  1271. self, x: float, y: float, *, steps: typing.Optional[int] = None
  1272. ) -> None:
  1273. """Mouse.move
  1274. Dispatches a `mousemove` event.
  1275. Parameters
  1276. ----------
  1277. x : float
  1278. X coordinate relative to the main frame's viewport in CSS pixels.
  1279. y : float
  1280. Y coordinate relative to the main frame's viewport in CSS pixels.
  1281. steps : Union[int, None]
  1282. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1283. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1284. """
  1285. return mapping.from_maybe_impl(await self._impl_obj.move(x=x, y=y, steps=steps))
  1286. async def down(
  1287. self,
  1288. *,
  1289. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1290. click_count: typing.Optional[int] = None,
  1291. ) -> None:
  1292. """Mouse.down
  1293. Dispatches a `mousedown` event.
  1294. Parameters
  1295. ----------
  1296. button : Union["left", "middle", "right", None]
  1297. Defaults to `left`.
  1298. click_count : Union[int, None]
  1299. defaults to 1. See [UIEvent.detail].
  1300. """
  1301. return mapping.from_maybe_impl(
  1302. await self._impl_obj.down(button=button, clickCount=click_count)
  1303. )
  1304. async def up(
  1305. self,
  1306. *,
  1307. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1308. click_count: typing.Optional[int] = None,
  1309. ) -> None:
  1310. """Mouse.up
  1311. Dispatches a `mouseup` event.
  1312. Parameters
  1313. ----------
  1314. button : Union["left", "middle", "right", None]
  1315. Defaults to `left`.
  1316. click_count : Union[int, None]
  1317. defaults to 1. See [UIEvent.detail].
  1318. """
  1319. return mapping.from_maybe_impl(
  1320. await self._impl_obj.up(button=button, clickCount=click_count)
  1321. )
  1322. async def click(
  1323. self,
  1324. x: float,
  1325. y: float,
  1326. *,
  1327. delay: typing.Optional[float] = None,
  1328. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1329. click_count: typing.Optional[int] = None,
  1330. ) -> None:
  1331. """Mouse.click
  1332. Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`.
  1333. Parameters
  1334. ----------
  1335. x : float
  1336. X coordinate relative to the main frame's viewport in CSS pixels.
  1337. y : float
  1338. Y coordinate relative to the main frame's viewport in CSS pixels.
  1339. delay : Union[float, None]
  1340. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1341. button : Union["left", "middle", "right", None]
  1342. Defaults to `left`.
  1343. click_count : Union[int, None]
  1344. defaults to 1. See [UIEvent.detail].
  1345. """
  1346. return mapping.from_maybe_impl(
  1347. await self._impl_obj.click(
  1348. x=x, y=y, delay=delay, button=button, clickCount=click_count
  1349. )
  1350. )
  1351. async def dblclick(
  1352. self,
  1353. x: float,
  1354. y: float,
  1355. *,
  1356. delay: typing.Optional[float] = None,
  1357. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1358. ) -> None:
  1359. """Mouse.dblclick
  1360. Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`, `mouse.down()` and
  1361. `mouse.up()`.
  1362. Parameters
  1363. ----------
  1364. x : float
  1365. X coordinate relative to the main frame's viewport in CSS pixels.
  1366. y : float
  1367. Y coordinate relative to the main frame's viewport in CSS pixels.
  1368. delay : Union[float, None]
  1369. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1370. button : Union["left", "middle", "right", None]
  1371. Defaults to `left`.
  1372. """
  1373. return mapping.from_maybe_impl(
  1374. await self._impl_obj.dblclick(x=x, y=y, delay=delay, button=button)
  1375. )
  1376. async def wheel(self, delta_x: float, delta_y: float) -> None:
  1377. """Mouse.wheel
  1378. Dispatches a `wheel` event. This method is usually used to manually scroll the page. See
  1379. [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  1380. **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling
  1381. to finish before returning.
  1382. Parameters
  1383. ----------
  1384. delta_x : float
  1385. Pixels to scroll horizontally.
  1386. delta_y : float
  1387. Pixels to scroll vertically.
  1388. """
  1389. return mapping.from_maybe_impl(
  1390. await self._impl_obj.wheel(deltaX=delta_x, deltaY=delta_y)
  1391. )
  1392. mapping.register(MouseImpl, Mouse)
  1393. class Touchscreen(AsyncBase):
  1394. async def tap(self, x: float, y: float) -> None:
  1395. """Touchscreen.tap
  1396. Dispatches a `touchstart` and `touchend` event with a single touch at the position (`x`,`y`).
  1397. **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
  1398. Parameters
  1399. ----------
  1400. x : float
  1401. X coordinate relative to the main frame's viewport in CSS pixels.
  1402. y : float
  1403. Y coordinate relative to the main frame's viewport in CSS pixels.
  1404. """
  1405. return mapping.from_maybe_impl(await self._impl_obj.tap(x=x, y=y))
  1406. mapping.register(TouchscreenImpl, Touchscreen)
  1407. class JSHandle(AsyncBase):
  1408. async def evaluate(
  1409. self, expression: str, arg: typing.Optional[typing.Any] = None
  1410. ) -> typing.Any:
  1411. """JSHandle.evaluate
  1412. Returns the return value of `expression`.
  1413. This method passes this handle as the first argument to `expression`.
  1414. If `expression` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
  1415. value.
  1416. **Usage**
  1417. ```py
  1418. tweet_handle = await page.query_selector(\".tweet .retweets\")
  1419. assert await tweet_handle.evaluate(\"node => node.innerText\") == \"10 retweets\"
  1420. ```
  1421. Parameters
  1422. ----------
  1423. expression : str
  1424. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  1425. function is automatically invoked.
  1426. arg : Union[Any, None]
  1427. Optional argument to pass to `expression`.
  1428. Returns
  1429. -------
  1430. Any
  1431. """
  1432. return mapping.from_maybe_impl(
  1433. await self._impl_obj.evaluate(
  1434. expression=expression, arg=mapping.to_impl(arg)
  1435. )
  1436. )
  1437. async def evaluate_handle(
  1438. self, expression: str, arg: typing.Optional[typing.Any] = None
  1439. ) -> "JSHandle":
  1440. """JSHandle.evaluate_handle
  1441. Returns the return value of `expression` as a `JSHandle`.
  1442. This method passes this handle as the first argument to `expression`.
  1443. The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
  1444. returns `JSHandle`.
  1445. If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
  1446. wait for the promise to resolve and return its value.
  1447. See `page.evaluate_handle()` for more details.
  1448. Parameters
  1449. ----------
  1450. expression : str
  1451. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  1452. function is automatically invoked.
  1453. arg : Union[Any, None]
  1454. Optional argument to pass to `expression`.
  1455. Returns
  1456. -------
  1457. JSHandle
  1458. """
  1459. return mapping.from_impl(
  1460. await self._impl_obj.evaluate_handle(
  1461. expression=expression, arg=mapping.to_impl(arg)
  1462. )
  1463. )
  1464. async def get_property(self, property_name: str) -> "JSHandle":
  1465. """JSHandle.get_property
  1466. Fetches a single property from the referenced object.
  1467. Parameters
  1468. ----------
  1469. property_name : str
  1470. property to get
  1471. Returns
  1472. -------
  1473. JSHandle
  1474. """
  1475. return mapping.from_impl(
  1476. await self._impl_obj.get_property(propertyName=property_name)
  1477. )
  1478. async def get_properties(self) -> typing.Dict[str, "JSHandle"]:
  1479. """JSHandle.get_properties
  1480. The method returns a map with **own property names** as keys and JSHandle instances for the property values.
  1481. **Usage**
  1482. ```py
  1483. handle = await page.evaluate_handle(\"({ window, document })\")
  1484. properties = await handle.get_properties()
  1485. window_handle = properties.get(\"window\")
  1486. document_handle = properties.get(\"document\")
  1487. await handle.dispose()
  1488. ```
  1489. Returns
  1490. -------
  1491. Dict[str, JSHandle]
  1492. """
  1493. return mapping.from_impl_dict(await self._impl_obj.get_properties())
  1494. def as_element(self) -> typing.Optional["ElementHandle"]:
  1495. """JSHandle.as_element
  1496. Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
  1497. Returns
  1498. -------
  1499. Union[ElementHandle, None]
  1500. """
  1501. return mapping.from_impl_nullable(self._impl_obj.as_element())
  1502. async def dispose(self) -> None:
  1503. """JSHandle.dispose
  1504. The `jsHandle.dispose` method stops referencing the element handle.
  1505. """
  1506. return mapping.from_maybe_impl(await self._impl_obj.dispose())
  1507. async def json_value(self) -> typing.Any:
  1508. """JSHandle.json_value
  1509. Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
  1510. **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw
  1511. an error if the object has circular references.
  1512. Returns
  1513. -------
  1514. Any
  1515. """
  1516. return mapping.from_maybe_impl(await self._impl_obj.json_value())
  1517. mapping.register(JSHandleImpl, JSHandle)
  1518. class ElementHandle(JSHandle):
  1519. def as_element(self) -> typing.Optional["ElementHandle"]:
  1520. """ElementHandle.as_element
  1521. Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
  1522. Returns
  1523. -------
  1524. Union[ElementHandle, None]
  1525. """
  1526. return mapping.from_impl_nullable(self._impl_obj.as_element())
  1527. async def owner_frame(self) -> typing.Optional["Frame"]:
  1528. """ElementHandle.owner_frame
  1529. Returns the frame containing the given element.
  1530. Returns
  1531. -------
  1532. Union[Frame, None]
  1533. """
  1534. return mapping.from_impl_nullable(await self._impl_obj.owner_frame())
  1535. async def content_frame(self) -> typing.Optional["Frame"]:
  1536. """ElementHandle.content_frame
  1537. Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
  1538. Returns
  1539. -------
  1540. Union[Frame, None]
  1541. """
  1542. return mapping.from_impl_nullable(await self._impl_obj.content_frame())
  1543. async def get_attribute(self, name: str) -> typing.Optional[str]:
  1544. """ElementHandle.get_attribute
  1545. Returns element attribute value.
  1546. Parameters
  1547. ----------
  1548. name : str
  1549. Attribute name to get the value for.
  1550. Returns
  1551. -------
  1552. Union[str, None]
  1553. """
  1554. return mapping.from_maybe_impl(await self._impl_obj.get_attribute(name=name))
  1555. async def text_content(self) -> typing.Optional[str]:
  1556. """ElementHandle.text_content
  1557. Returns the `node.textContent`.
  1558. Returns
  1559. -------
  1560. Union[str, None]
  1561. """
  1562. return mapping.from_maybe_impl(await self._impl_obj.text_content())
  1563. async def inner_text(self) -> str:
  1564. """ElementHandle.inner_text
  1565. Returns the `element.innerText`.
  1566. Returns
  1567. -------
  1568. str
  1569. """
  1570. return mapping.from_maybe_impl(await self._impl_obj.inner_text())
  1571. async def inner_html(self) -> str:
  1572. """ElementHandle.inner_html
  1573. Returns the `element.innerHTML`.
  1574. Returns
  1575. -------
  1576. str
  1577. """
  1578. return mapping.from_maybe_impl(await self._impl_obj.inner_html())
  1579. async def is_checked(self) -> bool:
  1580. """ElementHandle.is_checked
  1581. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  1582. Returns
  1583. -------
  1584. bool
  1585. """
  1586. return mapping.from_maybe_impl(await self._impl_obj.is_checked())
  1587. async def is_disabled(self) -> bool:
  1588. """ElementHandle.is_disabled
  1589. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  1590. Returns
  1591. -------
  1592. bool
  1593. """
  1594. return mapping.from_maybe_impl(await self._impl_obj.is_disabled())
  1595. async def is_editable(self) -> bool:
  1596. """ElementHandle.is_editable
  1597. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  1598. Returns
  1599. -------
  1600. bool
  1601. """
  1602. return mapping.from_maybe_impl(await self._impl_obj.is_editable())
  1603. async def is_enabled(self) -> bool:
  1604. """ElementHandle.is_enabled
  1605. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  1606. Returns
  1607. -------
  1608. bool
  1609. """
  1610. return mapping.from_maybe_impl(await self._impl_obj.is_enabled())
  1611. async def is_hidden(self) -> bool:
  1612. """ElementHandle.is_hidden
  1613. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
  1614. Returns
  1615. -------
  1616. bool
  1617. """
  1618. return mapping.from_maybe_impl(await self._impl_obj.is_hidden())
  1619. async def is_visible(self) -> bool:
  1620. """ElementHandle.is_visible
  1621. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  1622. Returns
  1623. -------
  1624. bool
  1625. """
  1626. return mapping.from_maybe_impl(await self._impl_obj.is_visible())
  1627. async def dispatch_event(
  1628. self, type: str, event_init: typing.Optional[typing.Dict] = None
  1629. ) -> None:
  1630. """ElementHandle.dispatch_event
  1631. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  1632. `click` is dispatched. This is equivalent to calling
  1633. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  1634. **Usage**
  1635. ```py
  1636. await element_handle.dispatch_event(\"click\")
  1637. ```
  1638. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  1639. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  1640. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  1641. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  1642. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  1643. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  1644. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  1645. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  1646. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  1647. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  1648. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  1649. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  1650. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  1651. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  1652. ```py
  1653. # note you can only create data_transfer in chromium and firefox
  1654. data_transfer = await page.evaluate_handle(\"new DataTransfer()\")
  1655. await element_handle.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
  1656. ```
  1657. Parameters
  1658. ----------
  1659. type : str
  1660. DOM event type: `"click"`, `"dragstart"`, etc.
  1661. event_init : Union[Dict, None]
  1662. Optional event-specific initialization properties.
  1663. """
  1664. return mapping.from_maybe_impl(
  1665. await self._impl_obj.dispatch_event(
  1666. type=type, eventInit=mapping.to_impl(event_init)
  1667. )
  1668. )
  1669. async def scroll_into_view_if_needed(
  1670. self,
  1671. *,
  1672. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1673. ) -> None:
  1674. """ElementHandle.scroll_into_view_if_needed
  1675. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
  1676. it is completely visible as defined by
  1677. [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
  1678. Throws when `elementHandle` does not point to an element
  1679. [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
  1680. See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  1681. Parameters
  1682. ----------
  1683. timeout : Union[float, None]
  1684. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1685. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1686. """
  1687. return mapping.from_maybe_impl(
  1688. await self._impl_obj.scroll_into_view_if_needed(
  1689. timeout=to_milliseconds(timeout)
  1690. )
  1691. )
  1692. async def hover(
  1693. self,
  1694. *,
  1695. modifiers: typing.Optional[
  1696. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1697. ] = None,
  1698. position: typing.Optional[Position] = None,
  1699. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1700. no_wait_after: typing.Optional[bool] = None,
  1701. force: typing.Optional[bool] = None,
  1702. trial: typing.Optional[bool] = None,
  1703. ) -> None:
  1704. """ElementHandle.hover
  1705. This method hovers over the element by performing the following steps:
  1706. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1707. 1. Scroll the element into view if needed.
  1708. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  1709. If the element is detached from the DOM at any moment during the action, this method throws.
  1710. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1711. Passing zero timeout disables this.
  1712. Parameters
  1713. ----------
  1714. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1715. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1716. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1717. "Control" on Windows and Linux and to "Meta" on macOS.
  1718. position : Union[{x: float, y: float}, None]
  1719. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1720. the element.
  1721. timeout : Union[float, None]
  1722. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1723. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1724. no_wait_after : Union[bool, None]
  1725. This option has no effect.
  1726. Deprecated: This option has no effect.
  1727. force : Union[bool, None]
  1728. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1729. trial : Union[bool, None]
  1730. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1731. to `false`. Useful to wait until the element is ready for the action without performing it.
  1732. """
  1733. return mapping.from_maybe_impl(
  1734. await self._impl_obj.hover(
  1735. modifiers=mapping.to_impl(modifiers),
  1736. position=position,
  1737. timeout=to_milliseconds(timeout),
  1738. noWaitAfter=no_wait_after,
  1739. force=force,
  1740. trial=trial,
  1741. )
  1742. )
  1743. async def click(
  1744. self,
  1745. *,
  1746. modifiers: typing.Optional[
  1747. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1748. ] = None,
  1749. position: typing.Optional[Position] = None,
  1750. delay: typing.Optional[float] = None,
  1751. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1752. click_count: typing.Optional[int] = None,
  1753. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1754. force: typing.Optional[bool] = None,
  1755. no_wait_after: typing.Optional[bool] = None,
  1756. trial: typing.Optional[bool] = None,
  1757. steps: typing.Optional[int] = None,
  1758. ) -> None:
  1759. """ElementHandle.click
  1760. This method clicks the element by performing the following steps:
  1761. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1762. 1. Scroll the element into view if needed.
  1763. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  1764. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  1765. If the element is detached from the DOM at any moment during the action, this method throws.
  1766. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1767. Passing zero timeout disables this.
  1768. Parameters
  1769. ----------
  1770. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1771. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1772. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1773. "Control" on Windows and Linux and to "Meta" on macOS.
  1774. position : Union[{x: float, y: float}, None]
  1775. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1776. the element.
  1777. delay : Union[float, None]
  1778. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1779. button : Union["left", "middle", "right", None]
  1780. Defaults to `left`.
  1781. click_count : Union[int, None]
  1782. defaults to 1. See [UIEvent.detail].
  1783. timeout : Union[float, None]
  1784. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1785. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1786. force : Union[bool, None]
  1787. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1788. no_wait_after : Union[bool, None]
  1789. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  1790. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  1791. navigating to inaccessible pages. Defaults to `false`.
  1792. Deprecated: This option will default to `true` in the future.
  1793. trial : Union[bool, None]
  1794. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1795. to `false`. Useful to wait until the element is ready for the action without performing it.
  1796. steps : Union[int, None]
  1797. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1798. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1799. """
  1800. return mapping.from_maybe_impl(
  1801. await self._impl_obj.click(
  1802. modifiers=mapping.to_impl(modifiers),
  1803. position=position,
  1804. delay=delay,
  1805. button=button,
  1806. clickCount=click_count,
  1807. timeout=to_milliseconds(timeout),
  1808. force=force,
  1809. noWaitAfter=no_wait_after,
  1810. trial=trial,
  1811. steps=steps,
  1812. )
  1813. )
  1814. async def dblclick(
  1815. self,
  1816. *,
  1817. modifiers: typing.Optional[
  1818. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1819. ] = None,
  1820. position: typing.Optional[Position] = None,
  1821. delay: typing.Optional[float] = None,
  1822. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1823. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1824. force: typing.Optional[bool] = None,
  1825. no_wait_after: typing.Optional[bool] = None,
  1826. trial: typing.Optional[bool] = None,
  1827. steps: typing.Optional[int] = None,
  1828. ) -> None:
  1829. """ElementHandle.dblclick
  1830. This method double clicks the element by performing the following steps:
  1831. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1832. 1. Scroll the element into view if needed.
  1833. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  1834. If the element is detached from the DOM at any moment during the action, this method throws.
  1835. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1836. Passing zero timeout disables this.
  1837. **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
  1838. Parameters
  1839. ----------
  1840. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1841. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1842. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1843. "Control" on Windows and Linux and to "Meta" on macOS.
  1844. position : Union[{x: float, y: float}, None]
  1845. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1846. the element.
  1847. delay : Union[float, None]
  1848. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1849. button : Union["left", "middle", "right", None]
  1850. Defaults to `left`.
  1851. timeout : Union[float, None]
  1852. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1853. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1854. force : Union[bool, None]
  1855. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1856. no_wait_after : Union[bool, None]
  1857. This option has no effect.
  1858. Deprecated: This option has no effect.
  1859. trial : Union[bool, None]
  1860. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1861. to `false`. Useful to wait until the element is ready for the action without performing it.
  1862. steps : Union[int, None]
  1863. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1864. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1865. """
  1866. return mapping.from_maybe_impl(
  1867. await self._impl_obj.dblclick(
  1868. modifiers=mapping.to_impl(modifiers),
  1869. position=position,
  1870. delay=delay,
  1871. button=button,
  1872. timeout=to_milliseconds(timeout),
  1873. force=force,
  1874. noWaitAfter=no_wait_after,
  1875. trial=trial,
  1876. steps=steps,
  1877. )
  1878. )
  1879. async def select_option(
  1880. self,
  1881. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  1882. *,
  1883. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  1884. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  1885. element: typing.Optional[
  1886. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  1887. ] = None,
  1888. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1889. force: typing.Optional[bool] = None,
  1890. no_wait_after: typing.Optional[bool] = None,
  1891. ) -> typing.List[str]:
  1892. """ElementHandle.select_option
  1893. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
  1894. the `<select>` element and selects these options.
  1895. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  1896. the `<label>` element that has an associated
  1897. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  1898. instead.
  1899. Returns the array of option values that have been successfully selected.
  1900. Triggers a `change` and `input` event once all the provided options have been selected.
  1901. **Usage**
  1902. ```py
  1903. # Single selection matching the value or label
  1904. await handle.select_option(\"blue\")
  1905. # single selection matching the label
  1906. await handle.select_option(label=\"blue\")
  1907. # multiple selection
  1908. await handle.select_option(value=[\"red\", \"green\", \"blue\"])
  1909. ```
  1910. Parameters
  1911. ----------
  1912. value : Union[Sequence[str], str, None]
  1913. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  1914. otherwise only the first option matching one of the passed options is selected. Optional.
  1915. index : Union[Sequence[int], int, None]
  1916. Options to select by index. Optional.
  1917. label : Union[Sequence[str], str, None]
  1918. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  1919. otherwise only the first option matching one of the passed options is selected. Optional.
  1920. element : Union[ElementHandle, Sequence[ElementHandle], None]
  1921. Option elements to select. Optional.
  1922. timeout : Union[float, None]
  1923. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1924. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1925. force : Union[bool, None]
  1926. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1927. no_wait_after : Union[bool, None]
  1928. This option has no effect.
  1929. Deprecated: This option has no effect.
  1930. Returns
  1931. -------
  1932. List[str]
  1933. """
  1934. return mapping.from_maybe_impl(
  1935. await self._impl_obj.select_option(
  1936. value=mapping.to_impl(value),
  1937. index=mapping.to_impl(index),
  1938. label=mapping.to_impl(label),
  1939. element=mapping.to_impl(element),
  1940. timeout=to_milliseconds(timeout),
  1941. force=force,
  1942. noWaitAfter=no_wait_after,
  1943. )
  1944. )
  1945. async def tap(
  1946. self,
  1947. *,
  1948. modifiers: typing.Optional[
  1949. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1950. ] = None,
  1951. position: typing.Optional[Position] = None,
  1952. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  1953. force: typing.Optional[bool] = None,
  1954. no_wait_after: typing.Optional[bool] = None,
  1955. trial: typing.Optional[bool] = None,
  1956. ) -> None:
  1957. """ElementHandle.tap
  1958. This method taps the element by performing the following steps:
  1959. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1960. 1. Scroll the element into view if needed.
  1961. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  1962. If the element is detached from the DOM at any moment during the action, this method throws.
  1963. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1964. Passing zero timeout disables this.
  1965. **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
  1966. Parameters
  1967. ----------
  1968. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1969. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1970. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1971. "Control" on Windows and Linux and to "Meta" on macOS.
  1972. position : Union[{x: float, y: float}, None]
  1973. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1974. the element.
  1975. timeout : Union[float, None]
  1976. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1977. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1978. force : Union[bool, None]
  1979. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1980. no_wait_after : Union[bool, None]
  1981. This option has no effect.
  1982. Deprecated: This option has no effect.
  1983. trial : Union[bool, None]
  1984. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1985. to `false`. Useful to wait until the element is ready for the action without performing it.
  1986. """
  1987. return mapping.from_maybe_impl(
  1988. await self._impl_obj.tap(
  1989. modifiers=mapping.to_impl(modifiers),
  1990. position=position,
  1991. timeout=to_milliseconds(timeout),
  1992. force=force,
  1993. noWaitAfter=no_wait_after,
  1994. trial=trial,
  1995. )
  1996. )
  1997. async def fill(
  1998. self,
  1999. value: str,
  2000. *,
  2001. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2002. no_wait_after: typing.Optional[bool] = None,
  2003. force: typing.Optional[bool] = None,
  2004. ) -> None:
  2005. """ElementHandle.fill
  2006. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
  2007. `input` event after filling. Note that you can pass an empty string to clear the input field.
  2008. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  2009. error. However, if the element is inside the `<label>` element that has an associated
  2010. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  2011. instead.
  2012. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  2013. Parameters
  2014. ----------
  2015. value : str
  2016. Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
  2017. timeout : Union[float, None]
  2018. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2019. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2020. no_wait_after : Union[bool, None]
  2021. This option has no effect.
  2022. Deprecated: This option has no effect.
  2023. force : Union[bool, None]
  2024. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2025. """
  2026. return mapping.from_maybe_impl(
  2027. await self._impl_obj.fill(
  2028. value=value,
  2029. timeout=to_milliseconds(timeout),
  2030. noWaitAfter=no_wait_after,
  2031. force=force,
  2032. )
  2033. )
  2034. async def select_text(
  2035. self,
  2036. *,
  2037. force: typing.Optional[bool] = None,
  2038. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2039. ) -> None:
  2040. """ElementHandle.select_text
  2041. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
  2042. text content.
  2043. If the element is inside the `<label>` element that has an associated
  2044. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
  2045. the control instead.
  2046. Parameters
  2047. ----------
  2048. force : Union[bool, None]
  2049. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2050. timeout : Union[float, None]
  2051. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2052. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2053. """
  2054. return mapping.from_maybe_impl(
  2055. await self._impl_obj.select_text(
  2056. force=force, timeout=to_milliseconds(timeout)
  2057. )
  2058. )
  2059. async def input_value(
  2060. self,
  2061. *,
  2062. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2063. ) -> str:
  2064. """ElementHandle.input_value
  2065. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  2066. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  2067. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  2068. control.
  2069. Parameters
  2070. ----------
  2071. timeout : Union[float, None]
  2072. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2073. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2074. Returns
  2075. -------
  2076. str
  2077. """
  2078. return mapping.from_maybe_impl(
  2079. await self._impl_obj.input_value(timeout=to_milliseconds(timeout))
  2080. )
  2081. async def set_input_files(
  2082. self,
  2083. files: typing.Union[
  2084. str,
  2085. pathlib.Path,
  2086. FilePayload,
  2087. typing.Sequence[typing.Union[str, pathlib.Path]],
  2088. typing.Sequence[FilePayload],
  2089. ],
  2090. *,
  2091. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2092. no_wait_after: typing.Optional[bool] = None,
  2093. ) -> None:
  2094. """ElementHandle.set_input_files
  2095. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  2096. they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
  2097. with a `[webkitdirectory]` attribute, only a single directory path is supported.
  2098. This method expects `ElementHandle` to point to an
  2099. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  2100. the `<label>` element that has an associated
  2101. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  2102. Parameters
  2103. ----------
  2104. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  2105. timeout : Union[float, None]
  2106. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2107. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2108. no_wait_after : Union[bool, None]
  2109. This option has no effect.
  2110. Deprecated: This option has no effect.
  2111. """
  2112. return mapping.from_maybe_impl(
  2113. await self._impl_obj.set_input_files(
  2114. files=mapping.to_impl(files),
  2115. timeout=to_milliseconds(timeout),
  2116. noWaitAfter=no_wait_after,
  2117. )
  2118. )
  2119. async def focus(self) -> None:
  2120. """ElementHandle.focus
  2121. Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
  2122. """
  2123. return mapping.from_maybe_impl(await self._impl_obj.focus())
  2124. async def type(
  2125. self,
  2126. text: str,
  2127. *,
  2128. delay: typing.Optional[float] = None,
  2129. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2130. no_wait_after: typing.Optional[bool] = None,
  2131. ) -> None:
  2132. """ElementHandle.type
  2133. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  2134. text.
  2135. To press a special key, like `Control` or `ArrowDown`, use `element_handle.press()`.
  2136. **Usage**
  2137. Parameters
  2138. ----------
  2139. text : str
  2140. A text to type into a focused element.
  2141. delay : Union[float, None]
  2142. Time to wait between key presses in milliseconds. Defaults to 0.
  2143. timeout : Union[float, None]
  2144. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2145. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2146. no_wait_after : Union[bool, None]
  2147. This option has no effect.
  2148. Deprecated: This option has no effect.
  2149. """
  2150. return mapping.from_maybe_impl(
  2151. await self._impl_obj.type(
  2152. text=text,
  2153. delay=delay,
  2154. timeout=to_milliseconds(timeout),
  2155. noWaitAfter=no_wait_after,
  2156. )
  2157. )
  2158. async def press(
  2159. self,
  2160. key: str,
  2161. *,
  2162. delay: typing.Optional[float] = None,
  2163. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2164. no_wait_after: typing.Optional[bool] = None,
  2165. ) -> None:
  2166. """ElementHandle.press
  2167. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  2168. `key` can specify the intended
  2169. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  2170. to generate the text for. A superset of the `key` values can be found
  2171. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  2172. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  2173. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  2174. etc.
  2175. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  2176. `ControlOrMeta`.
  2177. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  2178. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  2179. texts.
  2180. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  2181. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  2182. Parameters
  2183. ----------
  2184. key : str
  2185. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  2186. delay : Union[float, None]
  2187. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  2188. timeout : Union[float, None]
  2189. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2190. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2191. no_wait_after : Union[bool, None]
  2192. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  2193. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  2194. navigating to inaccessible pages. Defaults to `false`.
  2195. Deprecated: This option will default to `true` in the future.
  2196. """
  2197. return mapping.from_maybe_impl(
  2198. await self._impl_obj.press(
  2199. key=key,
  2200. delay=delay,
  2201. timeout=to_milliseconds(timeout),
  2202. noWaitAfter=no_wait_after,
  2203. )
  2204. )
  2205. async def set_checked(
  2206. self,
  2207. checked: bool,
  2208. *,
  2209. position: typing.Optional[Position] = None,
  2210. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2211. force: typing.Optional[bool] = None,
  2212. no_wait_after: typing.Optional[bool] = None,
  2213. trial: typing.Optional[bool] = None,
  2214. ) -> None:
  2215. """ElementHandle.set_checked
  2216. This method checks or unchecks an element by performing the following steps:
  2217. 1. Ensure that element is a checkbox or a radio input. If not, this method throws.
  2218. 1. If the element already has the right checked state, this method returns immediately.
  2219. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  2220. the element is detached during the checks, the whole action is retried.
  2221. 1. Scroll the element into view if needed.
  2222. 1. Use `page.mouse` to click in the center of the element.
  2223. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  2224. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2225. Passing zero timeout disables this.
  2226. Parameters
  2227. ----------
  2228. checked : bool
  2229. Whether to check or uncheck the checkbox.
  2230. position : Union[{x: float, y: float}, None]
  2231. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2232. the element.
  2233. timeout : Union[float, None]
  2234. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2235. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2236. force : Union[bool, None]
  2237. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2238. no_wait_after : Union[bool, None]
  2239. This option has no effect.
  2240. Deprecated: This option has no effect.
  2241. trial : Union[bool, None]
  2242. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2243. to `false`. Useful to wait until the element is ready for the action without performing it.
  2244. """
  2245. return mapping.from_maybe_impl(
  2246. await self._impl_obj.set_checked(
  2247. checked=checked,
  2248. position=position,
  2249. timeout=to_milliseconds(timeout),
  2250. force=force,
  2251. noWaitAfter=no_wait_after,
  2252. trial=trial,
  2253. )
  2254. )
  2255. async def check(
  2256. self,
  2257. *,
  2258. position: typing.Optional[Position] = None,
  2259. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2260. force: typing.Optional[bool] = None,
  2261. no_wait_after: typing.Optional[bool] = None,
  2262. trial: typing.Optional[bool] = None,
  2263. ) -> None:
  2264. """ElementHandle.check
  2265. This method checks the element by performing the following steps:
  2266. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  2267. checked, this method returns immediately.
  2268. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  2269. 1. Scroll the element into view if needed.
  2270. 1. Use `page.mouse` to click in the center of the element.
  2271. 1. Ensure that the element is now checked. If not, this method throws.
  2272. If the element is detached from the DOM at any moment during the action, this method throws.
  2273. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2274. Passing zero timeout disables this.
  2275. Parameters
  2276. ----------
  2277. position : Union[{x: float, y: float}, None]
  2278. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2279. the element.
  2280. timeout : Union[float, None]
  2281. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2282. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2283. force : Union[bool, None]
  2284. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2285. no_wait_after : Union[bool, None]
  2286. This option has no effect.
  2287. Deprecated: This option has no effect.
  2288. trial : Union[bool, None]
  2289. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2290. to `false`. Useful to wait until the element is ready for the action without performing it.
  2291. """
  2292. return mapping.from_maybe_impl(
  2293. await self._impl_obj.check(
  2294. position=position,
  2295. timeout=to_milliseconds(timeout),
  2296. force=force,
  2297. noWaitAfter=no_wait_after,
  2298. trial=trial,
  2299. )
  2300. )
  2301. async def uncheck(
  2302. self,
  2303. *,
  2304. position: typing.Optional[Position] = None,
  2305. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2306. force: typing.Optional[bool] = None,
  2307. no_wait_after: typing.Optional[bool] = None,
  2308. trial: typing.Optional[bool] = None,
  2309. ) -> None:
  2310. """ElementHandle.uncheck
  2311. This method checks the element by performing the following steps:
  2312. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  2313. unchecked, this method returns immediately.
  2314. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  2315. 1. Scroll the element into view if needed.
  2316. 1. Use `page.mouse` to click in the center of the element.
  2317. 1. Ensure that the element is now unchecked. If not, this method throws.
  2318. If the element is detached from the DOM at any moment during the action, this method throws.
  2319. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2320. Passing zero timeout disables this.
  2321. Parameters
  2322. ----------
  2323. position : Union[{x: float, y: float}, None]
  2324. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2325. the element.
  2326. timeout : Union[float, None]
  2327. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2328. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2329. force : Union[bool, None]
  2330. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2331. no_wait_after : Union[bool, None]
  2332. This option has no effect.
  2333. Deprecated: This option has no effect.
  2334. trial : Union[bool, None]
  2335. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2336. to `false`. Useful to wait until the element is ready for the action without performing it.
  2337. """
  2338. return mapping.from_maybe_impl(
  2339. await self._impl_obj.uncheck(
  2340. position=position,
  2341. timeout=to_milliseconds(timeout),
  2342. force=force,
  2343. noWaitAfter=no_wait_after,
  2344. trial=trial,
  2345. )
  2346. )
  2347. async def bounding_box(self) -> typing.Optional[FloatRect]:
  2348. """ElementHandle.bounding_box
  2349. This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
  2350. calculated relative to the main frame viewport - which is usually the same as the browser window.
  2351. Scrolling affects the returned bounding box, similarly to
  2352. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2353. That means `x` and/or `y` may be negative.
  2354. Elements from child frames return the bounding box relative to the main frame, unlike the
  2355. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2356. Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
  2357. following snippet should click the center of the element.
  2358. **Usage**
  2359. ```py
  2360. box = await element_handle.bounding_box()
  2361. await page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
  2362. ```
  2363. Returns
  2364. -------
  2365. Union[{x: float, y: float, width: float, height: float}, None]
  2366. """
  2367. return mapping.from_impl_nullable(await self._impl_obj.bounding_box())
  2368. async def screenshot(
  2369. self,
  2370. *,
  2371. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2372. type: typing.Optional[Literal["jpeg", "png"]] = None,
  2373. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  2374. quality: typing.Optional[int] = None,
  2375. omit_background: typing.Optional[bool] = None,
  2376. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  2377. caret: typing.Optional[Literal["hide", "initial"]] = None,
  2378. scale: typing.Optional[Literal["css", "device"]] = None,
  2379. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  2380. mask_color: typing.Optional[str] = None,
  2381. style: typing.Optional[str] = None,
  2382. ) -> bytes:
  2383. """ElementHandle.screenshot
  2384. This method captures a screenshot of the page, clipped to the size and position of this particular element. If the
  2385. element is covered by other elements, it will not be actually visible on the screenshot. If the element is a
  2386. scrollable container, only the currently scrolled content will be visible on the screenshot.
  2387. This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
  2388. a screenshot. If the element is detached from DOM, the method throws an error.
  2389. Returns the buffer with the captured screenshot.
  2390. Parameters
  2391. ----------
  2392. timeout : Union[float, None]
  2393. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2394. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2395. type : Union["jpeg", "png", None]
  2396. Specify screenshot type, defaults to `png`.
  2397. path : Union[pathlib.Path, str, None]
  2398. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  2399. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  2400. won't be saved to the disk.
  2401. quality : Union[int, None]
  2402. The quality of the image, between 0-100. Not applicable to `png` images.
  2403. omit_background : Union[bool, None]
  2404. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  2405. Defaults to `false`.
  2406. animations : Union["allow", "disabled", None]
  2407. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  2408. treatment depending on their duration:
  2409. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  2410. - infinite animations are canceled to initial state, and then played over after the screenshot.
  2411. Defaults to `"allow"` that leaves animations untouched.
  2412. caret : Union["hide", "initial", None]
  2413. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  2414. changed. Defaults to `"hide"`.
  2415. scale : Union["css", "device", None]
  2416. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  2417. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  2418. screenshots of high-dpi devices will be twice as large or even larger.
  2419. Defaults to `"device"`.
  2420. mask : Union[Sequence[Locator], None]
  2421. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  2422. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  2423. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  2424. that.
  2425. mask_color : Union[str, None]
  2426. Specify the color of the overlay box for masked elements, in
  2427. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  2428. style : Union[str, None]
  2429. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  2430. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  2431. the Shadow DOM and applies to the inner frames.
  2432. Returns
  2433. -------
  2434. bytes
  2435. """
  2436. return mapping.from_maybe_impl(
  2437. await self._impl_obj.screenshot(
  2438. timeout=to_milliseconds(timeout),
  2439. type=type,
  2440. path=path,
  2441. quality=quality,
  2442. omitBackground=omit_background,
  2443. animations=animations,
  2444. caret=caret,
  2445. scale=scale,
  2446. mask=mapping.to_impl(mask),
  2447. maskColor=mask_color,
  2448. style=style,
  2449. )
  2450. )
  2451. async def query_selector(self, selector: str) -> typing.Optional["ElementHandle"]:
  2452. """ElementHandle.query_selector
  2453. The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
  2454. the selector, returns `null`.
  2455. Parameters
  2456. ----------
  2457. selector : str
  2458. A selector to query for.
  2459. Returns
  2460. -------
  2461. Union[ElementHandle, None]
  2462. """
  2463. return mapping.from_impl_nullable(
  2464. await self._impl_obj.query_selector(selector=selector)
  2465. )
  2466. async def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  2467. """ElementHandle.query_selector_all
  2468. The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
  2469. the selector, returns empty array.
  2470. Parameters
  2471. ----------
  2472. selector : str
  2473. A selector to query for.
  2474. Returns
  2475. -------
  2476. List[ElementHandle]
  2477. """
  2478. return mapping.from_impl_list(
  2479. await self._impl_obj.query_selector_all(selector=selector)
  2480. )
  2481. async def eval_on_selector(
  2482. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  2483. ) -> typing.Any:
  2484. """ElementHandle.eval_on_selector
  2485. Returns the return value of `expression`.
  2486. The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
  2487. first argument to `expression`. If no elements match the selector, the method throws an error.
  2488. If `expression` returns a [Promise], then `element_handle.eval_on_selector()` would wait for the promise to
  2489. resolve and return its value.
  2490. **Usage**
  2491. ```py
  2492. tweet_handle = await page.query_selector(\".tweet\")
  2493. assert await tweet_handle.eval_on_selector(\".like\", \"node => node.innerText\") == \"100\"
  2494. assert await tweet_handle.eval_on_selector(\".retweets\", \"node => node.innerText\") == \"10\"
  2495. ```
  2496. Parameters
  2497. ----------
  2498. selector : str
  2499. A selector to query for.
  2500. expression : str
  2501. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2502. function is automatically invoked.
  2503. arg : Union[Any, None]
  2504. Optional argument to pass to `expression`.
  2505. Returns
  2506. -------
  2507. Any
  2508. """
  2509. return mapping.from_maybe_impl(
  2510. await self._impl_obj.eval_on_selector(
  2511. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  2512. )
  2513. )
  2514. async def eval_on_selector_all(
  2515. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  2516. ) -> typing.Any:
  2517. """ElementHandle.eval_on_selector_all
  2518. Returns the return value of `expression`.
  2519. The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
  2520. of matched elements as a first argument to `expression`.
  2521. If `expression` returns a [Promise], then `element_handle.eval_on_selector_all()` would wait for the promise to
  2522. resolve and return its value.
  2523. **Usage**
  2524. ```html
  2525. <div class=\"feed\">
  2526. <div class=\"tweet\">Hello!</div>
  2527. <div class=\"tweet\">Hi!</div>
  2528. </div>
  2529. ```
  2530. ```py
  2531. feed_handle = await page.query_selector(\".feed\")
  2532. assert await feed_handle.eval_on_selector_all(\".tweet\", \"nodes => nodes.map(n => n.innerText)\") == [\"hello!\", \"hi!\"]
  2533. ```
  2534. Parameters
  2535. ----------
  2536. selector : str
  2537. A selector to query for.
  2538. expression : str
  2539. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2540. function is automatically invoked.
  2541. arg : Union[Any, None]
  2542. Optional argument to pass to `expression`.
  2543. Returns
  2544. -------
  2545. Any
  2546. """
  2547. return mapping.from_maybe_impl(
  2548. await self._impl_obj.eval_on_selector_all(
  2549. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  2550. )
  2551. )
  2552. async def wait_for_element_state(
  2553. self,
  2554. state: Literal[
  2555. "disabled", "editable", "enabled", "hidden", "stable", "visible"
  2556. ],
  2557. *,
  2558. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2559. ) -> None:
  2560. """ElementHandle.wait_for_element_state
  2561. Returns when the element satisfies the `state`.
  2562. Depending on the `state` parameter, this method waits for one of the [actionability](https://playwright.dev/python/docs/actionability) checks to
  2563. pass. This method throws when the element is detached while waiting, unless waiting for the `\"hidden\"` state.
  2564. - `\"visible\"` Wait until the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  2565. - `\"hidden\"` Wait until the element is [not visible](https://playwright.dev/python/docs/actionability#visible) or not attached. Note that
  2566. waiting for hidden does not throw when the element detaches.
  2567. - `\"stable\"` Wait until the element is both [visible](https://playwright.dev/python/docs/actionability#visible) and
  2568. [stable](https://playwright.dev/python/docs/actionability#stable).
  2569. - `\"enabled\"` Wait until the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  2570. - `\"disabled\"` Wait until the element is [not enabled](https://playwright.dev/python/docs/actionability#enabled).
  2571. - `\"editable\"` Wait until the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  2572. If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
  2573. Parameters
  2574. ----------
  2575. state : Union["disabled", "editable", "enabled", "hidden", "stable", "visible"]
  2576. A state to wait for, see below for more details.
  2577. timeout : Union[float, None]
  2578. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2579. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2580. """
  2581. return mapping.from_maybe_impl(
  2582. await self._impl_obj.wait_for_element_state(
  2583. state=state, timeout=to_milliseconds(timeout)
  2584. )
  2585. )
  2586. async def wait_for_selector(
  2587. self,
  2588. selector: str,
  2589. *,
  2590. state: typing.Optional[
  2591. Literal["attached", "detached", "hidden", "visible"]
  2592. ] = None,
  2593. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2594. strict: typing.Optional[bool] = None,
  2595. ) -> typing.Optional["ElementHandle"]:
  2596. """ElementHandle.wait_for_selector
  2597. Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
  2598. `detached`.
  2599. Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
  2600. or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
  2601. method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
  2602. function will throw.
  2603. **Usage**
  2604. ```py
  2605. await page.set_content(\"<div><span></span></div>\")
  2606. div = await page.query_selector(\"div\")
  2607. # waiting for the \"span\" selector relative to the div.
  2608. span = await div.wait_for_selector(\"span\", state=\"attached\")
  2609. ```
  2610. **NOTE** This method does not work across navigations, use `page.wait_for_selector()` instead.
  2611. Parameters
  2612. ----------
  2613. selector : str
  2614. A selector to query for.
  2615. state : Union["attached", "detached", "hidden", "visible", None]
  2616. Defaults to `'visible'`. Can be either:
  2617. - `'attached'` - wait for element to be present in DOM.
  2618. - `'detached'` - wait for element to not be present in DOM.
  2619. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  2620. without any content or with `display:none` has an empty bounding box and is not considered visible.
  2621. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  2622. `visibility:hidden`. This is opposite to the `'visible'` option.
  2623. timeout : Union[float, None]
  2624. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2625. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2626. strict : Union[bool, None]
  2627. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2628. element, the call throws an exception.
  2629. Returns
  2630. -------
  2631. Union[ElementHandle, None]
  2632. """
  2633. return mapping.from_impl_nullable(
  2634. await self._impl_obj.wait_for_selector(
  2635. selector=selector,
  2636. state=state,
  2637. timeout=to_milliseconds(timeout),
  2638. strict=strict,
  2639. )
  2640. )
  2641. mapping.register(ElementHandleImpl, ElementHandle)
  2642. class FileChooser(AsyncBase):
  2643. @property
  2644. def page(self) -> "Page":
  2645. """FileChooser.page
  2646. Returns page this file chooser belongs to.
  2647. Returns
  2648. -------
  2649. Page
  2650. """
  2651. return mapping.from_impl(self._impl_obj.page)
  2652. @property
  2653. def element(self) -> "ElementHandle":
  2654. """FileChooser.element
  2655. Returns input element associated with this file chooser.
  2656. Returns
  2657. -------
  2658. ElementHandle
  2659. """
  2660. return mapping.from_impl(self._impl_obj.element)
  2661. def is_multiple(self) -> bool:
  2662. """FileChooser.is_multiple
  2663. Returns whether this file chooser accepts multiple files.
  2664. Returns
  2665. -------
  2666. bool
  2667. """
  2668. return mapping.from_maybe_impl(self._impl_obj.is_multiple())
  2669. async def set_files(
  2670. self,
  2671. files: typing.Union[
  2672. str,
  2673. pathlib.Path,
  2674. FilePayload,
  2675. typing.Sequence[typing.Union[str, pathlib.Path]],
  2676. typing.Sequence[FilePayload],
  2677. ],
  2678. *,
  2679. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2680. no_wait_after: typing.Optional[bool] = None,
  2681. ) -> None:
  2682. """FileChooser.set_files
  2683. Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,
  2684. then they are resolved relative to the current working directory. For empty array, clears the selected files.
  2685. Parameters
  2686. ----------
  2687. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  2688. timeout : Union[float, None]
  2689. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2690. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2691. no_wait_after : Union[bool, None]
  2692. This option has no effect.
  2693. Deprecated: This option has no effect.
  2694. """
  2695. return mapping.from_maybe_impl(
  2696. await self._impl_obj.set_files(
  2697. files=mapping.to_impl(files),
  2698. timeout=to_milliseconds(timeout),
  2699. noWaitAfter=no_wait_after,
  2700. )
  2701. )
  2702. mapping.register(FileChooserImpl, FileChooser)
  2703. class Frame(AsyncBase):
  2704. @property
  2705. def page(self) -> "Page":
  2706. """Frame.page
  2707. Returns the page containing this frame.
  2708. Returns
  2709. -------
  2710. Page
  2711. """
  2712. return mapping.from_impl(self._impl_obj.page)
  2713. @property
  2714. def name(self) -> str:
  2715. """Frame.name
  2716. Returns frame's name attribute as specified in the tag.
  2717. If the name is empty, returns the id attribute instead.
  2718. **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed
  2719. later.
  2720. Returns
  2721. -------
  2722. str
  2723. """
  2724. return mapping.from_maybe_impl(self._impl_obj.name)
  2725. @property
  2726. def url(self) -> str:
  2727. """Frame.url
  2728. Returns frame's url.
  2729. Returns
  2730. -------
  2731. str
  2732. """
  2733. return mapping.from_maybe_impl(self._impl_obj.url)
  2734. @property
  2735. def parent_frame(self) -> typing.Optional["Frame"]:
  2736. """Frame.parent_frame
  2737. Parent frame, if any. Detached frames and main frames return `null`.
  2738. Returns
  2739. -------
  2740. Union[Frame, None]
  2741. """
  2742. return mapping.from_impl_nullable(self._impl_obj.parent_frame)
  2743. @property
  2744. def child_frames(self) -> typing.List["Frame"]:
  2745. """Frame.child_frames
  2746. Returns
  2747. -------
  2748. List[Frame]
  2749. """
  2750. return mapping.from_impl_list(self._impl_obj.child_frames)
  2751. async def goto(
  2752. self,
  2753. url: str,
  2754. *,
  2755. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2756. wait_until: typing.Optional[
  2757. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2758. ] = None,
  2759. referer: typing.Optional[str] = None,
  2760. ) -> typing.Optional["Response"]:
  2761. """Frame.goto
  2762. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  2763. the last redirect.
  2764. The method will throw an error if:
  2765. - there's an SSL error (e.g. in case of self-signed certificates).
  2766. - target URL is invalid.
  2767. - the `timeout` is exceeded during navigation.
  2768. - the remote server does not respond or is unreachable.
  2769. - the main resource failed to load.
  2770. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
  2771. \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
  2772. `response.status()`.
  2773. **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
  2774. to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
  2775. **NOTE** Headless mode doesn't support navigation to a PDF document. See the
  2776. [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
  2777. Parameters
  2778. ----------
  2779. url : str
  2780. URL to navigate frame to. The url should include scheme, e.g. `https://`.
  2781. timeout : Union[float, None]
  2782. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2783. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2784. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2785. `page.set_default_timeout()` methods.
  2786. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2787. When to consider operation succeeded, defaults to `load`. Events can be either:
  2788. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2789. - `'load'` - consider operation to be finished when the `load` event is fired.
  2790. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2791. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2792. - `'commit'` - consider operation to be finished when network response is received and the document started
  2793. loading.
  2794. referer : Union[str, None]
  2795. Referer header value. If provided it will take preference over the referer header value set by
  2796. `page.set_extra_http_headers()`.
  2797. Returns
  2798. -------
  2799. Union[Response, None]
  2800. """
  2801. return mapping.from_impl_nullable(
  2802. await self._impl_obj.goto(
  2803. url=url,
  2804. timeout=to_milliseconds(timeout),
  2805. waitUntil=wait_until,
  2806. referer=referer,
  2807. )
  2808. )
  2809. def expect_navigation(
  2810. self,
  2811. *,
  2812. url: typing.Optional[
  2813. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  2814. ] = None,
  2815. wait_until: typing.Optional[
  2816. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2817. ] = None,
  2818. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2819. ) -> AsyncEventContextManager["Response"]:
  2820. """Frame.expect_navigation
  2821. Waits for the frame navigation and returns the main resource response. In case of multiple redirects, the
  2822. navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
  2823. navigation due to History API usage, the navigation will resolve with `null`.
  2824. **Usage**
  2825. This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly
  2826. cause the frame to navigate. Consider this example:
  2827. ```py
  2828. async with frame.expect_navigation():
  2829. await frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  2830. # Resolves after navigation has finished
  2831. ```
  2832. **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
  2833. is considered a navigation.
  2834. Parameters
  2835. ----------
  2836. url : Union[Callable[[str], bool], Pattern[str], str, None]
  2837. A glob pattern, regex pattern, or predicate receiving [URL] to match while waiting for the navigation. Note that if
  2838. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  2839. equal to the string.
  2840. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2841. When to consider operation succeeded, defaults to `load`. Events can be either:
  2842. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2843. - `'load'` - consider operation to be finished when the `load` event is fired.
  2844. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2845. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2846. - `'commit'` - consider operation to be finished when network response is received and the document started
  2847. loading.
  2848. timeout : Union[float, None]
  2849. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2850. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2851. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2852. `page.set_default_timeout()` methods.
  2853. Returns
  2854. -------
  2855. EventContextManager[Response]
  2856. """
  2857. return AsyncEventContextManager(
  2858. self._impl_obj.expect_navigation(
  2859. url=self._wrap_handler(url),
  2860. waitUntil=wait_until,
  2861. timeout=to_milliseconds(timeout),
  2862. ).future
  2863. )
  2864. async def wait_for_url(
  2865. self,
  2866. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  2867. *,
  2868. wait_until: typing.Optional[
  2869. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2870. ] = None,
  2871. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2872. ) -> None:
  2873. """Frame.wait_for_url
  2874. Waits for the frame to navigate to the given URL.
  2875. **Usage**
  2876. ```py
  2877. await frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  2878. await frame.wait_for_url(\"**/target.html\")
  2879. ```
  2880. Parameters
  2881. ----------
  2882. url : Union[Callable[[str], bool], Pattern[str], str]
  2883. A glob pattern, regex pattern, or predicate receiving [URL] to match while waiting for the navigation. Note that if
  2884. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  2885. equal to the string.
  2886. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2887. When to consider operation succeeded, defaults to `load`. Events can be either:
  2888. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2889. - `'load'` - consider operation to be finished when the `load` event is fired.
  2890. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2891. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2892. - `'commit'` - consider operation to be finished when network response is received and the document started
  2893. loading.
  2894. timeout : Union[float, None]
  2895. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2896. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2897. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2898. `page.set_default_timeout()` methods.
  2899. """
  2900. return mapping.from_maybe_impl(
  2901. await self._impl_obj.wait_for_url(
  2902. url=self._wrap_handler(url),
  2903. waitUntil=wait_until,
  2904. timeout=to_milliseconds(timeout),
  2905. )
  2906. )
  2907. async def wait_for_load_state(
  2908. self,
  2909. state: typing.Optional[
  2910. Literal["domcontentloaded", "load", "networkidle"]
  2911. ] = None,
  2912. *,
  2913. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  2914. ) -> None:
  2915. """Frame.wait_for_load_state
  2916. Waits for the required load state to be reached.
  2917. This returns when the frame reaches a required load state, `load` by default. The navigation must have been
  2918. committed when this method is called. If current document has already reached the required state, resolves
  2919. immediately.
  2920. **NOTE** Most of the time, this method is not needed because Playwright
  2921. [auto-waits before every action](https://playwright.dev/python/docs/actionability).
  2922. **Usage**
  2923. ```py
  2924. await frame.click(\"button\") # click triggers navigation.
  2925. await frame.wait_for_load_state() # the promise resolves after \"load\" event.
  2926. ```
  2927. Parameters
  2928. ----------
  2929. state : Union["domcontentloaded", "load", "networkidle", None]
  2930. Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
  2931. document, the method resolves immediately. Can be one of:
  2932. - `'load'` - wait for the `load` event to be fired.
  2933. - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
  2934. - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
  2935. this method for testing, rely on web assertions to assess readiness instead.
  2936. timeout : Union[float, None]
  2937. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2938. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2939. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2940. `page.set_default_timeout()` methods.
  2941. """
  2942. return mapping.from_maybe_impl(
  2943. await self._impl_obj.wait_for_load_state(
  2944. state=state, timeout=to_milliseconds(timeout)
  2945. )
  2946. )
  2947. async def frame_element(self) -> "ElementHandle":
  2948. """Frame.frame_element
  2949. Returns the `frame` or `iframe` element handle which corresponds to this frame.
  2950. This is an inverse of `element_handle.content_frame()`. Note that returned handle actually belongs to the
  2951. parent frame.
  2952. This method throws an error if the frame has been detached before `frameElement()` returns.
  2953. **Usage**
  2954. ```py
  2955. frame_element = await frame.frame_element()
  2956. content_frame = await frame_element.content_frame()
  2957. assert frame == content_frame
  2958. ```
  2959. Returns
  2960. -------
  2961. ElementHandle
  2962. """
  2963. return mapping.from_impl(await self._impl_obj.frame_element())
  2964. async def evaluate(
  2965. self, expression: str, arg: typing.Optional[typing.Any] = None
  2966. ) -> typing.Any:
  2967. """Frame.evaluate
  2968. Returns the return value of `expression`.
  2969. If the function passed to the `frame.evaluate()` returns a [Promise], then `frame.evaluate()` would
  2970. wait for the promise to resolve and return its value.
  2971. If the function passed to the `frame.evaluate()` returns a non-[Serializable] value, then
  2972. `frame.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
  2973. are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  2974. **Usage**
  2975. ```py
  2976. result = await frame.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
  2977. print(result) # prints \"56\"
  2978. ```
  2979. A string can also be passed in instead of a function.
  2980. ```py
  2981. print(await frame.evaluate(\"1 + 2\")) # prints \"3\"
  2982. x = 10
  2983. print(await frame.evaluate(f\"1 + {x}\")) # prints \"11\"
  2984. ```
  2985. `ElementHandle` instances can be passed as an argument to the `frame.evaluate()`:
  2986. ```py
  2987. body_handle = await frame.evaluate(\"document.body\")
  2988. html = await frame.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
  2989. await body_handle.dispose()
  2990. ```
  2991. Parameters
  2992. ----------
  2993. expression : str
  2994. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2995. function is automatically invoked.
  2996. arg : Union[Any, None]
  2997. Optional argument to pass to `expression`.
  2998. Returns
  2999. -------
  3000. Any
  3001. """
  3002. return mapping.from_maybe_impl(
  3003. await self._impl_obj.evaluate(
  3004. expression=expression, arg=mapping.to_impl(arg)
  3005. )
  3006. )
  3007. async def evaluate_handle(
  3008. self, expression: str, arg: typing.Optional[typing.Any] = None
  3009. ) -> "JSHandle":
  3010. """Frame.evaluate_handle
  3011. Returns the return value of `expression` as a `JSHandle`.
  3012. The only difference between `frame.evaluate()` and `frame.evaluate_handle()` is that
  3013. `frame.evaluate_handle()` returns `JSHandle`.
  3014. If the function, passed to the `frame.evaluate_handle()`, returns a [Promise], then
  3015. `frame.evaluate_handle()` would wait for the promise to resolve and return its value.
  3016. **Usage**
  3017. ```py
  3018. a_window_handle = await frame.evaluate_handle(\"Promise.resolve(window)\")
  3019. a_window_handle # handle for the window object.
  3020. ```
  3021. A string can also be passed in instead of a function.
  3022. ```py
  3023. a_handle = await page.evaluate_handle(\"document\") # handle for the \"document\"
  3024. ```
  3025. `JSHandle` instances can be passed as an argument to the `frame.evaluate_handle()`:
  3026. ```py
  3027. a_handle = await page.evaluate_handle(\"document.body\")
  3028. result_handle = await page.evaluate_handle(\"body => body.innerHTML\", a_handle)
  3029. print(await result_handle.json_value())
  3030. await result_handle.dispose()
  3031. ```
  3032. Parameters
  3033. ----------
  3034. expression : str
  3035. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3036. function is automatically invoked.
  3037. arg : Union[Any, None]
  3038. Optional argument to pass to `expression`.
  3039. Returns
  3040. -------
  3041. JSHandle
  3042. """
  3043. return mapping.from_impl(
  3044. await self._impl_obj.evaluate_handle(
  3045. expression=expression, arg=mapping.to_impl(arg)
  3046. )
  3047. )
  3048. async def query_selector(
  3049. self, selector: str, *, strict: typing.Optional[bool] = None
  3050. ) -> typing.Optional["ElementHandle"]:
  3051. """Frame.query_selector
  3052. Returns the ElementHandle pointing to the frame element.
  3053. **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects and web-first assertions instead.
  3054. The method finds an element matching the specified selector within the frame. If no elements match the selector,
  3055. returns `null`.
  3056. Parameters
  3057. ----------
  3058. selector : str
  3059. A selector to query for.
  3060. strict : Union[bool, None]
  3061. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3062. element, the call throws an exception.
  3063. Returns
  3064. -------
  3065. Union[ElementHandle, None]
  3066. """
  3067. return mapping.from_impl_nullable(
  3068. await self._impl_obj.query_selector(selector=selector, strict=strict)
  3069. )
  3070. async def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  3071. """Frame.query_selector_all
  3072. Returns the ElementHandles pointing to the frame elements.
  3073. **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects instead.
  3074. The method finds all elements matching the specified selector within the frame. If no elements match the selector,
  3075. returns empty array.
  3076. Parameters
  3077. ----------
  3078. selector : str
  3079. A selector to query for.
  3080. Returns
  3081. -------
  3082. List[ElementHandle]
  3083. """
  3084. return mapping.from_impl_list(
  3085. await self._impl_obj.query_selector_all(selector=selector)
  3086. )
  3087. async def wait_for_selector(
  3088. self,
  3089. selector: str,
  3090. *,
  3091. strict: typing.Optional[bool] = None,
  3092. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3093. state: typing.Optional[
  3094. Literal["attached", "detached", "hidden", "visible"]
  3095. ] = None,
  3096. ) -> typing.Optional["ElementHandle"]:
  3097. """Frame.wait_for_selector
  3098. Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
  3099. `detached`.
  3100. **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
  3101. objects and web-first assertions make the code wait-for-selector-free.
  3102. Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
  3103. at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
  3104. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
  3105. **Usage**
  3106. This method works across navigations:
  3107. ```py
  3108. import asyncio
  3109. from playwright.async_api import async_playwright, Playwright
  3110. async def run(playwright: Playwright):
  3111. chromium = playwright.chromium
  3112. browser = await chromium.launch()
  3113. page = await browser.new_page()
  3114. for current_url in [\"https://google.com\", \"https://bbc.com\"]:
  3115. await page.goto(current_url, wait_until=\"domcontentloaded\")
  3116. element = await page.main_frame.wait_for_selector(\"img\")
  3117. print(\"Loaded image: \" + str(await element.get_attribute(\"src\")))
  3118. await browser.close()
  3119. async def main():
  3120. async with async_playwright() as playwright:
  3121. await run(playwright)
  3122. asyncio.run(main())
  3123. ```
  3124. Parameters
  3125. ----------
  3126. selector : str
  3127. A selector to query for.
  3128. strict : Union[bool, None]
  3129. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3130. element, the call throws an exception.
  3131. timeout : Union[float, None]
  3132. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3133. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3134. state : Union["attached", "detached", "hidden", "visible", None]
  3135. Defaults to `'visible'`. Can be either:
  3136. - `'attached'` - wait for element to be present in DOM.
  3137. - `'detached'` - wait for element to not be present in DOM.
  3138. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  3139. without any content or with `display:none` has an empty bounding box and is not considered visible.
  3140. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  3141. `visibility:hidden`. This is opposite to the `'visible'` option.
  3142. Returns
  3143. -------
  3144. Union[ElementHandle, None]
  3145. """
  3146. return mapping.from_impl_nullable(
  3147. await self._impl_obj.wait_for_selector(
  3148. selector=selector,
  3149. strict=strict,
  3150. timeout=to_milliseconds(timeout),
  3151. state=state,
  3152. )
  3153. )
  3154. async def is_checked(
  3155. self,
  3156. selector: str,
  3157. *,
  3158. strict: typing.Optional[bool] = None,
  3159. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3160. ) -> bool:
  3161. """Frame.is_checked
  3162. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  3163. Parameters
  3164. ----------
  3165. selector : str
  3166. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3167. used.
  3168. strict : Union[bool, None]
  3169. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3170. element, the call throws an exception.
  3171. timeout : Union[float, None]
  3172. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3173. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3174. Returns
  3175. -------
  3176. bool
  3177. """
  3178. return mapping.from_maybe_impl(
  3179. await self._impl_obj.is_checked(
  3180. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  3181. )
  3182. )
  3183. async def is_disabled(
  3184. self,
  3185. selector: str,
  3186. *,
  3187. strict: typing.Optional[bool] = None,
  3188. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3189. ) -> bool:
  3190. """Frame.is_disabled
  3191. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  3192. Parameters
  3193. ----------
  3194. selector : str
  3195. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3196. used.
  3197. strict : Union[bool, None]
  3198. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3199. element, the call throws an exception.
  3200. timeout : Union[float, None]
  3201. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3202. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3203. Returns
  3204. -------
  3205. bool
  3206. """
  3207. return mapping.from_maybe_impl(
  3208. await self._impl_obj.is_disabled(
  3209. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  3210. )
  3211. )
  3212. async def is_editable(
  3213. self,
  3214. selector: str,
  3215. *,
  3216. strict: typing.Optional[bool] = None,
  3217. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3218. ) -> bool:
  3219. """Frame.is_editable
  3220. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  3221. Parameters
  3222. ----------
  3223. selector : str
  3224. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3225. used.
  3226. strict : Union[bool, None]
  3227. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3228. element, the call throws an exception.
  3229. timeout : Union[float, None]
  3230. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3231. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3232. Returns
  3233. -------
  3234. bool
  3235. """
  3236. return mapping.from_maybe_impl(
  3237. await self._impl_obj.is_editable(
  3238. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  3239. )
  3240. )
  3241. async def is_enabled(
  3242. self,
  3243. selector: str,
  3244. *,
  3245. strict: typing.Optional[bool] = None,
  3246. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3247. ) -> bool:
  3248. """Frame.is_enabled
  3249. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  3250. Parameters
  3251. ----------
  3252. selector : str
  3253. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3254. used.
  3255. strict : Union[bool, None]
  3256. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3257. element, the call throws an exception.
  3258. timeout : Union[float, None]
  3259. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3260. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3261. Returns
  3262. -------
  3263. bool
  3264. """
  3265. return mapping.from_maybe_impl(
  3266. await self._impl_obj.is_enabled(
  3267. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  3268. )
  3269. )
  3270. async def is_hidden(
  3271. self, selector: str, *, strict: typing.Optional[bool] = None
  3272. ) -> bool:
  3273. """Frame.is_hidden
  3274. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
  3275. does not match any elements is considered hidden.
  3276. Parameters
  3277. ----------
  3278. selector : str
  3279. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3280. used.
  3281. strict : Union[bool, None]
  3282. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3283. element, the call throws an exception.
  3284. Returns
  3285. -------
  3286. bool
  3287. """
  3288. return mapping.from_maybe_impl(
  3289. await self._impl_obj.is_hidden(selector=selector, strict=strict)
  3290. )
  3291. async def is_visible(
  3292. self, selector: str, *, strict: typing.Optional[bool] = None
  3293. ) -> bool:
  3294. """Frame.is_visible
  3295. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
  3296. is considered not visible.
  3297. Parameters
  3298. ----------
  3299. selector : str
  3300. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3301. used.
  3302. strict : Union[bool, None]
  3303. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3304. element, the call throws an exception.
  3305. Returns
  3306. -------
  3307. bool
  3308. """
  3309. return mapping.from_maybe_impl(
  3310. await self._impl_obj.is_visible(selector=selector, strict=strict)
  3311. )
  3312. async def dispatch_event(
  3313. self,
  3314. selector: str,
  3315. type: str,
  3316. event_init: typing.Optional[typing.Dict] = None,
  3317. *,
  3318. strict: typing.Optional[bool] = None,
  3319. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3320. ) -> None:
  3321. """Frame.dispatch_event
  3322. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  3323. `click` is dispatched. This is equivalent to calling
  3324. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  3325. **Usage**
  3326. ```py
  3327. await frame.dispatch_event(\"button#submit\", \"click\")
  3328. ```
  3329. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  3330. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  3331. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  3332. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  3333. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  3334. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  3335. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  3336. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  3337. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  3338. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  3339. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  3340. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  3341. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  3342. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  3343. ```py
  3344. # note you can only create data_transfer in chromium and firefox
  3345. data_transfer = await frame.evaluate_handle(\"new DataTransfer()\")
  3346. await frame.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
  3347. ```
  3348. Parameters
  3349. ----------
  3350. selector : str
  3351. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3352. used.
  3353. type : str
  3354. DOM event type: `"click"`, `"dragstart"`, etc.
  3355. event_init : Union[Dict, None]
  3356. Optional event-specific initialization properties.
  3357. strict : Union[bool, None]
  3358. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3359. element, the call throws an exception.
  3360. timeout : Union[float, None]
  3361. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3362. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3363. """
  3364. return mapping.from_maybe_impl(
  3365. await self._impl_obj.dispatch_event(
  3366. selector=selector,
  3367. type=type,
  3368. eventInit=mapping.to_impl(event_init),
  3369. strict=strict,
  3370. timeout=to_milliseconds(timeout),
  3371. )
  3372. )
  3373. async def eval_on_selector(
  3374. self,
  3375. selector: str,
  3376. expression: str,
  3377. arg: typing.Optional[typing.Any] = None,
  3378. *,
  3379. strict: typing.Optional[bool] = None,
  3380. ) -> typing.Any:
  3381. """Frame.eval_on_selector
  3382. Returns the return value of `expression`.
  3383. The method finds an element matching the specified selector within the frame and passes it as a first argument to
  3384. `expression`. If no elements match the selector, the method throws an error.
  3385. If `expression` returns a [Promise], then `frame.eval_on_selector()` would wait for the promise to resolve
  3386. and return its value.
  3387. **Usage**
  3388. ```py
  3389. search_value = await frame.eval_on_selector(\"#search\", \"el => el.value\")
  3390. preload_href = await frame.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
  3391. html = await frame.eval_on_selector(\".main-container\", \"(e, suffix) => e.outerHTML + suffix\", \"hello\")
  3392. ```
  3393. Parameters
  3394. ----------
  3395. selector : str
  3396. A selector to query for.
  3397. expression : str
  3398. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3399. function is automatically invoked.
  3400. arg : Union[Any, None]
  3401. Optional argument to pass to `expression`.
  3402. strict : Union[bool, None]
  3403. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3404. element, the call throws an exception.
  3405. Returns
  3406. -------
  3407. Any
  3408. """
  3409. return mapping.from_maybe_impl(
  3410. await self._impl_obj.eval_on_selector(
  3411. selector=selector,
  3412. expression=expression,
  3413. arg=mapping.to_impl(arg),
  3414. strict=strict,
  3415. )
  3416. )
  3417. async def eval_on_selector_all(
  3418. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  3419. ) -> typing.Any:
  3420. """Frame.eval_on_selector_all
  3421. Returns the return value of `expression`.
  3422. The method finds all elements matching the specified selector within the frame and passes an array of matched
  3423. elements as a first argument to `expression`.
  3424. If `expression` returns a [Promise], then `frame.eval_on_selector_all()` would wait for the promise to resolve
  3425. and return its value.
  3426. **Usage**
  3427. ```py
  3428. divs_counts = await frame.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
  3429. ```
  3430. Parameters
  3431. ----------
  3432. selector : str
  3433. A selector to query for.
  3434. expression : str
  3435. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3436. function is automatically invoked.
  3437. arg : Union[Any, None]
  3438. Optional argument to pass to `expression`.
  3439. Returns
  3440. -------
  3441. Any
  3442. """
  3443. return mapping.from_maybe_impl(
  3444. await self._impl_obj.eval_on_selector_all(
  3445. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  3446. )
  3447. )
  3448. async def content(self) -> str:
  3449. """Frame.content
  3450. Gets the full HTML contents of the frame, including the doctype.
  3451. Returns
  3452. -------
  3453. str
  3454. """
  3455. return mapping.from_maybe_impl(await self._impl_obj.content())
  3456. async def set_content(
  3457. self,
  3458. html: str,
  3459. *,
  3460. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3461. wait_until: typing.Optional[
  3462. Literal["commit", "domcontentloaded", "load", "networkidle"]
  3463. ] = None,
  3464. ) -> None:
  3465. """Frame.set_content
  3466. This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
  3467. inheriting all its specific characteristics and behaviors.
  3468. Parameters
  3469. ----------
  3470. html : str
  3471. HTML markup to assign to the page.
  3472. timeout : Union[float, None]
  3473. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  3474. be changed by using the `browser_context.set_default_navigation_timeout()`,
  3475. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  3476. `page.set_default_timeout()` methods.
  3477. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  3478. When to consider operation succeeded, defaults to `load`. Events can be either:
  3479. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  3480. - `'load'` - consider operation to be finished when the `load` event is fired.
  3481. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  3482. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  3483. - `'commit'` - consider operation to be finished when network response is received and the document started
  3484. loading.
  3485. """
  3486. return mapping.from_maybe_impl(
  3487. await self._impl_obj.set_content(
  3488. html=html, timeout=to_milliseconds(timeout), waitUntil=wait_until
  3489. )
  3490. )
  3491. def is_detached(self) -> bool:
  3492. """Frame.is_detached
  3493. Returns `true` if the frame has been detached, or `false` otherwise.
  3494. Returns
  3495. -------
  3496. bool
  3497. """
  3498. return mapping.from_maybe_impl(self._impl_obj.is_detached())
  3499. async def add_script_tag(
  3500. self,
  3501. *,
  3502. url: typing.Optional[str] = None,
  3503. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  3504. content: typing.Optional[str] = None,
  3505. type: typing.Optional[str] = None,
  3506. ) -> "ElementHandle":
  3507. """Frame.add_script_tag
  3508. Returns the added tag when the script's onload fires or when the script content was injected into frame.
  3509. Adds a `<script>` tag into the page with the desired url or content.
  3510. Parameters
  3511. ----------
  3512. url : Union[str, None]
  3513. URL of a script to be added.
  3514. path : Union[pathlib.Path, str, None]
  3515. Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
  3516. to the current working directory.
  3517. content : Union[str, None]
  3518. Raw JavaScript content to be injected into frame.
  3519. type : Union[str, None]
  3520. Script type. Use 'module' in order to load a JavaScript ES6 module. See
  3521. [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
  3522. Returns
  3523. -------
  3524. ElementHandle
  3525. """
  3526. return mapping.from_impl(
  3527. await self._impl_obj.add_script_tag(
  3528. url=url, path=path, content=content, type=type
  3529. )
  3530. )
  3531. async def add_style_tag(
  3532. self,
  3533. *,
  3534. url: typing.Optional[str] = None,
  3535. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  3536. content: typing.Optional[str] = None,
  3537. ) -> "ElementHandle":
  3538. """Frame.add_style_tag
  3539. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
  3540. Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
  3541. content.
  3542. Parameters
  3543. ----------
  3544. url : Union[str, None]
  3545. URL of the `<link>` tag.
  3546. path : Union[pathlib.Path, str, None]
  3547. Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
  3548. current working directory.
  3549. content : Union[str, None]
  3550. Raw CSS content to be injected into frame.
  3551. Returns
  3552. -------
  3553. ElementHandle
  3554. """
  3555. return mapping.from_impl(
  3556. await self._impl_obj.add_style_tag(url=url, path=path, content=content)
  3557. )
  3558. async def click(
  3559. self,
  3560. selector: str,
  3561. *,
  3562. modifiers: typing.Optional[
  3563. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3564. ] = None,
  3565. position: typing.Optional[Position] = None,
  3566. delay: typing.Optional[float] = None,
  3567. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  3568. click_count: typing.Optional[int] = None,
  3569. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3570. force: typing.Optional[bool] = None,
  3571. no_wait_after: typing.Optional[bool] = None,
  3572. strict: typing.Optional[bool] = None,
  3573. trial: typing.Optional[bool] = None,
  3574. ) -> None:
  3575. """Frame.click
  3576. This method clicks an element matching `selector` by performing the following steps:
  3577. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3578. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3579. the element is detached during the checks, the whole action is retried.
  3580. 1. Scroll the element into view if needed.
  3581. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  3582. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  3583. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3584. Passing zero timeout disables this.
  3585. Parameters
  3586. ----------
  3587. selector : str
  3588. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3589. used.
  3590. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3591. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3592. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3593. "Control" on Windows and Linux and to "Meta" on macOS.
  3594. position : Union[{x: float, y: float}, None]
  3595. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3596. the element.
  3597. delay : Union[float, None]
  3598. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  3599. button : Union["left", "middle", "right", None]
  3600. Defaults to `left`.
  3601. click_count : Union[int, None]
  3602. defaults to 1. See [UIEvent.detail].
  3603. timeout : Union[float, None]
  3604. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3605. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3606. force : Union[bool, None]
  3607. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3608. no_wait_after : Union[bool, None]
  3609. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  3610. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  3611. navigating to inaccessible pages. Defaults to `false`.
  3612. Deprecated: This option will default to `true` in the future.
  3613. strict : Union[bool, None]
  3614. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3615. element, the call throws an exception.
  3616. trial : Union[bool, None]
  3617. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3618. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3619. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3620. are pressed.
  3621. """
  3622. return mapping.from_maybe_impl(
  3623. await self._impl_obj.click(
  3624. selector=selector,
  3625. modifiers=mapping.to_impl(modifiers),
  3626. position=position,
  3627. delay=delay,
  3628. button=button,
  3629. clickCount=click_count,
  3630. timeout=to_milliseconds(timeout),
  3631. force=force,
  3632. noWaitAfter=no_wait_after,
  3633. strict=strict,
  3634. trial=trial,
  3635. )
  3636. )
  3637. async def dblclick(
  3638. self,
  3639. selector: str,
  3640. *,
  3641. modifiers: typing.Optional[
  3642. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3643. ] = None,
  3644. position: typing.Optional[Position] = None,
  3645. delay: typing.Optional[float] = None,
  3646. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  3647. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3648. force: typing.Optional[bool] = None,
  3649. no_wait_after: typing.Optional[bool] = None,
  3650. strict: typing.Optional[bool] = None,
  3651. trial: typing.Optional[bool] = None,
  3652. ) -> None:
  3653. """Frame.dblclick
  3654. This method double clicks an element matching `selector` by performing the following steps:
  3655. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3656. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3657. the element is detached during the checks, the whole action is retried.
  3658. 1. Scroll the element into view if needed.
  3659. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`. if
  3660. the first click of the `dblclick()` triggers a navigation event, this method will throw.
  3661. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3662. Passing zero timeout disables this.
  3663. **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
  3664. Parameters
  3665. ----------
  3666. selector : str
  3667. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3668. used.
  3669. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3670. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3671. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3672. "Control" on Windows and Linux and to "Meta" on macOS.
  3673. position : Union[{x: float, y: float}, None]
  3674. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3675. the element.
  3676. delay : Union[float, None]
  3677. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  3678. button : Union["left", "middle", "right", None]
  3679. Defaults to `left`.
  3680. timeout : Union[float, None]
  3681. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3682. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3683. force : Union[bool, None]
  3684. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3685. no_wait_after : Union[bool, None]
  3686. This option has no effect.
  3687. Deprecated: This option has no effect.
  3688. strict : Union[bool, None]
  3689. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3690. element, the call throws an exception.
  3691. trial : Union[bool, None]
  3692. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3693. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3694. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3695. are pressed.
  3696. """
  3697. return mapping.from_maybe_impl(
  3698. await self._impl_obj.dblclick(
  3699. selector=selector,
  3700. modifiers=mapping.to_impl(modifiers),
  3701. position=position,
  3702. delay=delay,
  3703. button=button,
  3704. timeout=to_milliseconds(timeout),
  3705. force=force,
  3706. noWaitAfter=no_wait_after,
  3707. strict=strict,
  3708. trial=trial,
  3709. )
  3710. )
  3711. async def tap(
  3712. self,
  3713. selector: str,
  3714. *,
  3715. modifiers: typing.Optional[
  3716. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3717. ] = None,
  3718. position: typing.Optional[Position] = None,
  3719. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3720. force: typing.Optional[bool] = None,
  3721. no_wait_after: typing.Optional[bool] = None,
  3722. strict: typing.Optional[bool] = None,
  3723. trial: typing.Optional[bool] = None,
  3724. ) -> None:
  3725. """Frame.tap
  3726. This method taps an element matching `selector` by performing the following steps:
  3727. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3728. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3729. the element is detached during the checks, the whole action is retried.
  3730. 1. Scroll the element into view if needed.
  3731. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  3732. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3733. Passing zero timeout disables this.
  3734. **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
  3735. Parameters
  3736. ----------
  3737. selector : str
  3738. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3739. used.
  3740. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3741. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3742. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3743. "Control" on Windows and Linux and to "Meta" on macOS.
  3744. position : Union[{x: float, y: float}, None]
  3745. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3746. the element.
  3747. timeout : Union[float, None]
  3748. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3749. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3750. force : Union[bool, None]
  3751. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3752. no_wait_after : Union[bool, None]
  3753. This option has no effect.
  3754. Deprecated: This option has no effect.
  3755. strict : Union[bool, None]
  3756. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3757. element, the call throws an exception.
  3758. trial : Union[bool, None]
  3759. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3760. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3761. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3762. are pressed.
  3763. """
  3764. return mapping.from_maybe_impl(
  3765. await self._impl_obj.tap(
  3766. selector=selector,
  3767. modifiers=mapping.to_impl(modifiers),
  3768. position=position,
  3769. timeout=to_milliseconds(timeout),
  3770. force=force,
  3771. noWaitAfter=no_wait_after,
  3772. strict=strict,
  3773. trial=trial,
  3774. )
  3775. )
  3776. async def fill(
  3777. self,
  3778. selector: str,
  3779. value: str,
  3780. *,
  3781. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  3782. no_wait_after: typing.Optional[bool] = None,
  3783. strict: typing.Optional[bool] = None,
  3784. force: typing.Optional[bool] = None,
  3785. ) -> None:
  3786. """Frame.fill
  3787. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
  3788. focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
  3789. to clear the input field.
  3790. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  3791. error. However, if the element is inside the `<label>` element that has an associated
  3792. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  3793. instead.
  3794. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  3795. Parameters
  3796. ----------
  3797. selector : str
  3798. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3799. used.
  3800. value : str
  3801. Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
  3802. timeout : Union[float, None]
  3803. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3804. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3805. no_wait_after : Union[bool, None]
  3806. This option has no effect.
  3807. Deprecated: This option has no effect.
  3808. strict : Union[bool, None]
  3809. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3810. element, the call throws an exception.
  3811. force : Union[bool, None]
  3812. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3813. """
  3814. return mapping.from_maybe_impl(
  3815. await self._impl_obj.fill(
  3816. selector=selector,
  3817. value=value,
  3818. timeout=to_milliseconds(timeout),
  3819. noWaitAfter=no_wait_after,
  3820. strict=strict,
  3821. force=force,
  3822. )
  3823. )
  3824. def locator(
  3825. self,
  3826. selector: str,
  3827. *,
  3828. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3829. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3830. has: typing.Optional["Locator"] = None,
  3831. has_not: typing.Optional["Locator"] = None,
  3832. ) -> "Locator":
  3833. """Frame.locator
  3834. The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
  3835. to the element immediately before performing an action, so a series of actions on the same locator can in fact be
  3836. performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
  3837. [Learn more about locators](https://playwright.dev/python/docs/locators).
  3838. [Learn more about locators](https://playwright.dev/python/docs/locators).
  3839. Parameters
  3840. ----------
  3841. selector : str
  3842. A selector to use when resolving DOM element.
  3843. has_text : Union[Pattern[str], str, None]
  3844. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  3845. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  3846. `<article><div>Playwright</div></article>`.
  3847. has_not_text : Union[Pattern[str], str, None]
  3848. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  3849. When passed a [string], matching is case-insensitive and searches for a substring.
  3850. has : Union[Locator, None]
  3851. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  3852. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  3853. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  3854. the document root. For example, you can find `content` that has `div` in
  3855. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  3856. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  3857. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  3858. has_not : Union[Locator, None]
  3859. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  3860. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  3861. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  3862. Returns
  3863. -------
  3864. Locator
  3865. """
  3866. return mapping.from_impl(
  3867. self._impl_obj.locator(
  3868. selector=selector,
  3869. hasText=has_text,
  3870. hasNotText=has_not_text,
  3871. has=has._impl_obj if has else None,
  3872. hasNot=has_not._impl_obj if has_not else None,
  3873. )
  3874. )
  3875. def get_by_alt_text(
  3876. self,
  3877. text: typing.Union[str, typing.Pattern[str]],
  3878. *,
  3879. exact: typing.Optional[bool] = None,
  3880. ) -> "Locator":
  3881. """Frame.get_by_alt_text
  3882. Allows locating elements by their alt text.
  3883. **Usage**
  3884. For example, this method will find the image by alt text \"Playwright logo\":
  3885. ```html
  3886. <img alt='Playwright logo'>
  3887. ```
  3888. ```py
  3889. await page.get_by_alt_text(\"Playwright logo\").click()
  3890. ```
  3891. Parameters
  3892. ----------
  3893. text : Union[Pattern[str], str]
  3894. Text to locate the element for.
  3895. exact : Union[bool, None]
  3896. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3897. regular expression. Note that exact match still trims whitespace.
  3898. Returns
  3899. -------
  3900. Locator
  3901. """
  3902. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  3903. def get_by_label(
  3904. self,
  3905. text: typing.Union[str, typing.Pattern[str]],
  3906. *,
  3907. exact: typing.Optional[bool] = None,
  3908. ) -> "Locator":
  3909. """Frame.get_by_label
  3910. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  3911. `aria-label` attribute.
  3912. **Usage**
  3913. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  3914. ```html
  3915. <input aria-label=\"Username\">
  3916. <label for=\"password-input\">Password:</label>
  3917. <input id=\"password-input\">
  3918. ```
  3919. ```py
  3920. await page.get_by_label(\"Username\").fill(\"john\")
  3921. await page.get_by_label(\"Password\").fill(\"secret\")
  3922. ```
  3923. Parameters
  3924. ----------
  3925. text : Union[Pattern[str], str]
  3926. Text to locate the element for.
  3927. exact : Union[bool, None]
  3928. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3929. regular expression. Note that exact match still trims whitespace.
  3930. Returns
  3931. -------
  3932. Locator
  3933. """
  3934. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  3935. def get_by_placeholder(
  3936. self,
  3937. text: typing.Union[str, typing.Pattern[str]],
  3938. *,
  3939. exact: typing.Optional[bool] = None,
  3940. ) -> "Locator":
  3941. """Frame.get_by_placeholder
  3942. Allows locating input elements by the placeholder text.
  3943. **Usage**
  3944. For example, consider the following DOM structure.
  3945. ```html
  3946. <input type=\"email\" placeholder=\"name@example.com\" />
  3947. ```
  3948. You can fill the input after locating it by the placeholder text:
  3949. ```py
  3950. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  3951. ```
  3952. Parameters
  3953. ----------
  3954. text : Union[Pattern[str], str]
  3955. Text to locate the element for.
  3956. exact : Union[bool, None]
  3957. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3958. regular expression. Note that exact match still trims whitespace.
  3959. Returns
  3960. -------
  3961. Locator
  3962. """
  3963. return mapping.from_impl(
  3964. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  3965. )
  3966. def get_by_role(
  3967. self,
  3968. role: Literal[
  3969. "alert",
  3970. "alertdialog",
  3971. "application",
  3972. "article",
  3973. "banner",
  3974. "blockquote",
  3975. "button",
  3976. "caption",
  3977. "cell",
  3978. "checkbox",
  3979. "code",
  3980. "columnheader",
  3981. "combobox",
  3982. "complementary",
  3983. "contentinfo",
  3984. "definition",
  3985. "deletion",
  3986. "dialog",
  3987. "directory",
  3988. "document",
  3989. "emphasis",
  3990. "feed",
  3991. "figure",
  3992. "form",
  3993. "generic",
  3994. "grid",
  3995. "gridcell",
  3996. "group",
  3997. "heading",
  3998. "img",
  3999. "insertion",
  4000. "link",
  4001. "list",
  4002. "listbox",
  4003. "listitem",
  4004. "log",
  4005. "main",
  4006. "marquee",
  4007. "math",
  4008. "menu",
  4009. "menubar",
  4010. "menuitem",
  4011. "menuitemcheckbox",
  4012. "menuitemradio",
  4013. "meter",
  4014. "navigation",
  4015. "none",
  4016. "note",
  4017. "option",
  4018. "paragraph",
  4019. "presentation",
  4020. "progressbar",
  4021. "radio",
  4022. "radiogroup",
  4023. "region",
  4024. "row",
  4025. "rowgroup",
  4026. "rowheader",
  4027. "scrollbar",
  4028. "search",
  4029. "searchbox",
  4030. "separator",
  4031. "slider",
  4032. "spinbutton",
  4033. "status",
  4034. "strong",
  4035. "subscript",
  4036. "superscript",
  4037. "switch",
  4038. "tab",
  4039. "table",
  4040. "tablist",
  4041. "tabpanel",
  4042. "term",
  4043. "textbox",
  4044. "time",
  4045. "timer",
  4046. "toolbar",
  4047. "tooltip",
  4048. "tree",
  4049. "treegrid",
  4050. "treeitem",
  4051. ],
  4052. *,
  4053. checked: typing.Optional[bool] = None,
  4054. disabled: typing.Optional[bool] = None,
  4055. expanded: typing.Optional[bool] = None,
  4056. include_hidden: typing.Optional[bool] = None,
  4057. level: typing.Optional[int] = None,
  4058. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  4059. pressed: typing.Optional[bool] = None,
  4060. selected: typing.Optional[bool] = None,
  4061. exact: typing.Optional[bool] = None,
  4062. description: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  4063. ) -> "Locator":
  4064. """Frame.get_by_role
  4065. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  4066. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  4067. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  4068. **Usage**
  4069. Consider the following DOM structure.
  4070. ```html
  4071. <h3>Sign up</h3>
  4072. <label>
  4073. <input type=\"checkbox\" /> Subscribe
  4074. </label>
  4075. <br/>
  4076. <button>Submit</button>
  4077. ```
  4078. You can locate each element by its implicit role:
  4079. ```py
  4080. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  4081. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  4082. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  4083. ```
  4084. **Details**
  4085. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  4086. about the ARIA guidelines.
  4087. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  4088. that is recognized by the role selector. You can find all the
  4089. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  4090. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  4091. Parameters
  4092. ----------
  4093. 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"]
  4094. Required aria role.
  4095. checked : Union[bool, None]
  4096. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  4097. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  4098. disabled : Union[bool, None]
  4099. An attribute that is usually set by `aria-disabled` or `disabled`.
  4100. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  4101. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  4102. expanded : Union[bool, None]
  4103. An attribute that is usually set by `aria-expanded`.
  4104. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  4105. include_hidden : Union[bool, None]
  4106. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  4107. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  4108. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  4109. level : Union[int, None]
  4110. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  4111. for `<h1>-<h6>` elements.
  4112. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  4113. name : Union[Pattern[str], str, None]
  4114. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  4115. case-insensitive and searches for a substring, use `exact` to control this behavior.
  4116. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  4117. pressed : Union[bool, None]
  4118. An attribute that is usually set by `aria-pressed`.
  4119. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  4120. selected : Union[bool, None]
  4121. An attribute that is usually set by `aria-selected`.
  4122. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  4123. exact : Union[bool, None]
  4124. Whether `name` and `description` are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored
  4125. when the value is a regular expression. Note that exact match still trims whitespace.
  4126. description : Union[Pattern[str], str, None]
  4127. Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By
  4128. default, matching is case-insensitive and searches for a substring, use `exact` to control this behavior.
  4129. Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  4130. Returns
  4131. -------
  4132. Locator
  4133. """
  4134. return mapping.from_impl(
  4135. self._impl_obj.get_by_role(
  4136. role=role,
  4137. checked=checked,
  4138. disabled=disabled,
  4139. expanded=expanded,
  4140. includeHidden=include_hidden,
  4141. level=level,
  4142. name=name,
  4143. pressed=pressed,
  4144. selected=selected,
  4145. exact=exact,
  4146. description=description,
  4147. )
  4148. )
  4149. def get_by_test_id(
  4150. self, test_id: typing.Union[str, typing.Pattern[str]]
  4151. ) -> "Locator":
  4152. """Frame.get_by_test_id
  4153. Locate element by the test id.
  4154. **Usage**
  4155. Consider the following DOM structure.
  4156. ```html
  4157. <button data-testid=\"directions\">Itinéraire</button>
  4158. ```
  4159. You can locate the element by its test id:
  4160. ```py
  4161. await page.get_by_test_id(\"directions\").click()
  4162. ```
  4163. **Details**
  4164. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  4165. configure a different test id attribute if necessary.
  4166. Parameters
  4167. ----------
  4168. test_id : Union[Pattern[str], str]
  4169. Id to locate the element by.
  4170. Returns
  4171. -------
  4172. Locator
  4173. """
  4174. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  4175. def get_by_text(
  4176. self,
  4177. text: typing.Union[str, typing.Pattern[str]],
  4178. *,
  4179. exact: typing.Optional[bool] = None,
  4180. ) -> "Locator":
  4181. """Frame.get_by_text
  4182. Allows locating elements that contain given text.
  4183. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  4184. filter by the text content.
  4185. **Usage**
  4186. Consider the following DOM structure:
  4187. ```html
  4188. <div>Hello <span>world</span></div>
  4189. <div>Hello</div>
  4190. ```
  4191. You can locate by text substring, exact string, or a regular expression:
  4192. ```py
  4193. # Matches <span>
  4194. page.get_by_text(\"world\")
  4195. # Matches first <div>
  4196. page.get_by_text(\"Hello world\")
  4197. # Matches second <div>
  4198. page.get_by_text(\"Hello\", exact=True)
  4199. # Matches both <div>s
  4200. page.get_by_text(re.compile(\"Hello\"))
  4201. # Matches second <div>
  4202. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  4203. ```
  4204. **Details**
  4205. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  4206. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  4207. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  4208. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  4209. Parameters
  4210. ----------
  4211. text : Union[Pattern[str], str]
  4212. Text to locate the element for.
  4213. exact : Union[bool, None]
  4214. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4215. regular expression. Note that exact match still trims whitespace.
  4216. Returns
  4217. -------
  4218. Locator
  4219. """
  4220. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  4221. def get_by_title(
  4222. self,
  4223. text: typing.Union[str, typing.Pattern[str]],
  4224. *,
  4225. exact: typing.Optional[bool] = None,
  4226. ) -> "Locator":
  4227. """Frame.get_by_title
  4228. Allows locating elements by their title attribute.
  4229. **Usage**
  4230. Consider the following DOM structure.
  4231. ```html
  4232. <span title='Issues count'>25 issues</span>
  4233. ```
  4234. You can check the issues count after locating it by the title text:
  4235. ```py
  4236. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  4237. ```
  4238. Parameters
  4239. ----------
  4240. text : Union[Pattern[str], str]
  4241. Text to locate the element for.
  4242. exact : Union[bool, None]
  4243. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4244. regular expression. Note that exact match still trims whitespace.
  4245. Returns
  4246. -------
  4247. Locator
  4248. """
  4249. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  4250. def frame_locator(self, selector: str) -> "FrameLocator":
  4251. """Frame.frame_locator
  4252. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  4253. in that iframe.
  4254. **Usage**
  4255. Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
  4256. id=\"my-frame\">`:
  4257. ```py
  4258. locator = frame.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
  4259. await locator.click()
  4260. ```
  4261. Parameters
  4262. ----------
  4263. selector : str
  4264. A selector to use when resolving DOM element.
  4265. Returns
  4266. -------
  4267. FrameLocator
  4268. """
  4269. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  4270. async def focus(
  4271. self,
  4272. selector: str,
  4273. *,
  4274. strict: typing.Optional[bool] = None,
  4275. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4276. ) -> None:
  4277. """Frame.focus
  4278. This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
  4279. method waits until a matching element appears in the DOM.
  4280. Parameters
  4281. ----------
  4282. selector : str
  4283. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4284. used.
  4285. strict : Union[bool, None]
  4286. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4287. element, the call throws an exception.
  4288. timeout : Union[float, None]
  4289. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4290. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4291. """
  4292. return mapping.from_maybe_impl(
  4293. await self._impl_obj.focus(
  4294. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  4295. )
  4296. )
  4297. async def text_content(
  4298. self,
  4299. selector: str,
  4300. *,
  4301. strict: typing.Optional[bool] = None,
  4302. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4303. ) -> typing.Optional[str]:
  4304. """Frame.text_content
  4305. Returns `element.textContent`.
  4306. Parameters
  4307. ----------
  4308. selector : str
  4309. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4310. used.
  4311. strict : Union[bool, None]
  4312. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4313. element, the call throws an exception.
  4314. timeout : Union[float, None]
  4315. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4316. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4317. Returns
  4318. -------
  4319. Union[str, None]
  4320. """
  4321. return mapping.from_maybe_impl(
  4322. await self._impl_obj.text_content(
  4323. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  4324. )
  4325. )
  4326. async def inner_text(
  4327. self,
  4328. selector: str,
  4329. *,
  4330. strict: typing.Optional[bool] = None,
  4331. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4332. ) -> str:
  4333. """Frame.inner_text
  4334. Returns `element.innerText`.
  4335. Parameters
  4336. ----------
  4337. selector : str
  4338. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4339. used.
  4340. strict : Union[bool, None]
  4341. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4342. element, the call throws an exception.
  4343. timeout : Union[float, None]
  4344. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4345. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4346. Returns
  4347. -------
  4348. str
  4349. """
  4350. return mapping.from_maybe_impl(
  4351. await self._impl_obj.inner_text(
  4352. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  4353. )
  4354. )
  4355. async def inner_html(
  4356. self,
  4357. selector: str,
  4358. *,
  4359. strict: typing.Optional[bool] = None,
  4360. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4361. ) -> str:
  4362. """Frame.inner_html
  4363. Returns `element.innerHTML`.
  4364. Parameters
  4365. ----------
  4366. selector : str
  4367. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4368. used.
  4369. strict : Union[bool, None]
  4370. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4371. element, the call throws an exception.
  4372. timeout : Union[float, None]
  4373. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4374. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4375. Returns
  4376. -------
  4377. str
  4378. """
  4379. return mapping.from_maybe_impl(
  4380. await self._impl_obj.inner_html(
  4381. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  4382. )
  4383. )
  4384. async def get_attribute(
  4385. self,
  4386. selector: str,
  4387. name: str,
  4388. *,
  4389. strict: typing.Optional[bool] = None,
  4390. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4391. ) -> typing.Optional[str]:
  4392. """Frame.get_attribute
  4393. Returns element attribute value.
  4394. Parameters
  4395. ----------
  4396. selector : str
  4397. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4398. used.
  4399. name : str
  4400. Attribute name to get the value for.
  4401. strict : Union[bool, None]
  4402. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4403. element, the call throws an exception.
  4404. timeout : Union[float, None]
  4405. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4406. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4407. Returns
  4408. -------
  4409. Union[str, None]
  4410. """
  4411. return mapping.from_maybe_impl(
  4412. await self._impl_obj.get_attribute(
  4413. selector=selector,
  4414. name=name,
  4415. strict=strict,
  4416. timeout=to_milliseconds(timeout),
  4417. )
  4418. )
  4419. async def hover(
  4420. self,
  4421. selector: str,
  4422. *,
  4423. modifiers: typing.Optional[
  4424. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  4425. ] = None,
  4426. position: typing.Optional[Position] = None,
  4427. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4428. no_wait_after: typing.Optional[bool] = None,
  4429. force: typing.Optional[bool] = None,
  4430. strict: typing.Optional[bool] = None,
  4431. trial: typing.Optional[bool] = None,
  4432. ) -> None:
  4433. """Frame.hover
  4434. This method hovers over an element matching `selector` by performing the following steps:
  4435. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4436. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4437. the element is detached during the checks, the whole action is retried.
  4438. 1. Scroll the element into view if needed.
  4439. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  4440. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4441. Passing zero timeout disables this.
  4442. Parameters
  4443. ----------
  4444. selector : str
  4445. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4446. used.
  4447. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  4448. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  4449. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  4450. "Control" on Windows and Linux and to "Meta" on macOS.
  4451. position : Union[{x: float, y: float}, None]
  4452. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4453. the element.
  4454. timeout : Union[float, None]
  4455. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4456. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4457. no_wait_after : Union[bool, None]
  4458. This option has no effect.
  4459. Deprecated: This option has no effect.
  4460. force : Union[bool, None]
  4461. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4462. strict : Union[bool, None]
  4463. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4464. element, the call throws an exception.
  4465. trial : Union[bool, None]
  4466. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4467. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  4468. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  4469. are pressed.
  4470. """
  4471. return mapping.from_maybe_impl(
  4472. await self._impl_obj.hover(
  4473. selector=selector,
  4474. modifiers=mapping.to_impl(modifiers),
  4475. position=position,
  4476. timeout=to_milliseconds(timeout),
  4477. noWaitAfter=no_wait_after,
  4478. force=force,
  4479. strict=strict,
  4480. trial=trial,
  4481. )
  4482. )
  4483. async def drag_and_drop(
  4484. self,
  4485. source: str,
  4486. target: str,
  4487. *,
  4488. source_position: typing.Optional[Position] = None,
  4489. target_position: typing.Optional[Position] = None,
  4490. force: typing.Optional[bool] = None,
  4491. no_wait_after: typing.Optional[bool] = None,
  4492. strict: typing.Optional[bool] = None,
  4493. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4494. trial: typing.Optional[bool] = None,
  4495. steps: typing.Optional[int] = None,
  4496. ) -> None:
  4497. """Frame.drag_and_drop
  4498. Parameters
  4499. ----------
  4500. source : str
  4501. A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
  4502. be used.
  4503. target : str
  4504. A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
  4505. will be used.
  4506. source_position : Union[{x: float, y: float}, None]
  4507. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  4508. specified, some visible point of the element is used.
  4509. target_position : Union[{x: float, y: float}, None]
  4510. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  4511. specified, some visible point of the element is used.
  4512. force : Union[bool, None]
  4513. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4514. no_wait_after : Union[bool, None]
  4515. This option has no effect.
  4516. Deprecated: This option has no effect.
  4517. strict : Union[bool, None]
  4518. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4519. element, the call throws an exception.
  4520. timeout : Union[float, None]
  4521. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4522. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4523. trial : Union[bool, None]
  4524. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4525. to `false`. Useful to wait until the element is ready for the action without performing it.
  4526. steps : Union[int, None]
  4527. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  4528. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  4529. """
  4530. return mapping.from_maybe_impl(
  4531. await self._impl_obj.drag_and_drop(
  4532. source=source,
  4533. target=target,
  4534. sourcePosition=source_position,
  4535. targetPosition=target_position,
  4536. force=force,
  4537. noWaitAfter=no_wait_after,
  4538. strict=strict,
  4539. timeout=to_milliseconds(timeout),
  4540. trial=trial,
  4541. steps=steps,
  4542. )
  4543. )
  4544. async def select_option(
  4545. self,
  4546. selector: str,
  4547. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  4548. *,
  4549. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  4550. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  4551. element: typing.Optional[
  4552. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  4553. ] = None,
  4554. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4555. no_wait_after: typing.Optional[bool] = None,
  4556. strict: typing.Optional[bool] = None,
  4557. force: typing.Optional[bool] = None,
  4558. ) -> typing.List[str]:
  4559. """Frame.select_option
  4560. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
  4561. until all specified options are present in the `<select>` element and selects these options.
  4562. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  4563. the `<label>` element that has an associated
  4564. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  4565. instead.
  4566. Returns the array of option values that have been successfully selected.
  4567. Triggers a `change` and `input` event once all the provided options have been selected.
  4568. **Usage**
  4569. ```py
  4570. # Single selection matching the value or label
  4571. await frame.select_option(\"select#colors\", \"blue\")
  4572. # single selection matching the label
  4573. await frame.select_option(\"select#colors\", label=\"blue\")
  4574. # multiple selection
  4575. await frame.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
  4576. ```
  4577. Parameters
  4578. ----------
  4579. selector : str
  4580. A selector to query for.
  4581. value : Union[Sequence[str], str, None]
  4582. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  4583. otherwise only the first option matching one of the passed options is selected. Optional.
  4584. index : Union[Sequence[int], int, None]
  4585. Options to select by index. Optional.
  4586. label : Union[Sequence[str], str, None]
  4587. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  4588. otherwise only the first option matching one of the passed options is selected. Optional.
  4589. element : Union[ElementHandle, Sequence[ElementHandle], None]
  4590. Option elements to select. Optional.
  4591. timeout : Union[float, None]
  4592. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4593. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4594. no_wait_after : Union[bool, None]
  4595. This option has no effect.
  4596. Deprecated: This option has no effect.
  4597. strict : Union[bool, None]
  4598. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4599. element, the call throws an exception.
  4600. force : Union[bool, None]
  4601. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4602. Returns
  4603. -------
  4604. List[str]
  4605. """
  4606. return mapping.from_maybe_impl(
  4607. await self._impl_obj.select_option(
  4608. selector=selector,
  4609. value=mapping.to_impl(value),
  4610. index=mapping.to_impl(index),
  4611. label=mapping.to_impl(label),
  4612. element=mapping.to_impl(element),
  4613. timeout=to_milliseconds(timeout),
  4614. noWaitAfter=no_wait_after,
  4615. strict=strict,
  4616. force=force,
  4617. )
  4618. )
  4619. async def input_value(
  4620. self,
  4621. selector: str,
  4622. *,
  4623. strict: typing.Optional[bool] = None,
  4624. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4625. ) -> str:
  4626. """Frame.input_value
  4627. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  4628. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  4629. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  4630. control.
  4631. Parameters
  4632. ----------
  4633. selector : str
  4634. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4635. used.
  4636. strict : Union[bool, None]
  4637. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4638. element, the call throws an exception.
  4639. timeout : Union[float, None]
  4640. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4641. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4642. Returns
  4643. -------
  4644. str
  4645. """
  4646. return mapping.from_maybe_impl(
  4647. await self._impl_obj.input_value(
  4648. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  4649. )
  4650. )
  4651. async def set_input_files(
  4652. self,
  4653. selector: str,
  4654. files: typing.Union[
  4655. str,
  4656. pathlib.Path,
  4657. FilePayload,
  4658. typing.Sequence[typing.Union[str, pathlib.Path]],
  4659. typing.Sequence[FilePayload],
  4660. ],
  4661. *,
  4662. strict: typing.Optional[bool] = None,
  4663. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4664. no_wait_after: typing.Optional[bool] = None,
  4665. ) -> None:
  4666. """Frame.set_input_files
  4667. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  4668. they are resolved relative to the current working directory. For empty array, clears the selected files.
  4669. This method expects `selector` to point to an
  4670. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  4671. the `<label>` element that has an associated
  4672. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  4673. Parameters
  4674. ----------
  4675. selector : str
  4676. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4677. used.
  4678. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  4679. strict : Union[bool, None]
  4680. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4681. element, the call throws an exception.
  4682. timeout : Union[float, None]
  4683. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4684. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4685. no_wait_after : Union[bool, None]
  4686. This option has no effect.
  4687. Deprecated: This option has no effect.
  4688. """
  4689. return mapping.from_maybe_impl(
  4690. await self._impl_obj.set_input_files(
  4691. selector=selector,
  4692. files=mapping.to_impl(files),
  4693. strict=strict,
  4694. timeout=to_milliseconds(timeout),
  4695. noWaitAfter=no_wait_after,
  4696. )
  4697. )
  4698. async def type(
  4699. self,
  4700. selector: str,
  4701. text: str,
  4702. *,
  4703. delay: typing.Optional[float] = None,
  4704. strict: typing.Optional[bool] = None,
  4705. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4706. no_wait_after: typing.Optional[bool] = None,
  4707. ) -> None:
  4708. """Frame.type
  4709. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used
  4710. to send fine-grained keyboard events. To fill values in form fields, use `frame.fill()`.
  4711. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  4712. **Usage**
  4713. Parameters
  4714. ----------
  4715. selector : str
  4716. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4717. used.
  4718. text : str
  4719. A text to type into a focused element.
  4720. delay : Union[float, None]
  4721. Time to wait between key presses in milliseconds. Defaults to 0.
  4722. strict : Union[bool, None]
  4723. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4724. element, the call throws an exception.
  4725. timeout : Union[float, None]
  4726. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4727. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4728. no_wait_after : Union[bool, None]
  4729. This option has no effect.
  4730. Deprecated: This option has no effect.
  4731. """
  4732. return mapping.from_maybe_impl(
  4733. await self._impl_obj.type(
  4734. selector=selector,
  4735. text=text,
  4736. delay=delay,
  4737. strict=strict,
  4738. timeout=to_milliseconds(timeout),
  4739. noWaitAfter=no_wait_after,
  4740. )
  4741. )
  4742. async def press(
  4743. self,
  4744. selector: str,
  4745. key: str,
  4746. *,
  4747. delay: typing.Optional[float] = None,
  4748. strict: typing.Optional[bool] = None,
  4749. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4750. no_wait_after: typing.Optional[bool] = None,
  4751. ) -> None:
  4752. """Frame.press
  4753. `key` can specify the intended
  4754. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  4755. to generate the text for. A superset of the `key` values can be found
  4756. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  4757. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  4758. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  4759. etc.
  4760. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  4761. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  4762. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  4763. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  4764. texts.
  4765. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  4766. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  4767. Parameters
  4768. ----------
  4769. selector : str
  4770. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4771. used.
  4772. key : str
  4773. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  4774. delay : Union[float, None]
  4775. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  4776. strict : Union[bool, None]
  4777. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4778. element, the call throws an exception.
  4779. timeout : Union[float, None]
  4780. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4781. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4782. no_wait_after : Union[bool, None]
  4783. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  4784. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  4785. navigating to inaccessible pages. Defaults to `false`.
  4786. Deprecated: This option will default to `true` in the future.
  4787. """
  4788. return mapping.from_maybe_impl(
  4789. await self._impl_obj.press(
  4790. selector=selector,
  4791. key=key,
  4792. delay=delay,
  4793. strict=strict,
  4794. timeout=to_milliseconds(timeout),
  4795. noWaitAfter=no_wait_after,
  4796. )
  4797. )
  4798. async def check(
  4799. self,
  4800. selector: str,
  4801. *,
  4802. position: typing.Optional[Position] = None,
  4803. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4804. force: typing.Optional[bool] = None,
  4805. no_wait_after: typing.Optional[bool] = None,
  4806. strict: typing.Optional[bool] = None,
  4807. trial: typing.Optional[bool] = None,
  4808. ) -> None:
  4809. """Frame.check
  4810. This method checks an element matching `selector` by performing the following steps:
  4811. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4812. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  4813. already checked, this method returns immediately.
  4814. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4815. the element is detached during the checks, the whole action is retried.
  4816. 1. Scroll the element into view if needed.
  4817. 1. Use `page.mouse` to click in the center of the element.
  4818. 1. Ensure that the element is now checked. If not, this method throws.
  4819. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4820. Passing zero timeout disables this.
  4821. Parameters
  4822. ----------
  4823. selector : str
  4824. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4825. used.
  4826. position : Union[{x: float, y: float}, None]
  4827. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4828. the element.
  4829. timeout : Union[float, None]
  4830. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4831. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4832. force : Union[bool, None]
  4833. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4834. no_wait_after : Union[bool, None]
  4835. This option has no effect.
  4836. Deprecated: This option has no effect.
  4837. strict : Union[bool, None]
  4838. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4839. element, the call throws an exception.
  4840. trial : Union[bool, None]
  4841. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4842. to `false`. Useful to wait until the element is ready for the action without performing it.
  4843. """
  4844. return mapping.from_maybe_impl(
  4845. await self._impl_obj.check(
  4846. selector=selector,
  4847. position=position,
  4848. timeout=to_milliseconds(timeout),
  4849. force=force,
  4850. noWaitAfter=no_wait_after,
  4851. strict=strict,
  4852. trial=trial,
  4853. )
  4854. )
  4855. async def uncheck(
  4856. self,
  4857. selector: str,
  4858. *,
  4859. position: typing.Optional[Position] = None,
  4860. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4861. force: typing.Optional[bool] = None,
  4862. no_wait_after: typing.Optional[bool] = None,
  4863. strict: typing.Optional[bool] = None,
  4864. trial: typing.Optional[bool] = None,
  4865. ) -> None:
  4866. """Frame.uncheck
  4867. This method checks an element matching `selector` by performing the following steps:
  4868. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4869. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  4870. already unchecked, this method returns immediately.
  4871. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4872. the element is detached during the checks, the whole action is retried.
  4873. 1. Scroll the element into view if needed.
  4874. 1. Use `page.mouse` to click in the center of the element.
  4875. 1. Ensure that the element is now unchecked. If not, this method throws.
  4876. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4877. Passing zero timeout disables this.
  4878. Parameters
  4879. ----------
  4880. selector : str
  4881. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4882. used.
  4883. position : Union[{x: float, y: float}, None]
  4884. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4885. the element.
  4886. timeout : Union[float, None]
  4887. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4888. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4889. force : Union[bool, None]
  4890. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4891. no_wait_after : Union[bool, None]
  4892. This option has no effect.
  4893. Deprecated: This option has no effect.
  4894. strict : Union[bool, None]
  4895. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4896. element, the call throws an exception.
  4897. trial : Union[bool, None]
  4898. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4899. to `false`. Useful to wait until the element is ready for the action without performing it.
  4900. """
  4901. return mapping.from_maybe_impl(
  4902. await self._impl_obj.uncheck(
  4903. selector=selector,
  4904. position=position,
  4905. timeout=to_milliseconds(timeout),
  4906. force=force,
  4907. noWaitAfter=no_wait_after,
  4908. strict=strict,
  4909. trial=trial,
  4910. )
  4911. )
  4912. async def wait_for_timeout(
  4913. self, timeout: typing.Union[float, datetime.timedelta]
  4914. ) -> None:
  4915. """Frame.wait_for_timeout
  4916. Waits for the given `timeout` in milliseconds.
  4917. Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
  4918. to be flaky. Use signals such as network events, selectors becoming visible and others instead.
  4919. Parameters
  4920. ----------
  4921. timeout : float
  4922. A timeout to wait for
  4923. """
  4924. return mapping.from_maybe_impl(
  4925. await self._impl_obj.wait_for_timeout(timeout=to_milliseconds(timeout))
  4926. )
  4927. async def wait_for_function(
  4928. self,
  4929. expression: str,
  4930. *,
  4931. arg: typing.Optional[typing.Any] = None,
  4932. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  4933. polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
  4934. ) -> "JSHandle":
  4935. """Frame.wait_for_function
  4936. Returns when the `expression` returns a truthy value, returns that value.
  4937. **Usage**
  4938. The `frame.wait_for_function()` can be used to observe viewport size change:
  4939. ```py
  4940. import asyncio
  4941. from playwright.async_api import async_playwright, Playwright
  4942. async def run(playwright: Playwright):
  4943. webkit = playwright.webkit
  4944. browser = await webkit.launch()
  4945. page = await browser.new_page()
  4946. await page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
  4947. await page.main_frame.wait_for_function(\"() => window.x > 0\")
  4948. await browser.close()
  4949. async def main():
  4950. async with async_playwright() as playwright:
  4951. await run(playwright)
  4952. asyncio.run(main())
  4953. ```
  4954. To pass an argument to the predicate of `frame.waitForFunction` function:
  4955. ```py
  4956. selector = \".foo\"
  4957. await frame.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
  4958. ```
  4959. Parameters
  4960. ----------
  4961. expression : str
  4962. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  4963. function is automatically invoked.
  4964. arg : Union[Any, None]
  4965. Optional argument to pass to `expression`.
  4966. timeout : Union[float, None]
  4967. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  4968. default value can be changed by using the `browser_context.set_default_timeout()` or
  4969. `page.set_default_timeout()` methods.
  4970. polling : Union["raf", float, None]
  4971. If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
  4972. is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
  4973. `raf`.
  4974. Returns
  4975. -------
  4976. JSHandle
  4977. """
  4978. return mapping.from_impl(
  4979. await self._impl_obj.wait_for_function(
  4980. expression=expression,
  4981. arg=mapping.to_impl(arg),
  4982. timeout=to_milliseconds(timeout),
  4983. polling=polling,
  4984. )
  4985. )
  4986. async def title(self) -> str:
  4987. """Frame.title
  4988. Returns the page title.
  4989. Returns
  4990. -------
  4991. str
  4992. """
  4993. return mapping.from_maybe_impl(await self._impl_obj.title())
  4994. async def set_checked(
  4995. self,
  4996. selector: str,
  4997. checked: bool,
  4998. *,
  4999. position: typing.Optional[Position] = None,
  5000. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  5001. force: typing.Optional[bool] = None,
  5002. no_wait_after: typing.Optional[bool] = None,
  5003. strict: typing.Optional[bool] = None,
  5004. trial: typing.Optional[bool] = None,
  5005. ) -> None:
  5006. """Frame.set_checked
  5007. This method checks or unchecks an element matching `selector` by performing the following steps:
  5008. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  5009. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  5010. 1. If the element already has the right checked state, this method returns immediately.
  5011. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  5012. the element is detached during the checks, the whole action is retried.
  5013. 1. Scroll the element into view if needed.
  5014. 1. Use `page.mouse` to click in the center of the element.
  5015. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  5016. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  5017. Passing zero timeout disables this.
  5018. Parameters
  5019. ----------
  5020. selector : str
  5021. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  5022. used.
  5023. checked : bool
  5024. Whether to check or uncheck the checkbox.
  5025. position : Union[{x: float, y: float}, None]
  5026. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  5027. the element.
  5028. timeout : Union[float, None]
  5029. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  5030. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  5031. force : Union[bool, None]
  5032. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  5033. no_wait_after : Union[bool, None]
  5034. This option has no effect.
  5035. Deprecated: This option has no effect.
  5036. strict : Union[bool, None]
  5037. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  5038. element, the call throws an exception.
  5039. trial : Union[bool, None]
  5040. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  5041. to `false`. Useful to wait until the element is ready for the action without performing it.
  5042. """
  5043. return mapping.from_maybe_impl(
  5044. await self._impl_obj.set_checked(
  5045. selector=selector,
  5046. checked=checked,
  5047. position=position,
  5048. timeout=to_milliseconds(timeout),
  5049. force=force,
  5050. noWaitAfter=no_wait_after,
  5051. strict=strict,
  5052. trial=trial,
  5053. )
  5054. )
  5055. mapping.register(FrameImpl, Frame)
  5056. class FrameLocator(AsyncBase):
  5057. @property
  5058. def first(self) -> "FrameLocator":
  5059. """FrameLocator.first
  5060. Returns locator to the first matching frame.
  5061. Returns
  5062. -------
  5063. FrameLocator
  5064. """
  5065. return mapping.from_impl(self._impl_obj.first)
  5066. @property
  5067. def last(self) -> "FrameLocator":
  5068. """FrameLocator.last
  5069. Returns locator to the last matching frame.
  5070. Returns
  5071. -------
  5072. FrameLocator
  5073. """
  5074. return mapping.from_impl(self._impl_obj.last)
  5075. @property
  5076. def owner(self) -> "Locator":
  5077. """FrameLocator.owner
  5078. Returns a `Locator` object pointing to the same `iframe` as this frame locator.
  5079. Useful when you have a `FrameLocator` object obtained somewhere, and later on would like to interact with the
  5080. `iframe` element.
  5081. For a reverse operation, use `locator.content_frame()`.
  5082. **Usage**
  5083. ```py
  5084. frame_locator = page.locator(\"iframe[name=\\\"embedded\\\"]\").content_frame
  5085. # ...
  5086. locator = frame_locator.owner
  5087. await expect(locator).to_be_visible()
  5088. ```
  5089. Returns
  5090. -------
  5091. Locator
  5092. """
  5093. return mapping.from_impl(self._impl_obj.owner)
  5094. def locator(
  5095. self,
  5096. selector_or_locator: typing.Union["Locator", str],
  5097. *,
  5098. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5099. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5100. has: typing.Optional["Locator"] = None,
  5101. has_not: typing.Optional["Locator"] = None,
  5102. ) -> "Locator":
  5103. """FrameLocator.locator
  5104. The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
  5105. options, similar to `locator.filter()` method.
  5106. [Learn more about locators](https://playwright.dev/python/docs/locators).
  5107. Parameters
  5108. ----------
  5109. selector_or_locator : Union[Locator, str]
  5110. A selector or locator to use when resolving DOM element.
  5111. has_text : Union[Pattern[str], str, None]
  5112. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  5113. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  5114. `<article><div>Playwright</div></article>`.
  5115. has_not_text : Union[Pattern[str], str, None]
  5116. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  5117. When passed a [string], matching is case-insensitive and searches for a substring.
  5118. has : Union[Locator, None]
  5119. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  5120. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  5121. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  5122. the document root. For example, you can find `content` that has `div` in
  5123. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  5124. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  5125. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  5126. has_not : Union[Locator, None]
  5127. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  5128. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  5129. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  5130. Returns
  5131. -------
  5132. Locator
  5133. """
  5134. return mapping.from_impl(
  5135. self._impl_obj.locator(
  5136. selectorOrLocator=selector_or_locator,
  5137. hasText=has_text,
  5138. hasNotText=has_not_text,
  5139. has=has._impl_obj if has else None,
  5140. hasNot=has_not._impl_obj if has_not else None,
  5141. )
  5142. )
  5143. def get_by_alt_text(
  5144. self,
  5145. text: typing.Union[str, typing.Pattern[str]],
  5146. *,
  5147. exact: typing.Optional[bool] = None,
  5148. ) -> "Locator":
  5149. """FrameLocator.get_by_alt_text
  5150. Allows locating elements by their alt text.
  5151. **Usage**
  5152. For example, this method will find the image by alt text \"Playwright logo\":
  5153. ```html
  5154. <img alt='Playwright logo'>
  5155. ```
  5156. ```py
  5157. await page.get_by_alt_text(\"Playwright logo\").click()
  5158. ```
  5159. Parameters
  5160. ----------
  5161. text : Union[Pattern[str], str]
  5162. Text to locate the element for.
  5163. exact : Union[bool, None]
  5164. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5165. regular expression. Note that exact match still trims whitespace.
  5166. Returns
  5167. -------
  5168. Locator
  5169. """
  5170. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  5171. def get_by_label(
  5172. self,
  5173. text: typing.Union[str, typing.Pattern[str]],
  5174. *,
  5175. exact: typing.Optional[bool] = None,
  5176. ) -> "Locator":
  5177. """FrameLocator.get_by_label
  5178. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  5179. `aria-label` attribute.
  5180. **Usage**
  5181. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  5182. ```html
  5183. <input aria-label=\"Username\">
  5184. <label for=\"password-input\">Password:</label>
  5185. <input id=\"password-input\">
  5186. ```
  5187. ```py
  5188. await page.get_by_label(\"Username\").fill(\"john\")
  5189. await page.get_by_label(\"Password\").fill(\"secret\")
  5190. ```
  5191. Parameters
  5192. ----------
  5193. text : Union[Pattern[str], str]
  5194. Text to locate the element for.
  5195. exact : Union[bool, None]
  5196. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5197. regular expression. Note that exact match still trims whitespace.
  5198. Returns
  5199. -------
  5200. Locator
  5201. """
  5202. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  5203. def get_by_placeholder(
  5204. self,
  5205. text: typing.Union[str, typing.Pattern[str]],
  5206. *,
  5207. exact: typing.Optional[bool] = None,
  5208. ) -> "Locator":
  5209. """FrameLocator.get_by_placeholder
  5210. Allows locating input elements by the placeholder text.
  5211. **Usage**
  5212. For example, consider the following DOM structure.
  5213. ```html
  5214. <input type=\"email\" placeholder=\"name@example.com\" />
  5215. ```
  5216. You can fill the input after locating it by the placeholder text:
  5217. ```py
  5218. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  5219. ```
  5220. Parameters
  5221. ----------
  5222. text : Union[Pattern[str], str]
  5223. Text to locate the element for.
  5224. exact : Union[bool, None]
  5225. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5226. regular expression. Note that exact match still trims whitespace.
  5227. Returns
  5228. -------
  5229. Locator
  5230. """
  5231. return mapping.from_impl(
  5232. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  5233. )
  5234. def get_by_role(
  5235. self,
  5236. role: Literal[
  5237. "alert",
  5238. "alertdialog",
  5239. "application",
  5240. "article",
  5241. "banner",
  5242. "blockquote",
  5243. "button",
  5244. "caption",
  5245. "cell",
  5246. "checkbox",
  5247. "code",
  5248. "columnheader",
  5249. "combobox",
  5250. "complementary",
  5251. "contentinfo",
  5252. "definition",
  5253. "deletion",
  5254. "dialog",
  5255. "directory",
  5256. "document",
  5257. "emphasis",
  5258. "feed",
  5259. "figure",
  5260. "form",
  5261. "generic",
  5262. "grid",
  5263. "gridcell",
  5264. "group",
  5265. "heading",
  5266. "img",
  5267. "insertion",
  5268. "link",
  5269. "list",
  5270. "listbox",
  5271. "listitem",
  5272. "log",
  5273. "main",
  5274. "marquee",
  5275. "math",
  5276. "menu",
  5277. "menubar",
  5278. "menuitem",
  5279. "menuitemcheckbox",
  5280. "menuitemradio",
  5281. "meter",
  5282. "navigation",
  5283. "none",
  5284. "note",
  5285. "option",
  5286. "paragraph",
  5287. "presentation",
  5288. "progressbar",
  5289. "radio",
  5290. "radiogroup",
  5291. "region",
  5292. "row",
  5293. "rowgroup",
  5294. "rowheader",
  5295. "scrollbar",
  5296. "search",
  5297. "searchbox",
  5298. "separator",
  5299. "slider",
  5300. "spinbutton",
  5301. "status",
  5302. "strong",
  5303. "subscript",
  5304. "superscript",
  5305. "switch",
  5306. "tab",
  5307. "table",
  5308. "tablist",
  5309. "tabpanel",
  5310. "term",
  5311. "textbox",
  5312. "time",
  5313. "timer",
  5314. "toolbar",
  5315. "tooltip",
  5316. "tree",
  5317. "treegrid",
  5318. "treeitem",
  5319. ],
  5320. *,
  5321. checked: typing.Optional[bool] = None,
  5322. disabled: typing.Optional[bool] = None,
  5323. expanded: typing.Optional[bool] = None,
  5324. include_hidden: typing.Optional[bool] = None,
  5325. level: typing.Optional[int] = None,
  5326. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5327. pressed: typing.Optional[bool] = None,
  5328. selected: typing.Optional[bool] = None,
  5329. exact: typing.Optional[bool] = None,
  5330. description: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5331. ) -> "Locator":
  5332. """FrameLocator.get_by_role
  5333. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  5334. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  5335. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  5336. **Usage**
  5337. Consider the following DOM structure.
  5338. ```html
  5339. <h3>Sign up</h3>
  5340. <label>
  5341. <input type=\"checkbox\" /> Subscribe
  5342. </label>
  5343. <br/>
  5344. <button>Submit</button>
  5345. ```
  5346. You can locate each element by its implicit role:
  5347. ```py
  5348. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  5349. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  5350. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  5351. ```
  5352. **Details**
  5353. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  5354. about the ARIA guidelines.
  5355. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  5356. that is recognized by the role selector. You can find all the
  5357. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  5358. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  5359. Parameters
  5360. ----------
  5361. 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"]
  5362. Required aria role.
  5363. checked : Union[bool, None]
  5364. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  5365. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  5366. disabled : Union[bool, None]
  5367. An attribute that is usually set by `aria-disabled` or `disabled`.
  5368. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  5369. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  5370. expanded : Union[bool, None]
  5371. An attribute that is usually set by `aria-expanded`.
  5372. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  5373. include_hidden : Union[bool, None]
  5374. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  5375. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  5376. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  5377. level : Union[int, None]
  5378. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  5379. for `<h1>-<h6>` elements.
  5380. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  5381. name : Union[Pattern[str], str, None]
  5382. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  5383. case-insensitive and searches for a substring, use `exact` to control this behavior.
  5384. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  5385. pressed : Union[bool, None]
  5386. An attribute that is usually set by `aria-pressed`.
  5387. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  5388. selected : Union[bool, None]
  5389. An attribute that is usually set by `aria-selected`.
  5390. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  5391. exact : Union[bool, None]
  5392. Whether `name` and `description` are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored
  5393. when the value is a regular expression. Note that exact match still trims whitespace.
  5394. description : Union[Pattern[str], str, None]
  5395. Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By
  5396. default, matching is case-insensitive and searches for a substring, use `exact` to control this behavior.
  5397. Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  5398. Returns
  5399. -------
  5400. Locator
  5401. """
  5402. return mapping.from_impl(
  5403. self._impl_obj.get_by_role(
  5404. role=role,
  5405. checked=checked,
  5406. disabled=disabled,
  5407. expanded=expanded,
  5408. includeHidden=include_hidden,
  5409. level=level,
  5410. name=name,
  5411. pressed=pressed,
  5412. selected=selected,
  5413. exact=exact,
  5414. description=description,
  5415. )
  5416. )
  5417. def get_by_test_id(
  5418. self, test_id: typing.Union[str, typing.Pattern[str]]
  5419. ) -> "Locator":
  5420. """FrameLocator.get_by_test_id
  5421. Locate element by the test id.
  5422. **Usage**
  5423. Consider the following DOM structure.
  5424. ```html
  5425. <button data-testid=\"directions\">Itinéraire</button>
  5426. ```
  5427. You can locate the element by its test id:
  5428. ```py
  5429. await page.get_by_test_id(\"directions\").click()
  5430. ```
  5431. **Details**
  5432. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  5433. configure a different test id attribute if necessary.
  5434. Parameters
  5435. ----------
  5436. test_id : Union[Pattern[str], str]
  5437. Id to locate the element by.
  5438. Returns
  5439. -------
  5440. Locator
  5441. """
  5442. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  5443. def get_by_text(
  5444. self,
  5445. text: typing.Union[str, typing.Pattern[str]],
  5446. *,
  5447. exact: typing.Optional[bool] = None,
  5448. ) -> "Locator":
  5449. """FrameLocator.get_by_text
  5450. Allows locating elements that contain given text.
  5451. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  5452. filter by the text content.
  5453. **Usage**
  5454. Consider the following DOM structure:
  5455. ```html
  5456. <div>Hello <span>world</span></div>
  5457. <div>Hello</div>
  5458. ```
  5459. You can locate by text substring, exact string, or a regular expression:
  5460. ```py
  5461. # Matches <span>
  5462. page.get_by_text(\"world\")
  5463. # Matches first <div>
  5464. page.get_by_text(\"Hello world\")
  5465. # Matches second <div>
  5466. page.get_by_text(\"Hello\", exact=True)
  5467. # Matches both <div>s
  5468. page.get_by_text(re.compile(\"Hello\"))
  5469. # Matches second <div>
  5470. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  5471. ```
  5472. **Details**
  5473. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  5474. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  5475. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  5476. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  5477. Parameters
  5478. ----------
  5479. text : Union[Pattern[str], str]
  5480. Text to locate the element for.
  5481. exact : Union[bool, None]
  5482. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5483. regular expression. Note that exact match still trims whitespace.
  5484. Returns
  5485. -------
  5486. Locator
  5487. """
  5488. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  5489. def get_by_title(
  5490. self,
  5491. text: typing.Union[str, typing.Pattern[str]],
  5492. *,
  5493. exact: typing.Optional[bool] = None,
  5494. ) -> "Locator":
  5495. """FrameLocator.get_by_title
  5496. Allows locating elements by their title attribute.
  5497. **Usage**
  5498. Consider the following DOM structure.
  5499. ```html
  5500. <span title='Issues count'>25 issues</span>
  5501. ```
  5502. You can check the issues count after locating it by the title text:
  5503. ```py
  5504. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  5505. ```
  5506. Parameters
  5507. ----------
  5508. text : Union[Pattern[str], str]
  5509. Text to locate the element for.
  5510. exact : Union[bool, None]
  5511. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5512. regular expression. Note that exact match still trims whitespace.
  5513. Returns
  5514. -------
  5515. Locator
  5516. """
  5517. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  5518. def frame_locator(self, selector: str) -> "FrameLocator":
  5519. """FrameLocator.frame_locator
  5520. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  5521. in that iframe.
  5522. Parameters
  5523. ----------
  5524. selector : str
  5525. A selector to use when resolving DOM element.
  5526. Returns
  5527. -------
  5528. FrameLocator
  5529. """
  5530. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  5531. def nth(self, index: int) -> "FrameLocator":
  5532. """FrameLocator.nth
  5533. Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.
  5534. Parameters
  5535. ----------
  5536. index : int
  5537. Returns
  5538. -------
  5539. FrameLocator
  5540. """
  5541. return mapping.from_impl(self._impl_obj.nth(index=index))
  5542. mapping.register(FrameLocatorImpl, FrameLocator)
  5543. class Worker(AsyncBase):
  5544. @typing.overload
  5545. def on(
  5546. self,
  5547. event: Literal["close"],
  5548. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  5549. ) -> None:
  5550. """
  5551. Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
  5552. terminated."""
  5553. @typing.overload
  5554. def on(
  5555. self,
  5556. event: Literal["console"],
  5557. f: typing.Callable[
  5558. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  5559. ],
  5560. ) -> None:
  5561. """
  5562. Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
  5563. """
  5564. def on(
  5565. self,
  5566. event: str,
  5567. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  5568. ) -> None:
  5569. return super().on(event=event, f=f)
  5570. @typing.overload
  5571. def once(
  5572. self,
  5573. event: Literal["close"],
  5574. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  5575. ) -> None:
  5576. """
  5577. Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
  5578. terminated."""
  5579. @typing.overload
  5580. def once(
  5581. self,
  5582. event: Literal["console"],
  5583. f: typing.Callable[
  5584. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  5585. ],
  5586. ) -> None:
  5587. """
  5588. Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
  5589. """
  5590. def once(
  5591. self,
  5592. event: str,
  5593. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  5594. ) -> None:
  5595. return super().once(event=event, f=f)
  5596. @property
  5597. def url(self) -> str:
  5598. """Worker.url
  5599. Returns
  5600. -------
  5601. str
  5602. """
  5603. return mapping.from_maybe_impl(self._impl_obj.url)
  5604. async def evaluate(
  5605. self, expression: str, arg: typing.Optional[typing.Any] = None
  5606. ) -> typing.Any:
  5607. """Worker.evaluate
  5608. Returns the return value of `expression`.
  5609. If the function passed to the `worker.evaluate()` returns a [Promise], then `worker.evaluate()`
  5610. would wait for the promise to resolve and return its value.
  5611. If the function passed to the `worker.evaluate()` returns a non-[Serializable] value, then
  5612. `worker.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
  5613. are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  5614. Parameters
  5615. ----------
  5616. expression : str
  5617. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  5618. function is automatically invoked.
  5619. arg : Union[Any, None]
  5620. Optional argument to pass to `expression`.
  5621. Returns
  5622. -------
  5623. Any
  5624. """
  5625. return mapping.from_maybe_impl(
  5626. await self._impl_obj.evaluate(
  5627. expression=expression, arg=mapping.to_impl(arg)
  5628. )
  5629. )
  5630. async def evaluate_handle(
  5631. self, expression: str, arg: typing.Optional[typing.Any] = None
  5632. ) -> "JSHandle":
  5633. """Worker.evaluate_handle
  5634. Returns the return value of `expression` as a `JSHandle`.
  5635. The only difference between `worker.evaluate()` and `worker.evaluate_handle()` is that
  5636. `worker.evaluate_handle()` returns `JSHandle`.
  5637. If the function passed to the `worker.evaluate_handle()` returns a [Promise], then
  5638. `worker.evaluate_handle()` would wait for the promise to resolve and return its value.
  5639. Parameters
  5640. ----------
  5641. expression : str
  5642. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  5643. function is automatically invoked.
  5644. arg : Union[Any, None]
  5645. Optional argument to pass to `expression`.
  5646. Returns
  5647. -------
  5648. JSHandle
  5649. """
  5650. return mapping.from_impl(
  5651. await self._impl_obj.evaluate_handle(
  5652. expression=expression, arg=mapping.to_impl(arg)
  5653. )
  5654. )
  5655. @typing.overload
  5656. def expect_event(
  5657. self,
  5658. event: typing.Literal["close"],
  5659. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  5660. *,
  5661. timeout: typing.Optional[float] = None,
  5662. ) -> AsyncEventContextManager["Worker"]: ...
  5663. @typing.overload
  5664. def expect_event(
  5665. self,
  5666. event: typing.Literal["console"],
  5667. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  5668. *,
  5669. timeout: typing.Optional[float] = None,
  5670. ) -> AsyncEventContextManager["ConsoleMessage"]: ...
  5671. @typing.overload
  5672. def expect_event(
  5673. self,
  5674. event: str,
  5675. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  5676. *,
  5677. timeout: typing.Optional[float] = None,
  5678. ) -> AsyncEventContextManager[typing.Any]: ...
  5679. def expect_event(
  5680. self,
  5681. event: str,
  5682. predicate: typing.Optional[typing.Callable] = None,
  5683. *,
  5684. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  5685. ) -> AsyncEventContextManager:
  5686. """Worker.expect_event
  5687. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  5688. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
  5689. **Usage**
  5690. ```py
  5691. async with worker.expect_event(\"console\") as event_info:
  5692. await worker.evaluate(\"console.log(42)\")
  5693. message = await event_info.value
  5694. ```
  5695. Parameters
  5696. ----------
  5697. event : str
  5698. Event name, same one typically passed into `*.on(event)`.
  5699. predicate : Union[Callable, None]
  5700. Receives the event data and resolves to truthy value when the waiting should resolve.
  5701. timeout : Union[float, None]
  5702. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  5703. default value can be changed by using the `browser_context.set_default_timeout()`.
  5704. Returns
  5705. -------
  5706. EventContextManager
  5707. """
  5708. return AsyncEventContextManager(
  5709. self._impl_obj.expect_event(
  5710. event=event,
  5711. predicate=self._wrap_handler(predicate),
  5712. timeout=to_milliseconds(timeout),
  5713. ).future
  5714. )
  5715. mapping.register(WorkerImpl, Worker)
  5716. class Selectors(AsyncBase):
  5717. async def register(
  5718. self,
  5719. name: str,
  5720. script: typing.Optional[str] = None,
  5721. *,
  5722. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  5723. content_script: typing.Optional[bool] = None,
  5724. ) -> None:
  5725. """Selectors.register
  5726. Selectors must be registered before creating the page.
  5727. **Usage**
  5728. An example of registering selector engine that queries elements based on a tag name:
  5729. ```py
  5730. import asyncio
  5731. from playwright.async_api import async_playwright, Playwright
  5732. async def run(playwright: Playwright):
  5733. tag_selector = \"\"\"
  5734. {
  5735. // Returns the first element matching given selector in the root's subtree.
  5736. query(root, selector) {
  5737. return root.querySelector(selector);
  5738. },
  5739. // Returns all elements matching given selector in the root's subtree.
  5740. queryAll(root, selector) {
  5741. return Array.from(root.querySelectorAll(selector));
  5742. }
  5743. }\"\"\"
  5744. # Register the engine. Selectors will be prefixed with \"tag=\".
  5745. await playwright.selectors.register(\"tag\", tag_selector)
  5746. browser = await playwright.chromium.launch()
  5747. page = await browser.new_page()
  5748. await page.set_content('<div><button>Click me</button></div>')
  5749. # Use the selector prefixed with its name.
  5750. button = await page.query_selector('tag=button')
  5751. # Combine it with built-in locators.
  5752. await page.locator('tag=div').get_by_text('Click me').click()
  5753. # Can use it in any methods supporting selectors.
  5754. button_count = await page.locator('tag=button').count()
  5755. print(button_count)
  5756. await browser.close()
  5757. async def main():
  5758. async with async_playwright() as playwright:
  5759. await run(playwright)
  5760. asyncio.run(main())
  5761. ```
  5762. Parameters
  5763. ----------
  5764. name : str
  5765. Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only
  5766. contain `[a-zA-Z0-9_]` characters.
  5767. script : Union[str, None]
  5768. Raw script content.
  5769. path : Union[pathlib.Path, str, None]
  5770. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  5771. directory.
  5772. content_script : Union[bool, None]
  5773. Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same
  5774. DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content
  5775. script is not guaranteed when this engine is used together with other registered engines.
  5776. """
  5777. return mapping.from_maybe_impl(
  5778. await self._impl_obj.register(
  5779. name=name, script=script, path=path, contentScript=content_script
  5780. )
  5781. )
  5782. def set_test_id_attribute(self, attribute_name: str) -> None:
  5783. """Selectors.set_test_id_attribute
  5784. Defines custom attribute name to be used in `page.get_by_test_id()`. `data-testid` is used by default.
  5785. Parameters
  5786. ----------
  5787. attribute_name : str
  5788. Test id attribute name.
  5789. """
  5790. return mapping.from_maybe_impl(
  5791. self._impl_obj.set_test_id_attribute(attributeName=attribute_name)
  5792. )
  5793. mapping.register(SelectorsImpl, Selectors)
  5794. class Clock(AsyncBase):
  5795. async def install(
  5796. self,
  5797. *,
  5798. time: typing.Optional[typing.Union[float, str, datetime.datetime]] = None,
  5799. ) -> None:
  5800. """Clock.install
  5801. Install fake implementations for the following time-related functions:
  5802. - `Date`
  5803. - `setTimeout`
  5804. - `clearTimeout`
  5805. - `setInterval`
  5806. - `clearInterval`
  5807. - `requestAnimationFrame`
  5808. - `cancelAnimationFrame`
  5809. - `requestIdleCallback`
  5810. - `cancelIdleCallback`
  5811. - `performance`
  5812. Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,
  5813. and control the behavior of time-dependent functions. See `clock.run_for()` and
  5814. `clock.fast_forward()` for more information.
  5815. Parameters
  5816. ----------
  5817. time : Union[datetime.datetime, float, str, None]
  5818. Time to initialize with, current system time by default.
  5819. """
  5820. return mapping.from_maybe_impl(await self._impl_obj.install(time=time))
  5821. async def fast_forward(self, ticks: typing.Union[int, str]) -> None:
  5822. """Clock.fast_forward
  5823. Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user
  5824. closing the laptop lid for a while and reopening it later, after given time.
  5825. **Usage**
  5826. ```py
  5827. await page.clock.fast_forward(1000)
  5828. await page.clock.fast_forward(\"30:00\")
  5829. ```
  5830. Parameters
  5831. ----------
  5832. ticks : Union[int, str]
  5833. Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
  5834. "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
  5835. """
  5836. return mapping.from_maybe_impl(await self._impl_obj.fast_forward(ticks=ticks))
  5837. async def pause_at(self, time: typing.Union[float, str, datetime.datetime]) -> None:
  5838. """Clock.pause_at
  5839. Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired
  5840. unless `clock.run_for()`, `clock.fast_forward()`, `clock.pause_at()` or
  5841. `clock.resume()` is called.
  5842. Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it
  5843. at the specified time and pausing.
  5844. **Usage**
  5845. ```py
  5846. await page.clock.pause_at(datetime.datetime(2020, 2, 2))
  5847. await page.clock.pause_at(\"2020-02-02\")
  5848. ```
  5849. For best results, install the clock before navigating the page and set it to a time slightly before the intended
  5850. test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.
  5851. Once the page has fully loaded, you can safely use `clock.pause_at()` to pause the clock.
  5852. ```py
  5853. # Initialize clock with some time before the test time and let the page load
  5854. # naturally. `Date.now` will progress as the timers fire.
  5855. await page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0))
  5856. await page.goto(\"http://localhost:3333\")
  5857. await page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0))
  5858. ```
  5859. Parameters
  5860. ----------
  5861. time : Union[datetime.datetime, float, str]
  5862. Time to pause at.
  5863. """
  5864. return mapping.from_maybe_impl(await self._impl_obj.pause_at(time=time))
  5865. async def resume(self) -> None:
  5866. """Clock.resume
  5867. Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.
  5868. """
  5869. return mapping.from_maybe_impl(await self._impl_obj.resume())
  5870. async def run_for(self, ticks: typing.Union[int, str]) -> None:
  5871. """Clock.run_for
  5872. Advance the clock, firing all the time-related callbacks.
  5873. **Usage**
  5874. ```py
  5875. await page.clock.run_for(1000);
  5876. await page.clock.run_for(\"30:00\")
  5877. ```
  5878. Parameters
  5879. ----------
  5880. ticks : Union[int, str]
  5881. Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
  5882. "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
  5883. """
  5884. return mapping.from_maybe_impl(await self._impl_obj.run_for(ticks=ticks))
  5885. async def set_fixed_time(
  5886. self, time: typing.Union[float, str, datetime.datetime]
  5887. ) -> None:
  5888. """Clock.set_fixed_time
  5889. Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.
  5890. Use this method for simple scenarios where you only need to test with a predefined time. For more advanced
  5891. scenarios, use `clock.install()` instead. Read docs on [clock emulation](https://playwright.dev/python/docs/clock) to learn more.
  5892. **Usage**
  5893. ```py
  5894. await page.clock.set_fixed_time(datetime.datetime.now())
  5895. await page.clock.set_fixed_time(datetime.datetime(2020, 2, 2))
  5896. await page.clock.set_fixed_time(\"2020-02-02\")
  5897. ```
  5898. Parameters
  5899. ----------
  5900. time : Union[datetime.datetime, float, str]
  5901. Time to be set.
  5902. """
  5903. return mapping.from_maybe_impl(await self._impl_obj.set_fixed_time(time=time))
  5904. async def set_system_time(
  5905. self, time: typing.Union[float, str, datetime.datetime]
  5906. ) -> None:
  5907. """Clock.set_system_time
  5908. Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for
  5909. example switching from summer to winter time, or changing time zones.
  5910. **Usage**
  5911. ```py
  5912. await page.clock.set_system_time(datetime.datetime.now())
  5913. await page.clock.set_system_time(datetime.datetime(2020, 2, 2))
  5914. await page.clock.set_system_time(\"2020-02-02\")
  5915. ```
  5916. Parameters
  5917. ----------
  5918. time : Union[datetime.datetime, float, str]
  5919. Time to be set.
  5920. """
  5921. return mapping.from_maybe_impl(await self._impl_obj.set_system_time(time=time))
  5922. mapping.register(ClockImpl, Clock)
  5923. class ConsoleMessage(AsyncBase):
  5924. @property
  5925. def type(
  5926. self,
  5927. ) -> typing.Union[
  5928. Literal["assert"],
  5929. Literal["clear"],
  5930. Literal["count"],
  5931. Literal["debug"],
  5932. Literal["dir"],
  5933. Literal["dirxml"],
  5934. Literal["endGroup"],
  5935. Literal["error"],
  5936. Literal["info"],
  5937. Literal["log"],
  5938. Literal["profile"],
  5939. Literal["profileEnd"],
  5940. Literal["startGroup"],
  5941. Literal["startGroupCollapsed"],
  5942. Literal["table"],
  5943. Literal["time"],
  5944. Literal["timeEnd"],
  5945. Literal["trace"],
  5946. Literal["warning"],
  5947. ]:
  5948. """ConsoleMessage.type
  5949. Returns
  5950. -------
  5951. Union["assert", "clear", "count", "debug", "dir", "dirxml", "endGroup", "error", "info", "log", "profile", "profileEnd", "startGroup", "startGroupCollapsed", "table", "time", "timeEnd", "trace", "warning"]
  5952. """
  5953. return mapping.from_maybe_impl(self._impl_obj.type)
  5954. @property
  5955. def text(self) -> str:
  5956. """ConsoleMessage.text
  5957. The text of the console message.
  5958. Returns
  5959. -------
  5960. str
  5961. """
  5962. return mapping.from_maybe_impl(self._impl_obj.text)
  5963. @property
  5964. def args(self) -> typing.List["JSHandle"]:
  5965. """ConsoleMessage.args
  5966. List of arguments passed to a `console` function call. See also `page.on('console')`.
  5967. Returns
  5968. -------
  5969. List[JSHandle]
  5970. """
  5971. return mapping.from_impl_list(self._impl_obj.args)
  5972. @property
  5973. def location(self) -> SourceLocation:
  5974. """ConsoleMessage.location
  5975. Returns
  5976. -------
  5977. {url: str, line: int, column: int, lineNumber: int, columnNumber: int}
  5978. """
  5979. return mapping.from_impl(self._impl_obj.location)
  5980. @property
  5981. def timestamp(self) -> float:
  5982. """ConsoleMessage.timestamp
  5983. The timestamp of the console message in milliseconds since the Unix epoch.
  5984. Returns
  5985. -------
  5986. float
  5987. """
  5988. return mapping.from_maybe_impl(self._impl_obj.timestamp)
  5989. @property
  5990. def page(self) -> typing.Optional["Page"]:
  5991. """ConsoleMessage.page
  5992. The page that produced this console message, if any.
  5993. Returns
  5994. -------
  5995. Union[Page, None]
  5996. """
  5997. return mapping.from_impl_nullable(self._impl_obj.page)
  5998. @property
  5999. def worker(self) -> typing.Optional["Worker"]:
  6000. """ConsoleMessage.worker
  6001. The web worker or service worker that produced this console message, if any. Note that console messages from web
  6002. workers also have non-null `console_message.page()`.
  6003. Returns
  6004. -------
  6005. Union[Worker, None]
  6006. """
  6007. return mapping.from_impl_nullable(self._impl_obj.worker)
  6008. mapping.register(ConsoleMessageImpl, ConsoleMessage)
  6009. class Debugger(AsyncBase):
  6010. @typing.overload
  6011. def on(
  6012. self,
  6013. event: Literal["pausedstatechanged"],
  6014. f: typing.Callable[["None"], "typing.Union[typing.Awaitable[None], None]"],
  6015. ) -> None:
  6016. """
  6017. Emitted when the debugger pauses or resumes."""
  6018. @typing.overload
  6019. def on(
  6020. self,
  6021. event: str,
  6022. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6023. ) -> None: ...
  6024. def on(
  6025. self,
  6026. event: str,
  6027. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6028. ) -> None:
  6029. return super().on(event=event, f=f)
  6030. @typing.overload
  6031. def once(
  6032. self,
  6033. event: Literal["pausedstatechanged"],
  6034. f: typing.Callable[["None"], "typing.Union[typing.Awaitable[None], None]"],
  6035. ) -> None:
  6036. """
  6037. Emitted when the debugger pauses or resumes."""
  6038. @typing.overload
  6039. def once(
  6040. self,
  6041. event: str,
  6042. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6043. ) -> None: ...
  6044. def once(
  6045. self,
  6046. event: str,
  6047. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6048. ) -> None:
  6049. return super().once(event=event, f=f)
  6050. @property
  6051. def paused_details(self) -> typing.Optional[DebuggerPausedDetails]:
  6052. """Debugger.paused_details
  6053. Returns details about the currently paused call. Returns `null` if the debugger is not paused.
  6054. Returns
  6055. -------
  6056. Union[{location: {file: str, line: Union[int, None], column: Union[int, None]}, title: str}, None]
  6057. """
  6058. return mapping.from_impl_nullable(self._impl_obj.paused_details)
  6059. async def request_pause(self) -> None:
  6060. """Debugger.request_pause
  6061. Configures the debugger to pause before the next action is executed.
  6062. Throws if the debugger is already paused. Use `debugger.next()` or `debugger.run_to()` to step while
  6063. paused.
  6064. Note that `page.pause()` is equivalent to a \"debugger\" statement — it pauses execution at the call site
  6065. immediately. On the contrary, `debugger.request_pause()` is equivalent to \"pause on next statement\" — it
  6066. configures the debugger to pause before the next action is executed.
  6067. """
  6068. return mapping.from_maybe_impl(await self._impl_obj.request_pause())
  6069. async def resume(self) -> None:
  6070. """Debugger.resume
  6071. Resumes script execution. Throws if the debugger is not paused.
  6072. """
  6073. return mapping.from_maybe_impl(await self._impl_obj.resume())
  6074. async def next(self) -> None:
  6075. """Debugger.next
  6076. Resumes script execution and pauses again before the next action. Throws if the debugger is not paused.
  6077. """
  6078. return mapping.from_maybe_impl(await self._impl_obj.next())
  6079. async def run_to(self, location: DebuggerLocation) -> None:
  6080. """Debugger.run_to
  6081. Resumes script execution and pauses when an action originates from the given source location. Throws if the
  6082. debugger is not paused.
  6083. Parameters
  6084. ----------
  6085. location : {file: str, line: Union[int, None], column: Union[int, None]}
  6086. The source location to pause at.
  6087. """
  6088. return mapping.from_maybe_impl(await self._impl_obj.run_to(location=location))
  6089. mapping.register(DebuggerImpl, Debugger)
  6090. class Dialog(AsyncBase):
  6091. @property
  6092. def type(self) -> str:
  6093. """Dialog.type
  6094. Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
  6095. Returns
  6096. -------
  6097. str
  6098. """
  6099. return mapping.from_maybe_impl(self._impl_obj.type)
  6100. @property
  6101. def message(self) -> str:
  6102. """Dialog.message
  6103. A message displayed in the dialog.
  6104. Returns
  6105. -------
  6106. str
  6107. """
  6108. return mapping.from_maybe_impl(self._impl_obj.message)
  6109. @property
  6110. def default_value(self) -> str:
  6111. """Dialog.default_value
  6112. If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
  6113. Returns
  6114. -------
  6115. str
  6116. """
  6117. return mapping.from_maybe_impl(self._impl_obj.default_value)
  6118. @property
  6119. def page(self) -> typing.Optional["Page"]:
  6120. """Dialog.page
  6121. The page that initiated this dialog, if available.
  6122. Returns
  6123. -------
  6124. Union[Page, None]
  6125. """
  6126. return mapping.from_impl_nullable(self._impl_obj.page)
  6127. async def accept(self, prompt_text: typing.Optional[str] = None) -> None:
  6128. """Dialog.accept
  6129. Returns when the dialog has been accepted.
  6130. Parameters
  6131. ----------
  6132. prompt_text : Union[str, None]
  6133. A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.
  6134. """
  6135. return mapping.from_maybe_impl(
  6136. await self._impl_obj.accept(promptText=prompt_text)
  6137. )
  6138. async def dismiss(self) -> None:
  6139. """Dialog.dismiss
  6140. Returns when the dialog has been dismissed.
  6141. """
  6142. return mapping.from_maybe_impl(await self._impl_obj.dismiss())
  6143. mapping.register(DialogImpl, Dialog)
  6144. class Download(AsyncBase):
  6145. @property
  6146. def page(self) -> "Page":
  6147. """Download.page
  6148. Get the page that the download belongs to.
  6149. Returns
  6150. -------
  6151. Page
  6152. """
  6153. return mapping.from_impl(self._impl_obj.page)
  6154. @property
  6155. def url(self) -> str:
  6156. """Download.url
  6157. Returns downloaded url.
  6158. Returns
  6159. -------
  6160. str
  6161. """
  6162. return mapping.from_maybe_impl(self._impl_obj.url)
  6163. @property
  6164. def suggested_filename(self) -> str:
  6165. """Download.suggested_filename
  6166. Returns suggested filename for this download. It is typically computed by the browser from the
  6167. [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response
  6168. header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).
  6169. Different browsers can use different logic for computing it.
  6170. Returns
  6171. -------
  6172. str
  6173. """
  6174. return mapping.from_maybe_impl(self._impl_obj.suggested_filename)
  6175. async def delete(self) -> None:
  6176. """Download.delete
  6177. Deletes the downloaded file. Will wait for the download to finish if necessary.
  6178. """
  6179. return mapping.from_maybe_impl(await self._impl_obj.delete())
  6180. async def failure(self) -> typing.Optional[str]:
  6181. """Download.failure
  6182. Returns download error if any. Will wait for the download to finish if necessary.
  6183. Returns
  6184. -------
  6185. Union[str, None]
  6186. """
  6187. return mapping.from_maybe_impl(await self._impl_obj.failure())
  6188. async def path(self) -> pathlib.Path:
  6189. """Download.path
  6190. Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method
  6191. will wait for the download to finish if necessary. The method throws when connected remotely.
  6192. Note that the download's file name is a random GUID, use `download.suggested_filename()` to get suggested
  6193. file name.
  6194. Returns
  6195. -------
  6196. pathlib.Path
  6197. """
  6198. return mapping.from_maybe_impl(await self._impl_obj.path())
  6199. async def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
  6200. """Download.save_as
  6201. Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.
  6202. Will wait for the download to finish if necessary.
  6203. **Usage**
  6204. ```py
  6205. await download.save_as(\"/path/to/save/at/\" + download.suggested_filename)
  6206. ```
  6207. Parameters
  6208. ----------
  6209. path : Union[pathlib.Path, str]
  6210. Path where the download should be copied.
  6211. """
  6212. return mapping.from_maybe_impl(await self._impl_obj.save_as(path=path))
  6213. async def cancel(self) -> None:
  6214. """Download.cancel
  6215. Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,
  6216. `download.failure()` would resolve to `'canceled'`.
  6217. """
  6218. return mapping.from_maybe_impl(await self._impl_obj.cancel())
  6219. mapping.register(DownloadImpl, Download)
  6220. class Screencast(AsyncBase):
  6221. async def start(
  6222. self,
  6223. *,
  6224. on_frame: typing.Optional[
  6225. typing.Callable[[ScreencastFrame], typing.Any]
  6226. ] = None,
  6227. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  6228. quality: typing.Optional[int] = None,
  6229. ) -> "AsyncContextManager":
  6230. """Screencast.start
  6231. Starts the screencast. When `path` is provided, it saves video recording to the specified file. When `onFrame` is
  6232. provided, delivers JPEG-encoded frames to the callback. Both can be used together.
  6233. **Usage**
  6234. Parameters
  6235. ----------
  6236. on_frame : Union[Callable[[{data: bytes, viewportWidth: int, viewportHeight: int}], Any], None]
  6237. Callback that receives JPEG-encoded frame data along with the page viewport size at the time of capture.
  6238. path : Union[pathlib.Path, str, None]
  6239. Path where the video should be saved when the screencast is stopped. When provided, video recording is started.
  6240. quality : Union[int, None]
  6241. The quality of the image, between 0-100.
  6242. Returns
  6243. -------
  6244. AsyncContextManager
  6245. """
  6246. return mapping.from_impl(
  6247. await self._impl_obj.start(
  6248. onFrame=self._wrap_handler(on_frame), path=path, quality=quality
  6249. )
  6250. )
  6251. async def stop(self) -> None:
  6252. """Screencast.stop
  6253. Stops the screencast and video recording if active. If a video was being recorded, saves it to the path specified
  6254. in `screencast.start()`.
  6255. """
  6256. return mapping.from_maybe_impl(await self._impl_obj.stop())
  6257. async def show_actions(
  6258. self,
  6259. *,
  6260. duration: typing.Optional[float] = None,
  6261. position: typing.Optional[
  6262. Literal[
  6263. "bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"
  6264. ]
  6265. ] = None,
  6266. font_size: typing.Optional[int] = None,
  6267. ) -> "AsyncContextManager":
  6268. """Screencast.show_actions
  6269. Enables visual annotations on interacted elements. Returns a disposable that stops showing actions when disposed.
  6270. Parameters
  6271. ----------
  6272. duration : Union[float, None]
  6273. How long each annotation is displayed in milliseconds. Defaults to `500`.
  6274. position : Union["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right", None]
  6275. Position of the action title overlay. Defaults to `"top-right"`.
  6276. font_size : Union[int, None]
  6277. Font size of the action title in pixels. Defaults to `24`.
  6278. Returns
  6279. -------
  6280. AsyncContextManager
  6281. """
  6282. return mapping.from_impl(
  6283. await self._impl_obj.show_actions(
  6284. duration=duration, position=position, fontSize=font_size
  6285. )
  6286. )
  6287. async def hide_actions(self) -> None:
  6288. """Screencast.hide_actions
  6289. Removes action decorations.
  6290. """
  6291. return mapping.from_maybe_impl(await self._impl_obj.hide_actions())
  6292. async def show_overlay(
  6293. self, html: str, *, duration: typing.Optional[float] = None
  6294. ) -> "AsyncContextManager":
  6295. """Screencast.show_overlay
  6296. Adds an overlay with the given HTML content. The overlay is displayed on top of the page until removed. Returns a
  6297. disposable that removes the overlay when disposed.
  6298. Parameters
  6299. ----------
  6300. html : str
  6301. HTML content for the overlay.
  6302. duration : Union[float, None]
  6303. Duration in milliseconds after which the overlay is automatically removed. Overlay stays until dismissed if not
  6304. provided.
  6305. Returns
  6306. -------
  6307. AsyncContextManager
  6308. """
  6309. return mapping.from_impl(
  6310. await self._impl_obj.show_overlay(html=html, duration=duration)
  6311. )
  6312. async def show_chapter(
  6313. self,
  6314. title: str,
  6315. *,
  6316. description: typing.Optional[str] = None,
  6317. duration: typing.Optional[float] = None,
  6318. ) -> None:
  6319. """Screencast.show_chapter
  6320. Shows a chapter overlay with a title and optional description, centered on the page with a blurred backdrop. Useful
  6321. for narrating video recordings. The overlay is removed after the specified duration, or 2000ms.
  6322. Parameters
  6323. ----------
  6324. title : str
  6325. Title text displayed prominently in the overlay.
  6326. description : Union[str, None]
  6327. Optional description text displayed below the title.
  6328. duration : Union[float, None]
  6329. Duration in milliseconds after which the overlay is automatically removed. Defaults to `2000`.
  6330. """
  6331. return mapping.from_maybe_impl(
  6332. await self._impl_obj.show_chapter(
  6333. title=title, description=description, duration=duration
  6334. )
  6335. )
  6336. async def show_overlays(self) -> None:
  6337. """Screencast.show_overlays
  6338. Shows overlays.
  6339. """
  6340. return mapping.from_maybe_impl(await self._impl_obj.show_overlays())
  6341. async def hide_overlays(self) -> None:
  6342. """Screencast.hide_overlays
  6343. Hides overlays without removing them.
  6344. """
  6345. return mapping.from_maybe_impl(await self._impl_obj.hide_overlays())
  6346. mapping.register(ScreencastImpl, Screencast)
  6347. class Video(AsyncBase):
  6348. async def path(self) -> pathlib.Path:
  6349. """Video.path
  6350. Returns the file system path this video will be recorded to. The video is guaranteed to be written to the
  6351. filesystem upon closing the browser context. This method throws when connected remotely.
  6352. Returns
  6353. -------
  6354. pathlib.Path
  6355. """
  6356. return mapping.from_maybe_impl(await self._impl_obj.path())
  6357. async def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
  6358. """Video.save_as
  6359. Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or
  6360. after the page has closed. This method waits until the page is closed and the video is fully saved.
  6361. Parameters
  6362. ----------
  6363. path : Union[pathlib.Path, str]
  6364. Path where the video should be saved.
  6365. """
  6366. return mapping.from_maybe_impl(await self._impl_obj.save_as(path=path))
  6367. async def delete(self) -> None:
  6368. """Video.delete
  6369. Deletes the video file. Will wait for the video to finish if necessary.
  6370. """
  6371. return mapping.from_maybe_impl(await self._impl_obj.delete())
  6372. mapping.register(VideoImpl, Video)
  6373. class Page(AsyncContextManager):
  6374. @typing.overload
  6375. def on(
  6376. self,
  6377. event: Literal["close"],
  6378. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6379. ) -> None:
  6380. """
  6381. Emitted when the page closes."""
  6382. @typing.overload
  6383. def on(
  6384. self,
  6385. event: Literal["console"],
  6386. f: typing.Callable[
  6387. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  6388. ],
  6389. ) -> None:
  6390. """
  6391. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  6392. The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
  6393. **Usage**
  6394. ```py
  6395. async def print_args(msg):
  6396. values = []
  6397. for arg in msg.args:
  6398. values.append(await arg.json_value())
  6399. print(values)
  6400. page.on(\"console\", print_args)
  6401. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  6402. ```"""
  6403. @typing.overload
  6404. def on(
  6405. self,
  6406. event: Literal["crash"],
  6407. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6408. ) -> None:
  6409. """
  6410. Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
  6411. crashes, ongoing and subsequent operations will throw.
  6412. The most common way to deal with crashes is to catch an exception:
  6413. ```py
  6414. try:
  6415. # crash might happen during a click.
  6416. await page.click(\"button\")
  6417. # or while waiting for an event.
  6418. await page.wait_for_event(\"popup\")
  6419. except Error as e:
  6420. pass
  6421. # when the page crashes, exception message contains \"crash\".
  6422. ```"""
  6423. @typing.overload
  6424. def on(
  6425. self,
  6426. event: Literal["dialog"],
  6427. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  6428. ) -> None:
  6429. """
  6430. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  6431. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  6432. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  6433. and actions like click will never finish.
  6434. **Usage**
  6435. ```python
  6436. page.on(\"dialog\", lambda dialog: dialog.accept())
  6437. ```
  6438. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  6439. automatically dismissed."""
  6440. @typing.overload
  6441. def on(
  6442. self,
  6443. event: Literal["domcontentloaded"],
  6444. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6445. ) -> None:
  6446. """
  6447. Emitted when the JavaScript
  6448. [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
  6449. """
  6450. @typing.overload
  6451. def on(
  6452. self,
  6453. event: Literal["download"],
  6454. f: typing.Callable[["Download"], "typing.Union[typing.Awaitable[None], None]"],
  6455. ) -> None:
  6456. """
  6457. Emitted when attachment download started. User can access basic file operations on downloaded content via the
  6458. passed `Download` instance."""
  6459. @typing.overload
  6460. def on(
  6461. self,
  6462. event: Literal["filechooser"],
  6463. f: typing.Callable[
  6464. ["FileChooser"], "typing.Union[typing.Awaitable[None], None]"
  6465. ],
  6466. ) -> None:
  6467. """
  6468. Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
  6469. respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
  6470. ```py
  6471. page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
  6472. ```"""
  6473. @typing.overload
  6474. def on(
  6475. self,
  6476. event: Literal["frameattached"],
  6477. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6478. ) -> None:
  6479. """
  6480. Emitted when a frame is attached."""
  6481. @typing.overload
  6482. def on(
  6483. self,
  6484. event: Literal["framedetached"],
  6485. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6486. ) -> None:
  6487. """
  6488. Emitted when a frame is detached."""
  6489. @typing.overload
  6490. def on(
  6491. self,
  6492. event: Literal["framenavigated"],
  6493. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6494. ) -> None:
  6495. """
  6496. Emitted when a frame is navigated to a new url."""
  6497. @typing.overload
  6498. def on(
  6499. self,
  6500. event: Literal["load"],
  6501. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6502. ) -> None:
  6503. """
  6504. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
  6505. """
  6506. @typing.overload
  6507. def on(
  6508. self,
  6509. event: Literal["pageerror"],
  6510. f: typing.Callable[["Error"], "typing.Union[typing.Awaitable[None], None]"],
  6511. ) -> None:
  6512. """
  6513. Emitted when an uncaught exception happens within the page.
  6514. ```py
  6515. # Log all uncaught errors to the terminal
  6516. page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
  6517. # Navigate to a page with an exception.
  6518. await page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
  6519. ```"""
  6520. @typing.overload
  6521. def on(
  6522. self,
  6523. event: Literal["popup"],
  6524. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6525. ) -> None:
  6526. """
  6527. Emitted when the page opens a new tab or window. This event is emitted in addition to the
  6528. `browser_context.on('page')`, but only for popups relevant to this page.
  6529. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  6530. popup with `window.open('http://example.com')`, this event will fire when the network request to
  6531. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  6532. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  6533. instead of similar methods on the `Page`.
  6534. ```py
  6535. async with page.expect_event(\"popup\") as page_info:
  6536. await page.get_by_text(\"open the popup\").click()
  6537. popup = await page_info.value
  6538. print(await popup.evaluate(\"location.href\"))
  6539. ```
  6540. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  6541. need it in most cases)."""
  6542. @typing.overload
  6543. def on(
  6544. self,
  6545. event: Literal["request"],
  6546. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6547. ) -> None:
  6548. """
  6549. Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
  6550. see `page.route()` or `browser_context.route()`."""
  6551. @typing.overload
  6552. def on(
  6553. self,
  6554. event: Literal["requestfailed"],
  6555. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6556. ) -> None:
  6557. """
  6558. Emitted when a request fails, for example by timing out.
  6559. ```python
  6560. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
  6561. ```
  6562. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  6563. will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
  6564. only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
  6565. net::ERR_FAILED."""
  6566. @typing.overload
  6567. def on(
  6568. self,
  6569. event: Literal["requestfinished"],
  6570. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6571. ) -> None:
  6572. """
  6573. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  6574. sequence of events is `request`, `response` and `requestfinished`."""
  6575. @typing.overload
  6576. def on(
  6577. self,
  6578. event: Literal["response"],
  6579. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  6580. ) -> None:
  6581. """
  6582. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  6583. events is `request`, `response` and `requestfinished`."""
  6584. @typing.overload
  6585. def on(
  6586. self,
  6587. event: Literal["websocket"],
  6588. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  6589. ) -> None:
  6590. """
  6591. Emitted when `WebSocket` request is sent."""
  6592. @typing.overload
  6593. def on(
  6594. self,
  6595. event: Literal["worker"],
  6596. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  6597. ) -> None:
  6598. """
  6599. Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
  6600. by the page."""
  6601. def on(
  6602. self,
  6603. event: str,
  6604. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6605. ) -> None:
  6606. return super().on(event=event, f=f)
  6607. @typing.overload
  6608. def once(
  6609. self,
  6610. event: Literal["close"],
  6611. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6612. ) -> None:
  6613. """
  6614. Emitted when the page closes."""
  6615. @typing.overload
  6616. def once(
  6617. self,
  6618. event: Literal["console"],
  6619. f: typing.Callable[
  6620. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  6621. ],
  6622. ) -> None:
  6623. """
  6624. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  6625. The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
  6626. **Usage**
  6627. ```py
  6628. async def print_args(msg):
  6629. values = []
  6630. for arg in msg.args:
  6631. values.append(await arg.json_value())
  6632. print(values)
  6633. page.on(\"console\", print_args)
  6634. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  6635. ```"""
  6636. @typing.overload
  6637. def once(
  6638. self,
  6639. event: Literal["crash"],
  6640. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6641. ) -> None:
  6642. """
  6643. Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
  6644. crashes, ongoing and subsequent operations will throw.
  6645. The most common way to deal with crashes is to catch an exception:
  6646. ```py
  6647. try:
  6648. # crash might happen during a click.
  6649. await page.click(\"button\")
  6650. # or while waiting for an event.
  6651. await page.wait_for_event(\"popup\")
  6652. except Error as e:
  6653. pass
  6654. # when the page crashes, exception message contains \"crash\".
  6655. ```"""
  6656. @typing.overload
  6657. def once(
  6658. self,
  6659. event: Literal["dialog"],
  6660. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  6661. ) -> None:
  6662. """
  6663. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  6664. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  6665. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  6666. and actions like click will never finish.
  6667. **Usage**
  6668. ```python
  6669. page.on(\"dialog\", lambda dialog: dialog.accept())
  6670. ```
  6671. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  6672. automatically dismissed."""
  6673. @typing.overload
  6674. def once(
  6675. self,
  6676. event: Literal["domcontentloaded"],
  6677. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6678. ) -> None:
  6679. """
  6680. Emitted when the JavaScript
  6681. [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
  6682. """
  6683. @typing.overload
  6684. def once(
  6685. self,
  6686. event: Literal["download"],
  6687. f: typing.Callable[["Download"], "typing.Union[typing.Awaitable[None], None]"],
  6688. ) -> None:
  6689. """
  6690. Emitted when attachment download started. User can access basic file operations on downloaded content via the
  6691. passed `Download` instance."""
  6692. @typing.overload
  6693. def once(
  6694. self,
  6695. event: Literal["filechooser"],
  6696. f: typing.Callable[
  6697. ["FileChooser"], "typing.Union[typing.Awaitable[None], None]"
  6698. ],
  6699. ) -> None:
  6700. """
  6701. Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
  6702. respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
  6703. ```py
  6704. page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
  6705. ```"""
  6706. @typing.overload
  6707. def once(
  6708. self,
  6709. event: Literal["frameattached"],
  6710. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6711. ) -> None:
  6712. """
  6713. Emitted when a frame is attached."""
  6714. @typing.overload
  6715. def once(
  6716. self,
  6717. event: Literal["framedetached"],
  6718. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6719. ) -> None:
  6720. """
  6721. Emitted when a frame is detached."""
  6722. @typing.overload
  6723. def once(
  6724. self,
  6725. event: Literal["framenavigated"],
  6726. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6727. ) -> None:
  6728. """
  6729. Emitted when a frame is navigated to a new url."""
  6730. @typing.overload
  6731. def once(
  6732. self,
  6733. event: Literal["load"],
  6734. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6735. ) -> None:
  6736. """
  6737. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
  6738. """
  6739. @typing.overload
  6740. def once(
  6741. self,
  6742. event: Literal["pageerror"],
  6743. f: typing.Callable[["Error"], "typing.Union[typing.Awaitable[None], None]"],
  6744. ) -> None:
  6745. """
  6746. Emitted when an uncaught exception happens within the page.
  6747. ```py
  6748. # Log all uncaught errors to the terminal
  6749. page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
  6750. # Navigate to a page with an exception.
  6751. await page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
  6752. ```"""
  6753. @typing.overload
  6754. def once(
  6755. self,
  6756. event: Literal["popup"],
  6757. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6758. ) -> None:
  6759. """
  6760. Emitted when the page opens a new tab or window. This event is emitted in addition to the
  6761. `browser_context.on('page')`, but only for popups relevant to this page.
  6762. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  6763. popup with `window.open('http://example.com')`, this event will fire when the network request to
  6764. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  6765. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  6766. instead of similar methods on the `Page`.
  6767. ```py
  6768. async with page.expect_event(\"popup\") as page_info:
  6769. await page.get_by_text(\"open the popup\").click()
  6770. popup = await page_info.value
  6771. print(await popup.evaluate(\"location.href\"))
  6772. ```
  6773. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  6774. need it in most cases)."""
  6775. @typing.overload
  6776. def once(
  6777. self,
  6778. event: Literal["request"],
  6779. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6780. ) -> None:
  6781. """
  6782. Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
  6783. see `page.route()` or `browser_context.route()`."""
  6784. @typing.overload
  6785. def once(
  6786. self,
  6787. event: Literal["requestfailed"],
  6788. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6789. ) -> None:
  6790. """
  6791. Emitted when a request fails, for example by timing out.
  6792. ```python
  6793. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
  6794. ```
  6795. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  6796. will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
  6797. only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
  6798. net::ERR_FAILED."""
  6799. @typing.overload
  6800. def once(
  6801. self,
  6802. event: Literal["requestfinished"],
  6803. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6804. ) -> None:
  6805. """
  6806. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  6807. sequence of events is `request`, `response` and `requestfinished`."""
  6808. @typing.overload
  6809. def once(
  6810. self,
  6811. event: Literal["response"],
  6812. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  6813. ) -> None:
  6814. """
  6815. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  6816. events is `request`, `response` and `requestfinished`."""
  6817. @typing.overload
  6818. def once(
  6819. self,
  6820. event: Literal["websocket"],
  6821. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  6822. ) -> None:
  6823. """
  6824. Emitted when `WebSocket` request is sent."""
  6825. @typing.overload
  6826. def once(
  6827. self,
  6828. event: Literal["worker"],
  6829. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  6830. ) -> None:
  6831. """
  6832. Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
  6833. by the page."""
  6834. def once(
  6835. self,
  6836. event: str,
  6837. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6838. ) -> None:
  6839. return super().once(event=event, f=f)
  6840. @property
  6841. def keyboard(self) -> "Keyboard":
  6842. """Page.keyboard
  6843. Returns
  6844. -------
  6845. Keyboard
  6846. """
  6847. return mapping.from_impl(self._impl_obj.keyboard)
  6848. @property
  6849. def mouse(self) -> "Mouse":
  6850. """Page.mouse
  6851. Returns
  6852. -------
  6853. Mouse
  6854. """
  6855. return mapping.from_impl(self._impl_obj.mouse)
  6856. @property
  6857. def touchscreen(self) -> "Touchscreen":
  6858. """Page.touchscreen
  6859. Returns
  6860. -------
  6861. Touchscreen
  6862. """
  6863. return mapping.from_impl(self._impl_obj.touchscreen)
  6864. @property
  6865. def context(self) -> "BrowserContext":
  6866. """Page.context
  6867. Get the browser context that the page belongs to.
  6868. Returns
  6869. -------
  6870. BrowserContext
  6871. """
  6872. return mapping.from_impl(self._impl_obj.context)
  6873. @property
  6874. def clock(self) -> "Clock":
  6875. """Page.clock
  6876. Playwright has ability to mock clock and passage of time.
  6877. Returns
  6878. -------
  6879. Clock
  6880. """
  6881. return mapping.from_impl(self._impl_obj.clock)
  6882. @property
  6883. def main_frame(self) -> "Frame":
  6884. """Page.main_frame
  6885. The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
  6886. Returns
  6887. -------
  6888. Frame
  6889. """
  6890. return mapping.from_impl(self._impl_obj.main_frame)
  6891. @property
  6892. def frames(self) -> typing.List["Frame"]:
  6893. """Page.frames
  6894. An array of all frames attached to the page.
  6895. Returns
  6896. -------
  6897. List[Frame]
  6898. """
  6899. return mapping.from_impl_list(self._impl_obj.frames)
  6900. @property
  6901. def url(self) -> str:
  6902. """Page.url
  6903. Returns
  6904. -------
  6905. str
  6906. """
  6907. return mapping.from_maybe_impl(self._impl_obj.url)
  6908. @property
  6909. def viewport_size(self) -> typing.Optional[ViewportSize]:
  6910. """Page.viewport_size
  6911. Returns
  6912. -------
  6913. Union[{width: int, height: int}, None]
  6914. """
  6915. return mapping.from_impl_nullable(self._impl_obj.viewport_size)
  6916. @property
  6917. def workers(self) -> typing.List["Worker"]:
  6918. """Page.workers
  6919. This method returns all of the dedicated
  6920. [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
  6921. **NOTE** This does not contain ServiceWorkers
  6922. Returns
  6923. -------
  6924. List[Worker]
  6925. """
  6926. return mapping.from_impl_list(self._impl_obj.workers)
  6927. @property
  6928. def request(self) -> "APIRequestContext":
  6929. """Page.request
  6930. API testing helper associated with this page. This method returns the same instance as
  6931. `browser_context.request` on the page's context. See `browser_context.request` for more
  6932. details.
  6933. Returns
  6934. -------
  6935. APIRequestContext
  6936. """
  6937. return mapping.from_impl(self._impl_obj.request)
  6938. @property
  6939. def video(self) -> typing.Optional["Video"]:
  6940. """Page.video
  6941. Video object associated with this page. Can be used to access the video file when using the `recordVideo` context
  6942. option.
  6943. Returns
  6944. -------
  6945. Union[Video, None]
  6946. """
  6947. return mapping.from_impl_nullable(self._impl_obj.video)
  6948. @property
  6949. def screencast(self) -> "Screencast":
  6950. """Page.screencast
  6951. `Screencast` object associated with this page.
  6952. **Usage**
  6953. Returns
  6954. -------
  6955. Screencast
  6956. """
  6957. return mapping.from_impl(self._impl_obj.screencast)
  6958. async def opener(self) -> typing.Optional["Page"]:
  6959. """Page.opener
  6960. Returns the opener for popup pages and `null` for others. If the opener has been closed already the returns `null`.
  6961. Returns
  6962. -------
  6963. Union[Page, None]
  6964. """
  6965. return mapping.from_impl_nullable(await self._impl_obj.opener())
  6966. def frame(
  6967. self,
  6968. name: typing.Optional[str] = None,
  6969. *,
  6970. url: typing.Optional[
  6971. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  6972. ] = None,
  6973. ) -> typing.Optional["Frame"]:
  6974. """Page.frame
  6975. Returns frame matching the specified criteria. Either `name` or `url` must be specified.
  6976. **Usage**
  6977. ```py
  6978. frame = page.frame(name=\"frame-name\")
  6979. ```
  6980. Parameters
  6981. ----------
  6982. name : Union[str, None]
  6983. Frame name specified in the `iframe`'s `name` attribute. Optional.
  6984. url : Union[Callable[[str], bool], Pattern[str], str, None]
  6985. A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object. Optional.
  6986. Returns
  6987. -------
  6988. Union[Frame, None]
  6989. """
  6990. return mapping.from_impl_nullable(
  6991. self._impl_obj.frame(name=name, url=self._wrap_handler(url))
  6992. )
  6993. def set_default_navigation_timeout(
  6994. self, timeout: typing.Union[float, datetime.timedelta]
  6995. ) -> None:
  6996. """Page.set_default_navigation_timeout
  6997. This setting will change the default maximum navigation time for the following methods and related shortcuts:
  6998. - `page.go_back()`
  6999. - `page.go_forward()`
  7000. - `page.goto()`
  7001. - `page.reload()`
  7002. - `page.set_content()`
  7003. - `page.expect_navigation()`
  7004. - `page.wait_for_url()`
  7005. **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`,
  7006. `browser_context.set_default_timeout()` and `browser_context.set_default_navigation_timeout()`.
  7007. Parameters
  7008. ----------
  7009. timeout : float
  7010. Maximum navigation time in milliseconds
  7011. """
  7012. return mapping.from_maybe_impl(
  7013. self._impl_obj.set_default_navigation_timeout(
  7014. timeout=to_milliseconds(timeout)
  7015. )
  7016. )
  7017. def set_default_timeout(
  7018. self, timeout: typing.Union[float, datetime.timedelta]
  7019. ) -> None:
  7020. """Page.set_default_timeout
  7021. This setting will change the default maximum time for all the methods accepting `timeout` option.
  7022. **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`.
  7023. Parameters
  7024. ----------
  7025. timeout : float
  7026. Maximum time in milliseconds. Pass `0` to disable timeout.
  7027. """
  7028. return mapping.from_maybe_impl(
  7029. self._impl_obj.set_default_timeout(timeout=to_milliseconds(timeout))
  7030. )
  7031. async def query_selector(
  7032. self, selector: str, *, strict: typing.Optional[bool] = None
  7033. ) -> typing.Optional["ElementHandle"]:
  7034. """Page.query_selector
  7035. The method finds an element matching the specified selector within the page. If no elements match the selector, the
  7036. return value resolves to `null`. To wait for an element on the page, use `locator.wait_for()`.
  7037. Parameters
  7038. ----------
  7039. selector : str
  7040. A selector to query for.
  7041. strict : Union[bool, None]
  7042. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7043. element, the call throws an exception.
  7044. Returns
  7045. -------
  7046. Union[ElementHandle, None]
  7047. """
  7048. return mapping.from_impl_nullable(
  7049. await self._impl_obj.query_selector(selector=selector, strict=strict)
  7050. )
  7051. async def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  7052. """Page.query_selector_all
  7053. The method finds all elements matching the specified selector within the page. If no elements match the selector,
  7054. the return value resolves to `[]`.
  7055. Parameters
  7056. ----------
  7057. selector : str
  7058. A selector to query for.
  7059. Returns
  7060. -------
  7061. List[ElementHandle]
  7062. """
  7063. return mapping.from_impl_list(
  7064. await self._impl_obj.query_selector_all(selector=selector)
  7065. )
  7066. async def wait_for_selector(
  7067. self,
  7068. selector: str,
  7069. *,
  7070. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7071. state: typing.Optional[
  7072. Literal["attached", "detached", "hidden", "visible"]
  7073. ] = None,
  7074. strict: typing.Optional[bool] = None,
  7075. ) -> typing.Optional["ElementHandle"]:
  7076. """Page.wait_for_selector
  7077. Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
  7078. `detached`.
  7079. **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
  7080. objects and web-first assertions makes the code wait-for-selector-free.
  7081. Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
  7082. at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
  7083. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
  7084. **Usage**
  7085. This method works across navigations:
  7086. ```py
  7087. import asyncio
  7088. from playwright.async_api import async_playwright, Playwright
  7089. async def run(playwright: Playwright):
  7090. chromium = playwright.chromium
  7091. browser = await chromium.launch()
  7092. page = await browser.new_page()
  7093. for current_url in [\"https://google.com\", \"https://bbc.com\"]:
  7094. await page.goto(current_url, wait_until=\"domcontentloaded\")
  7095. element = await page.wait_for_selector(\"img\")
  7096. print(\"Loaded image: \" + str(await element.get_attribute(\"src\")))
  7097. await browser.close()
  7098. async def main():
  7099. async with async_playwright() as playwright:
  7100. await run(playwright)
  7101. asyncio.run(main())
  7102. ```
  7103. Parameters
  7104. ----------
  7105. selector : str
  7106. A selector to query for.
  7107. timeout : Union[float, None]
  7108. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7109. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7110. state : Union["attached", "detached", "hidden", "visible", None]
  7111. Defaults to `'visible'`. Can be either:
  7112. - `'attached'` - wait for element to be present in DOM.
  7113. - `'detached'` - wait for element to not be present in DOM.
  7114. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  7115. without any content or with `display:none` has an empty bounding box and is not considered visible.
  7116. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  7117. `visibility:hidden`. This is opposite to the `'visible'` option.
  7118. strict : Union[bool, None]
  7119. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7120. element, the call throws an exception.
  7121. Returns
  7122. -------
  7123. Union[ElementHandle, None]
  7124. """
  7125. return mapping.from_impl_nullable(
  7126. await self._impl_obj.wait_for_selector(
  7127. selector=selector,
  7128. timeout=to_milliseconds(timeout),
  7129. state=state,
  7130. strict=strict,
  7131. )
  7132. )
  7133. async def is_checked(
  7134. self,
  7135. selector: str,
  7136. *,
  7137. strict: typing.Optional[bool] = None,
  7138. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7139. ) -> bool:
  7140. """Page.is_checked
  7141. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  7142. Parameters
  7143. ----------
  7144. selector : str
  7145. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7146. used.
  7147. strict : Union[bool, None]
  7148. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7149. element, the call throws an exception.
  7150. timeout : Union[float, None]
  7151. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7152. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7153. Returns
  7154. -------
  7155. bool
  7156. """
  7157. return mapping.from_maybe_impl(
  7158. await self._impl_obj.is_checked(
  7159. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  7160. )
  7161. )
  7162. async def is_disabled(
  7163. self,
  7164. selector: str,
  7165. *,
  7166. strict: typing.Optional[bool] = None,
  7167. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7168. ) -> bool:
  7169. """Page.is_disabled
  7170. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  7171. Parameters
  7172. ----------
  7173. selector : str
  7174. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7175. used.
  7176. strict : Union[bool, None]
  7177. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7178. element, the call throws an exception.
  7179. timeout : Union[float, None]
  7180. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7181. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7182. Returns
  7183. -------
  7184. bool
  7185. """
  7186. return mapping.from_maybe_impl(
  7187. await self._impl_obj.is_disabled(
  7188. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  7189. )
  7190. )
  7191. async def is_editable(
  7192. self,
  7193. selector: str,
  7194. *,
  7195. strict: typing.Optional[bool] = None,
  7196. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7197. ) -> bool:
  7198. """Page.is_editable
  7199. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  7200. Parameters
  7201. ----------
  7202. selector : str
  7203. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7204. used.
  7205. strict : Union[bool, None]
  7206. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7207. element, the call throws an exception.
  7208. timeout : Union[float, None]
  7209. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7210. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7211. Returns
  7212. -------
  7213. bool
  7214. """
  7215. return mapping.from_maybe_impl(
  7216. await self._impl_obj.is_editable(
  7217. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  7218. )
  7219. )
  7220. async def is_enabled(
  7221. self,
  7222. selector: str,
  7223. *,
  7224. strict: typing.Optional[bool] = None,
  7225. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7226. ) -> bool:
  7227. """Page.is_enabled
  7228. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  7229. Parameters
  7230. ----------
  7231. selector : str
  7232. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7233. used.
  7234. strict : Union[bool, None]
  7235. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7236. element, the call throws an exception.
  7237. timeout : Union[float, None]
  7238. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7239. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7240. Returns
  7241. -------
  7242. bool
  7243. """
  7244. return mapping.from_maybe_impl(
  7245. await self._impl_obj.is_enabled(
  7246. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  7247. )
  7248. )
  7249. async def is_hidden(
  7250. self,
  7251. selector: str,
  7252. *,
  7253. strict: typing.Optional[bool] = None,
  7254. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7255. ) -> bool:
  7256. """Page.is_hidden
  7257. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
  7258. does not match any elements is considered hidden.
  7259. Parameters
  7260. ----------
  7261. selector : str
  7262. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7263. used.
  7264. strict : Union[bool, None]
  7265. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7266. element, the call throws an exception.
  7267. timeout : Union[float, None]
  7268. Deprecated: This option is ignored. `page.is_hidden()` does not wait for the↵element to become hidden and returns immediately.
  7269. Returns
  7270. -------
  7271. bool
  7272. """
  7273. return mapping.from_maybe_impl(
  7274. await self._impl_obj.is_hidden(
  7275. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  7276. )
  7277. )
  7278. async def is_visible(
  7279. self,
  7280. selector: str,
  7281. *,
  7282. strict: typing.Optional[bool] = None,
  7283. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7284. ) -> bool:
  7285. """Page.is_visible
  7286. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
  7287. is considered not visible.
  7288. Parameters
  7289. ----------
  7290. selector : str
  7291. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7292. used.
  7293. strict : Union[bool, None]
  7294. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7295. element, the call throws an exception.
  7296. timeout : Union[float, None]
  7297. Deprecated: This option is ignored. `page.is_visible()` does not wait↵for the element to become visible and returns immediately.
  7298. Returns
  7299. -------
  7300. bool
  7301. """
  7302. return mapping.from_maybe_impl(
  7303. await self._impl_obj.is_visible(
  7304. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  7305. )
  7306. )
  7307. async def dispatch_event(
  7308. self,
  7309. selector: str,
  7310. type: str,
  7311. event_init: typing.Optional[typing.Dict] = None,
  7312. *,
  7313. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7314. strict: typing.Optional[bool] = None,
  7315. ) -> None:
  7316. """Page.dispatch_event
  7317. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  7318. `click` is dispatched. This is equivalent to calling
  7319. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  7320. **Usage**
  7321. ```py
  7322. await page.dispatch_event(\"button#submit\", \"click\")
  7323. ```
  7324. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  7325. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  7326. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  7327. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  7328. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  7329. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  7330. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  7331. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  7332. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  7333. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  7334. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  7335. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  7336. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  7337. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  7338. ```py
  7339. # note you can only create data_transfer in chromium and firefox
  7340. data_transfer = await page.evaluate_handle(\"new DataTransfer()\")
  7341. await page.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
  7342. ```
  7343. Parameters
  7344. ----------
  7345. selector : str
  7346. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  7347. used.
  7348. type : str
  7349. DOM event type: `"click"`, `"dragstart"`, etc.
  7350. event_init : Union[Dict, None]
  7351. Optional event-specific initialization properties.
  7352. timeout : Union[float, None]
  7353. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7354. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7355. strict : Union[bool, None]
  7356. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7357. element, the call throws an exception.
  7358. """
  7359. return mapping.from_maybe_impl(
  7360. await self._impl_obj.dispatch_event(
  7361. selector=selector,
  7362. type=type,
  7363. eventInit=mapping.to_impl(event_init),
  7364. timeout=to_milliseconds(timeout),
  7365. strict=strict,
  7366. )
  7367. )
  7368. async def evaluate(
  7369. self, expression: str, arg: typing.Optional[typing.Any] = None
  7370. ) -> typing.Any:
  7371. """Page.evaluate
  7372. Returns the value of the `expression` invocation.
  7373. If the function passed to the `page.evaluate()` returns a [Promise], then `page.evaluate()` would
  7374. wait for the promise to resolve and return its value.
  7375. If the function passed to the `page.evaluate()` returns a non-[Serializable] value, then
  7376. `page.evaluate()` resolves to `undefined`. Playwright also supports transferring some additional values
  7377. that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  7378. **Usage**
  7379. Passing argument to `expression`:
  7380. ```py
  7381. result = await page.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
  7382. print(result) # prints \"56\"
  7383. ```
  7384. A string can also be passed in instead of a function:
  7385. ```py
  7386. print(await page.evaluate(\"1 + 2\")) # prints \"3\"
  7387. x = 10
  7388. print(await page.evaluate(f\"1 + {x}\")) # prints \"11\"
  7389. ```
  7390. `ElementHandle` instances can be passed as an argument to the `page.evaluate()`:
  7391. ```py
  7392. body_handle = await page.evaluate(\"document.body\")
  7393. html = await page.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
  7394. await body_handle.dispose()
  7395. ```
  7396. Parameters
  7397. ----------
  7398. expression : str
  7399. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7400. function is automatically invoked.
  7401. arg : Union[Any, None]
  7402. Optional argument to pass to `expression`.
  7403. Returns
  7404. -------
  7405. Any
  7406. """
  7407. return mapping.from_maybe_impl(
  7408. await self._impl_obj.evaluate(
  7409. expression=expression, arg=mapping.to_impl(arg)
  7410. )
  7411. )
  7412. async def evaluate_handle(
  7413. self, expression: str, arg: typing.Optional[typing.Any] = None
  7414. ) -> "JSHandle":
  7415. """Page.evaluate_handle
  7416. Returns the value of the `expression` invocation as a `JSHandle`.
  7417. The only difference between `page.evaluate()` and `page.evaluate_handle()` is that
  7418. `page.evaluate_handle()` returns `JSHandle`.
  7419. If the function passed to the `page.evaluate_handle()` returns a [Promise], then
  7420. `page.evaluate_handle()` would wait for the promise to resolve and return its value.
  7421. **Usage**
  7422. ```py
  7423. a_window_handle = await page.evaluate_handle(\"Promise.resolve(window)\")
  7424. a_window_handle # handle for the window object.
  7425. ```
  7426. A string can also be passed in instead of a function:
  7427. ```py
  7428. a_handle = await page.evaluate_handle(\"document\") # handle for the \"document\"
  7429. ```
  7430. `JSHandle` instances can be passed as an argument to the `page.evaluate_handle()`:
  7431. ```py
  7432. a_handle = await page.evaluate_handle(\"document.body\")
  7433. result_handle = await page.evaluate_handle(\"body => body.innerHTML\", a_handle)
  7434. print(await result_handle.json_value())
  7435. await result_handle.dispose()
  7436. ```
  7437. Parameters
  7438. ----------
  7439. expression : str
  7440. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7441. function is automatically invoked.
  7442. arg : Union[Any, None]
  7443. Optional argument to pass to `expression`.
  7444. Returns
  7445. -------
  7446. JSHandle
  7447. """
  7448. return mapping.from_impl(
  7449. await self._impl_obj.evaluate_handle(
  7450. expression=expression, arg=mapping.to_impl(arg)
  7451. )
  7452. )
  7453. async def eval_on_selector(
  7454. self,
  7455. selector: str,
  7456. expression: str,
  7457. arg: typing.Optional[typing.Any] = None,
  7458. *,
  7459. strict: typing.Optional[bool] = None,
  7460. ) -> typing.Any:
  7461. """Page.eval_on_selector
  7462. The method finds an element matching the specified selector within the page and passes it as a first argument to
  7463. `expression`. If no elements match the selector, the method throws an error. Returns the value of `expression`.
  7464. If `expression` returns a [Promise], then `page.eval_on_selector()` would wait for the promise to resolve and
  7465. return its value.
  7466. **Usage**
  7467. ```py
  7468. search_value = await page.eval_on_selector(\"#search\", \"el => el.value\")
  7469. preload_href = await page.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
  7470. html = await page.eval_on_selector(\".main-container\", \"(e, suffix) => e.outer_html + suffix\", \"hello\")
  7471. ```
  7472. Parameters
  7473. ----------
  7474. selector : str
  7475. A selector to query for.
  7476. expression : str
  7477. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7478. function is automatically invoked.
  7479. arg : Union[Any, None]
  7480. Optional argument to pass to `expression`.
  7481. strict : Union[bool, None]
  7482. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7483. element, the call throws an exception.
  7484. Returns
  7485. -------
  7486. Any
  7487. """
  7488. return mapping.from_maybe_impl(
  7489. await self._impl_obj.eval_on_selector(
  7490. selector=selector,
  7491. expression=expression,
  7492. arg=mapping.to_impl(arg),
  7493. strict=strict,
  7494. )
  7495. )
  7496. async def eval_on_selector_all(
  7497. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  7498. ) -> typing.Any:
  7499. """Page.eval_on_selector_all
  7500. The method finds all elements matching the specified selector within the page and passes an array of matched
  7501. elements as a first argument to `expression`. Returns the result of `expression` invocation.
  7502. If `expression` returns a [Promise], then `page.eval_on_selector_all()` would wait for the promise to resolve
  7503. and return its value.
  7504. **Usage**
  7505. ```py
  7506. div_counts = await page.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
  7507. ```
  7508. Parameters
  7509. ----------
  7510. selector : str
  7511. A selector to query for.
  7512. expression : str
  7513. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7514. function is automatically invoked.
  7515. arg : Union[Any, None]
  7516. Optional argument to pass to `expression`.
  7517. Returns
  7518. -------
  7519. Any
  7520. """
  7521. return mapping.from_maybe_impl(
  7522. await self._impl_obj.eval_on_selector_all(
  7523. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  7524. )
  7525. )
  7526. async def add_script_tag(
  7527. self,
  7528. *,
  7529. url: typing.Optional[str] = None,
  7530. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7531. content: typing.Optional[str] = None,
  7532. type: typing.Optional[str] = None,
  7533. ) -> "ElementHandle":
  7534. """Page.add_script_tag
  7535. Adds a `<script>` tag into the page with the desired url or content. Returns the added tag when the script's onload
  7536. fires or when the script content was injected into frame.
  7537. Parameters
  7538. ----------
  7539. url : Union[str, None]
  7540. URL of a script to be added.
  7541. path : Union[pathlib.Path, str, None]
  7542. Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
  7543. to the current working directory.
  7544. content : Union[str, None]
  7545. Raw JavaScript content to be injected into frame.
  7546. type : Union[str, None]
  7547. Script type. Use 'module' in order to load a JavaScript ES6 module. See
  7548. [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
  7549. Returns
  7550. -------
  7551. ElementHandle
  7552. """
  7553. return mapping.from_impl(
  7554. await self._impl_obj.add_script_tag(
  7555. url=url, path=path, content=content, type=type
  7556. )
  7557. )
  7558. async def add_style_tag(
  7559. self,
  7560. *,
  7561. url: typing.Optional[str] = None,
  7562. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7563. content: typing.Optional[str] = None,
  7564. ) -> "ElementHandle":
  7565. """Page.add_style_tag
  7566. Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
  7567. content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
  7568. Parameters
  7569. ----------
  7570. url : Union[str, None]
  7571. URL of the `<link>` tag.
  7572. path : Union[pathlib.Path, str, None]
  7573. Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
  7574. current working directory.
  7575. content : Union[str, None]
  7576. Raw CSS content to be injected into frame.
  7577. Returns
  7578. -------
  7579. ElementHandle
  7580. """
  7581. return mapping.from_impl(
  7582. await self._impl_obj.add_style_tag(url=url, path=path, content=content)
  7583. )
  7584. async def expose_function(
  7585. self, name: str, callback: typing.Callable
  7586. ) -> "AsyncContextManager":
  7587. """Page.expose_function
  7588. The method adds a function called `name` on the `window` object of every frame in the page. When called, the
  7589. function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  7590. If the `callback` returns a [Promise], it will be awaited.
  7591. See `browser_context.expose_function()` for context-wide exposed function.
  7592. **NOTE** Functions installed via `page.expose_function()` survive navigations.
  7593. **Usage**
  7594. An example of adding a `sha256` function to the page:
  7595. ```py
  7596. import asyncio
  7597. import hashlib
  7598. from playwright.async_api import async_playwright, Playwright
  7599. def sha256(text):
  7600. m = hashlib.sha256()
  7601. m.update(bytes(text, \"utf8\"))
  7602. return m.hexdigest()
  7603. async def run(playwright: Playwright):
  7604. webkit = playwright.webkit
  7605. browser = await webkit.launch(headless=False)
  7606. page = await browser.new_page()
  7607. await page.expose_function(\"sha256\", sha256)
  7608. await page.set_content(\"\"\"
  7609. <script>
  7610. async function onClick() {
  7611. document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  7612. }
  7613. </script>
  7614. <button onclick=\"onClick()\">Click me</button>
  7615. <div></div>
  7616. \"\"\")
  7617. await page.click(\"button\")
  7618. async def main():
  7619. async with async_playwright() as playwright:
  7620. await run(playwright)
  7621. asyncio.run(main())
  7622. ```
  7623. Parameters
  7624. ----------
  7625. name : str
  7626. Name of the function on the window object
  7627. callback : Callable
  7628. Callback function which will be called in Playwright's context.
  7629. Returns
  7630. -------
  7631. AsyncContextManager
  7632. """
  7633. return mapping.from_impl(
  7634. await self._impl_obj.expose_function(
  7635. name=name, callback=self._wrap_handler(callback)
  7636. )
  7637. )
  7638. async def expose_binding(
  7639. self, name: str, callback: typing.Callable
  7640. ) -> "AsyncContextManager":
  7641. """Page.expose_binding
  7642. The method adds a function called `name` on the `window` object of every frame in this page. When called, the
  7643. function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the
  7644. `callback` returns a [Promise], it will be awaited.
  7645. The first argument of the `callback` function contains information about the caller: `{ browserContext:
  7646. BrowserContext, page: Page, frame: Frame }`.
  7647. See `browser_context.expose_binding()` for the context-wide version.
  7648. **NOTE** Functions installed via `page.expose_binding()` survive navigations.
  7649. **Usage**
  7650. An example of exposing page URL to all frames in a page:
  7651. ```py
  7652. import asyncio
  7653. from playwright.async_api import async_playwright, Playwright
  7654. async def run(playwright: Playwright):
  7655. webkit = playwright.webkit
  7656. browser = await webkit.launch(headless=False)
  7657. context = await browser.new_context()
  7658. page = await context.new_page()
  7659. await page.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
  7660. await page.set_content(\"\"\"
  7661. <script>
  7662. async function onClick() {
  7663. document.querySelector('div').textContent = await window.pageURL();
  7664. }
  7665. </script>
  7666. <button onclick=\"onClick()\">Click me</button>
  7667. <div></div>
  7668. \"\"\")
  7669. await page.click(\"button\")
  7670. async def main():
  7671. async with async_playwright() as playwright:
  7672. await run(playwright)
  7673. asyncio.run(main())
  7674. ```
  7675. Parameters
  7676. ----------
  7677. name : str
  7678. Name of the function on the window object.
  7679. callback : Callable
  7680. Callback function that will be called in the Playwright's context.
  7681. Returns
  7682. -------
  7683. AsyncContextManager
  7684. """
  7685. return mapping.from_impl(
  7686. await self._impl_obj.expose_binding(
  7687. name=name, callback=self._wrap_handler(callback)
  7688. )
  7689. )
  7690. async def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
  7691. """Page.set_extra_http_headers
  7692. The extra HTTP headers will be sent with every request the page initiates.
  7693. **NOTE** `page.set_extra_http_headers()` does not guarantee the order of headers in the outgoing requests.
  7694. Parameters
  7695. ----------
  7696. headers : Dict[str, str]
  7697. An object containing additional HTTP headers to be sent with every request. All header values must be strings.
  7698. """
  7699. return mapping.from_maybe_impl(
  7700. await self._impl_obj.set_extra_http_headers(
  7701. headers=mapping.to_impl(headers)
  7702. )
  7703. )
  7704. async def content(self) -> str:
  7705. """Page.content
  7706. Gets the full HTML contents of the page, including the doctype.
  7707. Returns
  7708. -------
  7709. str
  7710. """
  7711. return mapping.from_maybe_impl(await self._impl_obj.content())
  7712. async def set_content(
  7713. self,
  7714. html: str,
  7715. *,
  7716. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7717. wait_until: typing.Optional[
  7718. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7719. ] = None,
  7720. ) -> None:
  7721. """Page.set_content
  7722. This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
  7723. inheriting all its specific characteristics and behaviors.
  7724. Parameters
  7725. ----------
  7726. html : str
  7727. HTML markup to assign to the page.
  7728. timeout : Union[float, None]
  7729. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7730. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7731. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7732. `page.set_default_timeout()` methods.
  7733. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7734. When to consider operation succeeded, defaults to `load`. Events can be either:
  7735. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7736. - `'load'` - consider operation to be finished when the `load` event is fired.
  7737. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7738. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7739. - `'commit'` - consider operation to be finished when network response is received and the document started
  7740. loading.
  7741. """
  7742. return mapping.from_maybe_impl(
  7743. await self._impl_obj.set_content(
  7744. html=html, timeout=to_milliseconds(timeout), waitUntil=wait_until
  7745. )
  7746. )
  7747. async def goto(
  7748. self,
  7749. url: str,
  7750. *,
  7751. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7752. wait_until: typing.Optional[
  7753. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7754. ] = None,
  7755. referer: typing.Optional[str] = None,
  7756. ) -> typing.Optional["Response"]:
  7757. """Page.goto
  7758. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first
  7759. non-redirect response.
  7760. The method will throw an error if:
  7761. - there's an SSL error (e.g. in case of self-signed certificates).
  7762. - target URL is invalid.
  7763. - the `timeout` is exceeded during navigation.
  7764. - the remote server does not respond or is unreachable.
  7765. - the main resource failed to load.
  7766. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
  7767. \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
  7768. `response.status()`.
  7769. **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
  7770. to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
  7771. **NOTE** Headless mode doesn't support navigation to a PDF document. See the
  7772. [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
  7773. Parameters
  7774. ----------
  7775. url : str
  7776. URL to navigate page to. The url should include scheme, e.g. `https://`. When a `baseURL` via the context options
  7777. was provided and the passed URL is a path, it gets merged via the
  7778. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  7779. timeout : Union[float, None]
  7780. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7781. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7782. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7783. `page.set_default_timeout()` methods.
  7784. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7785. When to consider operation succeeded, defaults to `load`. Events can be either:
  7786. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7787. - `'load'` - consider operation to be finished when the `load` event is fired.
  7788. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7789. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7790. - `'commit'` - consider operation to be finished when network response is received and the document started
  7791. loading.
  7792. referer : Union[str, None]
  7793. Referer header value. If provided it will take preference over the referer header value set by
  7794. `page.set_extra_http_headers()`.
  7795. Returns
  7796. -------
  7797. Union[Response, None]
  7798. """
  7799. return mapping.from_impl_nullable(
  7800. await self._impl_obj.goto(
  7801. url=url,
  7802. timeout=to_milliseconds(timeout),
  7803. waitUntil=wait_until,
  7804. referer=referer,
  7805. )
  7806. )
  7807. async def reload(
  7808. self,
  7809. *,
  7810. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7811. wait_until: typing.Optional[
  7812. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7813. ] = None,
  7814. ) -> typing.Optional["Response"]:
  7815. """Page.reload
  7816. This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the
  7817. main resource response. In case of multiple redirects, the navigation will resolve with the response of the last
  7818. redirect.
  7819. Parameters
  7820. ----------
  7821. timeout : Union[float, None]
  7822. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7823. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7824. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7825. `page.set_default_timeout()` methods.
  7826. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7827. When to consider operation succeeded, defaults to `load`. Events can be either:
  7828. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7829. - `'load'` - consider operation to be finished when the `load` event is fired.
  7830. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7831. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7832. - `'commit'` - consider operation to be finished when network response is received and the document started
  7833. loading.
  7834. Returns
  7835. -------
  7836. Union[Response, None]
  7837. """
  7838. return mapping.from_impl_nullable(
  7839. await self._impl_obj.reload(
  7840. timeout=to_milliseconds(timeout), waitUntil=wait_until
  7841. )
  7842. )
  7843. async def wait_for_load_state(
  7844. self,
  7845. state: typing.Optional[
  7846. Literal["domcontentloaded", "load", "networkidle"]
  7847. ] = None,
  7848. *,
  7849. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7850. ) -> None:
  7851. """Page.wait_for_load_state
  7852. Returns when the required load state has been reached.
  7853. This resolves when the page reaches a required load state, `load` by default. The navigation must have been
  7854. committed when this method is called. If current document has already reached the required state, resolves
  7855. immediately.
  7856. **NOTE** Most of the time, this method is not needed because Playwright
  7857. [auto-waits before every action](https://playwright.dev/python/docs/actionability).
  7858. **Usage**
  7859. ```py
  7860. await page.get_by_role(\"button\").click() # click triggers navigation.
  7861. await page.wait_for_load_state() # the promise resolves after \"load\" event.
  7862. ```
  7863. ```py
  7864. async with page.expect_popup() as page_info:
  7865. await page.get_by_role(\"button\").click() # click triggers a popup.
  7866. popup = await page_info.value
  7867. # Wait for the \"DOMContentLoaded\" event.
  7868. await popup.wait_for_load_state(\"domcontentloaded\")
  7869. print(await popup.title()) # popup is ready to use.
  7870. ```
  7871. Parameters
  7872. ----------
  7873. state : Union["domcontentloaded", "load", "networkidle", None]
  7874. Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
  7875. document, the method resolves immediately. Can be one of:
  7876. - `'load'` - wait for the `load` event to be fired.
  7877. - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
  7878. - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
  7879. this method for testing, rely on web assertions to assess readiness instead.
  7880. timeout : Union[float, None]
  7881. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7882. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7883. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7884. `page.set_default_timeout()` methods.
  7885. """
  7886. return mapping.from_maybe_impl(
  7887. await self._impl_obj.wait_for_load_state(
  7888. state=state, timeout=to_milliseconds(timeout)
  7889. )
  7890. )
  7891. async def wait_for_url(
  7892. self,
  7893. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7894. *,
  7895. wait_until: typing.Optional[
  7896. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7897. ] = None,
  7898. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  7899. ) -> None:
  7900. """Page.wait_for_url
  7901. Waits for the main frame to navigate to the given URL.
  7902. **Usage**
  7903. ```py
  7904. await page.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  7905. await page.wait_for_url(\"**/target.html\")
  7906. ```
  7907. Parameters
  7908. ----------
  7909. url : Union[Callable[[str], bool], Pattern[str], str]
  7910. A glob pattern, regex pattern, or predicate receiving [URL] to match while waiting for the navigation. Note that if
  7911. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  7912. equal to the string.
  7913. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7914. When to consider operation succeeded, defaults to `load`. Events can be either:
  7915. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7916. - `'load'` - consider operation to be finished when the `load` event is fired.
  7917. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7918. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7919. - `'commit'` - consider operation to be finished when network response is received and the document started
  7920. loading.
  7921. timeout : Union[float, None]
  7922. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7923. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7924. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7925. `page.set_default_timeout()` methods.
  7926. """
  7927. return mapping.from_maybe_impl(
  7928. await self._impl_obj.wait_for_url(
  7929. url=self._wrap_handler(url),
  7930. waitUntil=wait_until,
  7931. timeout=to_milliseconds(timeout),
  7932. )
  7933. )
  7934. @typing.overload
  7935. async def wait_for_event(
  7936. self,
  7937. event: typing.Literal["close"],
  7938. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  7939. *,
  7940. timeout: typing.Optional[float] = None,
  7941. ) -> "Page": ...
  7942. @typing.overload
  7943. async def wait_for_event(
  7944. self,
  7945. event: typing.Literal["console"],
  7946. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  7947. *,
  7948. timeout: typing.Optional[float] = None,
  7949. ) -> "ConsoleMessage": ...
  7950. @typing.overload
  7951. async def wait_for_event(
  7952. self,
  7953. event: typing.Literal["crash"],
  7954. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  7955. *,
  7956. timeout: typing.Optional[float] = None,
  7957. ) -> "Page": ...
  7958. @typing.overload
  7959. async def wait_for_event(
  7960. self,
  7961. event: typing.Literal["dialog"],
  7962. predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None,
  7963. *,
  7964. timeout: typing.Optional[float] = None,
  7965. ) -> "Dialog": ...
  7966. @typing.overload
  7967. async def wait_for_event(
  7968. self,
  7969. event: typing.Literal["domcontentloaded"],
  7970. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  7971. *,
  7972. timeout: typing.Optional[float] = None,
  7973. ) -> "Page": ...
  7974. @typing.overload
  7975. async def wait_for_event(
  7976. self,
  7977. event: typing.Literal["download"],
  7978. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  7979. *,
  7980. timeout: typing.Optional[float] = None,
  7981. ) -> "Download": ...
  7982. @typing.overload
  7983. async def wait_for_event(
  7984. self,
  7985. event: typing.Literal["filechooser"],
  7986. predicate: typing.Optional[typing.Callable[["FileChooser"], bool]] = None,
  7987. *,
  7988. timeout: typing.Optional[float] = None,
  7989. ) -> "FileChooser": ...
  7990. @typing.overload
  7991. async def wait_for_event(
  7992. self,
  7993. event: typing.Literal["frameattached"],
  7994. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  7995. *,
  7996. timeout: typing.Optional[float] = None,
  7997. ) -> "Frame": ...
  7998. @typing.overload
  7999. async def wait_for_event(
  8000. self,
  8001. event: typing.Literal["framedetached"],
  8002. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  8003. *,
  8004. timeout: typing.Optional[float] = None,
  8005. ) -> "Frame": ...
  8006. @typing.overload
  8007. async def wait_for_event(
  8008. self,
  8009. event: typing.Literal["framenavigated"],
  8010. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  8011. *,
  8012. timeout: typing.Optional[float] = None,
  8013. ) -> "Frame": ...
  8014. @typing.overload
  8015. async def wait_for_event(
  8016. self,
  8017. event: typing.Literal["load"],
  8018. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  8019. *,
  8020. timeout: typing.Optional[float] = None,
  8021. ) -> "Page": ...
  8022. @typing.overload
  8023. async def wait_for_event(
  8024. self,
  8025. event: typing.Literal["pageerror"],
  8026. predicate: typing.Optional[typing.Callable[["Error"], bool]] = None,
  8027. *,
  8028. timeout: typing.Optional[float] = None,
  8029. ) -> "Error": ...
  8030. @typing.overload
  8031. async def wait_for_event(
  8032. self,
  8033. event: typing.Literal["popup"],
  8034. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  8035. *,
  8036. timeout: typing.Optional[float] = None,
  8037. ) -> "Page": ...
  8038. @typing.overload
  8039. async def wait_for_event(
  8040. self,
  8041. event: typing.Literal["request"],
  8042. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  8043. *,
  8044. timeout: typing.Optional[float] = None,
  8045. ) -> "Request": ...
  8046. @typing.overload
  8047. async def wait_for_event(
  8048. self,
  8049. event: typing.Literal["requestfailed"],
  8050. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  8051. *,
  8052. timeout: typing.Optional[float] = None,
  8053. ) -> "Request": ...
  8054. @typing.overload
  8055. async def wait_for_event(
  8056. self,
  8057. event: typing.Literal["requestfinished"],
  8058. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  8059. *,
  8060. timeout: typing.Optional[float] = None,
  8061. ) -> "Request": ...
  8062. @typing.overload
  8063. async def wait_for_event(
  8064. self,
  8065. event: typing.Literal["response"],
  8066. predicate: typing.Optional[typing.Callable[["Response"], bool]] = None,
  8067. *,
  8068. timeout: typing.Optional[float] = None,
  8069. ) -> "Response": ...
  8070. @typing.overload
  8071. async def wait_for_event(
  8072. self,
  8073. event: typing.Literal["websocket"],
  8074. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  8075. *,
  8076. timeout: typing.Optional[float] = None,
  8077. ) -> "WebSocket": ...
  8078. @typing.overload
  8079. async def wait_for_event(
  8080. self,
  8081. event: typing.Literal["worker"],
  8082. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  8083. *,
  8084. timeout: typing.Optional[float] = None,
  8085. ) -> "Worker": ...
  8086. @typing.overload
  8087. async def wait_for_event(
  8088. self,
  8089. event: str,
  8090. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  8091. *,
  8092. timeout: typing.Optional[float] = None,
  8093. ) -> typing.Any: ...
  8094. async def wait_for_event(
  8095. self,
  8096. event: str,
  8097. predicate: typing.Optional[typing.Callable] = None,
  8098. *,
  8099. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8100. ) -> typing.Any:
  8101. """Page.wait_for_event
  8102. **NOTE** In most cases, you should use `page.expect_event()`.
  8103. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  8104. and waits for `predicate(event)` to return a truthy value. Will throw an error if the page is closed before the
  8105. `event` is fired.
  8106. Parameters
  8107. ----------
  8108. event : str
  8109. Event name, same one typically passed into `*.on(event)`.
  8110. predicate : Union[Callable, None]
  8111. Receives the event data and resolves to truthy value when the waiting should resolve.
  8112. timeout : Union[float, None]
  8113. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  8114. default value can be changed by using the `browser_context.set_default_timeout()`.
  8115. Returns
  8116. -------
  8117. Any
  8118. """
  8119. return mapping.from_maybe_impl(
  8120. await self._impl_obj.wait_for_event(
  8121. event=event,
  8122. predicate=self._wrap_handler(predicate),
  8123. timeout=to_milliseconds(timeout),
  8124. )
  8125. )
  8126. async def go_back(
  8127. self,
  8128. *,
  8129. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8130. wait_until: typing.Optional[
  8131. Literal["commit", "domcontentloaded", "load", "networkidle"]
  8132. ] = None,
  8133. ) -> typing.Optional["Response"]:
  8134. """Page.go_back
  8135. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  8136. the last redirect. If cannot go back, returns `null`.
  8137. Navigate to the previous page in history.
  8138. Parameters
  8139. ----------
  8140. timeout : Union[float, None]
  8141. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  8142. be changed by using the `browser_context.set_default_navigation_timeout()`,
  8143. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  8144. `page.set_default_timeout()` methods.
  8145. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  8146. When to consider operation succeeded, defaults to `load`. Events can be either:
  8147. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  8148. - `'load'` - consider operation to be finished when the `load` event is fired.
  8149. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  8150. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  8151. - `'commit'` - consider operation to be finished when network response is received and the document started
  8152. loading.
  8153. Returns
  8154. -------
  8155. Union[Response, None]
  8156. """
  8157. return mapping.from_impl_nullable(
  8158. await self._impl_obj.go_back(
  8159. timeout=to_milliseconds(timeout), waitUntil=wait_until
  8160. )
  8161. )
  8162. async def go_forward(
  8163. self,
  8164. *,
  8165. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8166. wait_until: typing.Optional[
  8167. Literal["commit", "domcontentloaded", "load", "networkidle"]
  8168. ] = None,
  8169. ) -> typing.Optional["Response"]:
  8170. """Page.go_forward
  8171. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  8172. the last redirect. If cannot go forward, returns `null`.
  8173. Navigate to the next page in history.
  8174. Parameters
  8175. ----------
  8176. timeout : Union[float, None]
  8177. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  8178. be changed by using the `browser_context.set_default_navigation_timeout()`,
  8179. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  8180. `page.set_default_timeout()` methods.
  8181. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  8182. When to consider operation succeeded, defaults to `load`. Events can be either:
  8183. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  8184. - `'load'` - consider operation to be finished when the `load` event is fired.
  8185. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  8186. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  8187. - `'commit'` - consider operation to be finished when network response is received and the document started
  8188. loading.
  8189. Returns
  8190. -------
  8191. Union[Response, None]
  8192. """
  8193. return mapping.from_impl_nullable(
  8194. await self._impl_obj.go_forward(
  8195. timeout=to_milliseconds(timeout), waitUntil=wait_until
  8196. )
  8197. )
  8198. async def request_gc(self) -> None:
  8199. """Page.request_gc
  8200. Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will
  8201. be collected.
  8202. This is useful to help detect memory leaks. For example, if your page has a large object `'suspect'` that might be
  8203. leaked, you can check that it does not leak by using a
  8204. [`WeakRef`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef).
  8205. ```py
  8206. # 1. In your page, save a WeakRef for the \"suspect\".
  8207. await page.evaluate(\"globalThis.suspectWeakRef = new WeakRef(suspect)\")
  8208. # 2. Request garbage collection.
  8209. await page.request_gc()
  8210. # 3. Check that weak ref does not deref to the original object.
  8211. assert await page.evaluate(\"!globalThis.suspectWeakRef.deref()\")
  8212. ```
  8213. """
  8214. return mapping.from_maybe_impl(await self._impl_obj.request_gc())
  8215. async def emulate_media(
  8216. self,
  8217. *,
  8218. media: typing.Optional[Literal["null", "print", "screen"]] = None,
  8219. color_scheme: typing.Optional[
  8220. Literal["dark", "light", "no-preference", "null"]
  8221. ] = None,
  8222. reduced_motion: typing.Optional[
  8223. Literal["no-preference", "null", "reduce"]
  8224. ] = None,
  8225. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  8226. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  8227. ) -> None:
  8228. """Page.emulate_media
  8229. This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media
  8230. feature, using the `colorScheme` argument.
  8231. **Usage**
  8232. ```py
  8233. await page.evaluate(\"matchMedia('screen').matches\")
  8234. # → True
  8235. await page.evaluate(\"matchMedia('print').matches\")
  8236. # → False
  8237. await page.emulate_media(media=\"print\")
  8238. await page.evaluate(\"matchMedia('screen').matches\")
  8239. # → False
  8240. await page.evaluate(\"matchMedia('print').matches\")
  8241. # → True
  8242. await page.emulate_media()
  8243. await page.evaluate(\"matchMedia('screen').matches\")
  8244. # → True
  8245. await page.evaluate(\"matchMedia('print').matches\")
  8246. # → False
  8247. ```
  8248. ```py
  8249. await page.emulate_media(color_scheme=\"dark\")
  8250. await page.evaluate(\"matchMedia('(prefers-color-scheme: dark)').matches\")
  8251. # → True
  8252. await page.evaluate(\"matchMedia('(prefers-color-scheme: light)').matches\")
  8253. # → False
  8254. ```
  8255. Parameters
  8256. ----------
  8257. media : Union["null", "print", "screen", None]
  8258. Changes the CSS media type of the page. The only allowed values are `'Screen'`, `'Print'` and `'Null'`. Passing
  8259. `'Null'` disables CSS media emulation.
  8260. color_scheme : Union["dark", "light", "no-preference", "null", None]
  8261. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  8262. media feature, supported values are `'light'` and `'dark'`. Passing `'Null'` disables color scheme emulation.
  8263. `'no-preference'` is deprecated.
  8264. reduced_motion : Union["no-preference", "null", "reduce", None]
  8265. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. Passing
  8266. `null` disables reduced motion emulation.
  8267. forced_colors : Union["active", "none", "null", None]
  8268. contrast : Union["more", "no-preference", "null", None]
  8269. """
  8270. return mapping.from_maybe_impl(
  8271. await self._impl_obj.emulate_media(
  8272. media=media,
  8273. colorScheme=color_scheme,
  8274. reducedMotion=reduced_motion,
  8275. forcedColors=forced_colors,
  8276. contrast=contrast,
  8277. )
  8278. )
  8279. async def set_viewport_size(self, viewport_size: ViewportSize) -> None:
  8280. """Page.set_viewport_size
  8281. In the case of multiple pages in a single browser, each page can have its own viewport size. However,
  8282. `browser.new_context()` allows to set viewport size (and more) for all pages in the context at once.
  8283. `page.set_viewport_size()` will resize the page. A lot of websites don't expect phones to change size, so you
  8284. should set the viewport size before navigating to the page. `page.set_viewport_size()` will also reset
  8285. `screen` size, use `browser.new_context()` with `screen` and `viewport` parameters if you need better
  8286. control of these properties.
  8287. **Usage**
  8288. ```py
  8289. page = await browser.new_page()
  8290. await page.set_viewport_size({\"width\": 640, \"height\": 480})
  8291. await page.goto(\"https://example.com\")
  8292. ```
  8293. Parameters
  8294. ----------
  8295. viewport_size : {width: int, height: int}
  8296. """
  8297. return mapping.from_maybe_impl(
  8298. await self._impl_obj.set_viewport_size(viewportSize=viewport_size)
  8299. )
  8300. async def bring_to_front(self) -> None:
  8301. """Page.bring_to_front
  8302. Brings page to front (activates tab).
  8303. """
  8304. return mapping.from_maybe_impl(await self._impl_obj.bring_to_front())
  8305. async def hide_highlight(self) -> None:
  8306. """Page.hide_highlight
  8307. Hide all locator highlight overlays previously added by `locator.highlight()` on this page.
  8308. """
  8309. return mapping.from_maybe_impl(await self._impl_obj.hide_highlight())
  8310. async def add_init_script(
  8311. self,
  8312. script: typing.Optional[str] = None,
  8313. *,
  8314. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  8315. ) -> "AsyncContextManager":
  8316. """Page.add_init_script
  8317. Adds a script which would be evaluated in one of the following scenarios:
  8318. - Whenever the page is navigated.
  8319. - Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the
  8320. newly attached frame.
  8321. The script is evaluated after the document was created but before any of its scripts were run. This is useful to
  8322. amend the JavaScript environment, e.g. to seed `Math.random`.
  8323. **Usage**
  8324. An example of overriding `Math.random` before the page loads:
  8325. ```py
  8326. # in your playwright script, assuming the preload.js file is in same directory
  8327. await page.add_init_script(path=\"./preload.js\")
  8328. ```
  8329. **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
  8330. `page.add_init_script()` is not defined.
  8331. Parameters
  8332. ----------
  8333. script : Union[str, None]
  8334. Script to be evaluated in all pages in the browser context. Optional.
  8335. path : Union[pathlib.Path, str, None]
  8336. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  8337. directory. Optional.
  8338. Returns
  8339. -------
  8340. AsyncContextManager
  8341. """
  8342. return mapping.from_impl(
  8343. await self._impl_obj.add_init_script(script=script, path=path)
  8344. )
  8345. async def route(
  8346. self,
  8347. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  8348. handler: typing.Union[
  8349. typing.Callable[["Route"], typing.Any],
  8350. typing.Callable[["Route", "Request"], typing.Any],
  8351. ],
  8352. *,
  8353. times: typing.Optional[int] = None,
  8354. ) -> "AsyncContextManager":
  8355. """Page.route
  8356. Routing provides the capability to modify network requests that are made by a page.
  8357. Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or
  8358. aborted.
  8359. **NOTE** The handler will only be called for the first url if the response is a redirect.
  8360. **NOTE** `page.route()` will not intercept requests intercepted by Service Worker. See
  8361. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  8362. using request interception by setting `serviceWorkers` to `'block'`.
  8363. **NOTE** `page.route()` will not intercept the first request of a popup page. Use
  8364. `browser_context.route()` instead.
  8365. **Usage**
  8366. An example of a naive handler that aborts all image requests:
  8367. ```py
  8368. page = await browser.new_page()
  8369. await page.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
  8370. await page.goto(\"https://example.com\")
  8371. await browser.close()
  8372. ```
  8373. or the same snippet using a regex pattern instead:
  8374. ```py
  8375. page = await browser.new_page()
  8376. await page.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
  8377. await page.goto(\"https://example.com\")
  8378. await browser.close()
  8379. ```
  8380. It is possible to examine the request to decide the route action. For example, mocking all requests that contain
  8381. some post data, and leaving all other requests as is:
  8382. ```py
  8383. async def handle_route(route: Route):
  8384. if (\"my-string\" in route.request.post_data):
  8385. await route.fulfill(body=\"mocked-data\")
  8386. else:
  8387. await route.continue_()
  8388. await page.route(\"/api/**\", handle_route)
  8389. ```
  8390. If a request matches multiple registered routes, the most recently registered route takes precedence.
  8391. Page routes take precedence over browser context routes (set up with `browser_context.route()`) when request
  8392. matches both handlers.
  8393. To remove a route with its handler you can use `page.unroute()`.
  8394. **NOTE** Enabling routing disables http cache.
  8395. Parameters
  8396. ----------
  8397. url : Union[Callable[[str], bool], Pattern[str], str]
  8398. A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
  8399. the context options and the provided URL is a string that does not start with `*`, it is resolved using the
  8400. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  8401. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
  8402. handler function to route the request.
  8403. times : Union[int, None]
  8404. How often a route should be used. By default it will be used every time.
  8405. Returns
  8406. -------
  8407. AsyncContextManager
  8408. """
  8409. return mapping.from_impl(
  8410. await self._impl_obj.route(
  8411. url=self._wrap_handler(url),
  8412. handler=self._wrap_handler(handler),
  8413. times=times,
  8414. )
  8415. )
  8416. async def unroute(
  8417. self,
  8418. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  8419. handler: typing.Optional[
  8420. typing.Union[
  8421. typing.Callable[["Route"], typing.Any],
  8422. typing.Callable[["Route", "Request"], typing.Any],
  8423. ]
  8424. ] = None,
  8425. ) -> None:
  8426. """Page.unroute
  8427. Removes a route created with `page.route()`. When `handler` is not specified, removes all routes for the
  8428. `url`.
  8429. Parameters
  8430. ----------
  8431. url : Union[Callable[[str], bool], Pattern[str], str]
  8432. A glob pattern, regex pattern, or predicate receiving [URL] to match while routing.
  8433. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
  8434. Optional handler function to route the request.
  8435. """
  8436. return mapping.from_maybe_impl(
  8437. await self._impl_obj.unroute(
  8438. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  8439. )
  8440. )
  8441. async def route_web_socket(
  8442. self,
  8443. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  8444. handler: typing.Callable[["WebSocketRoute"], typing.Any],
  8445. ) -> None:
  8446. """Page.route_web_socket
  8447. This method allows to modify websocket connections that are made by the page.
  8448. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
  8449. method before navigating the page.
  8450. **Usage**
  8451. Below is an example of a simple mock that responds to a single message. See `WebSocketRoute` for more details and
  8452. examples.
  8453. ```py
  8454. def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  8455. if message == \"request\":
  8456. ws.send(\"response\")
  8457. def handler(ws: WebSocketRoute):
  8458. ws.on_message(lambda message: message_handler(ws, message))
  8459. await page.route_web_socket(\"/ws\", handler)
  8460. ```
  8461. Parameters
  8462. ----------
  8463. url : Union[Callable[[str], bool], Pattern[str], str]
  8464. Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
  8465. `baseURL` context option.
  8466. handler : Callable[[WebSocketRoute], Any]
  8467. Handler function to route the WebSocket.
  8468. """
  8469. return mapping.from_maybe_impl(
  8470. await self._impl_obj.route_web_socket(
  8471. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  8472. )
  8473. )
  8474. async def unroute_all(
  8475. self,
  8476. *,
  8477. behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
  8478. ) -> None:
  8479. """Page.unroute_all
  8480. Removes all routes created with `page.route()` and `page.route_from_har()`.
  8481. Parameters
  8482. ----------
  8483. behavior : Union["default", "ignoreErrors", "wait", None]
  8484. Specifies whether to wait for already running handlers and what to do if they throw errors:
  8485. - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
  8486. result in unhandled error
  8487. - `'wait'` - wait for current handler calls (if any) to finish
  8488. - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
  8489. after unrouting are silently caught
  8490. """
  8491. return mapping.from_maybe_impl(
  8492. await self._impl_obj.unroute_all(behavior=behavior)
  8493. )
  8494. async def route_from_har(
  8495. self,
  8496. har: typing.Union[pathlib.Path, str],
  8497. *,
  8498. url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8499. not_found: typing.Optional[Literal["abort", "fallback"]] = None,
  8500. update: typing.Optional[bool] = None,
  8501. update_content: typing.Optional[Literal["attach", "embed"]] = None,
  8502. update_mode: typing.Optional[Literal["full", "minimal"]] = None,
  8503. ) -> None:
  8504. """Page.route_from_har
  8505. If specified the network requests that are made in the page will be served from the HAR file. Read more about
  8506. [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
  8507. Playwright will not serve requests intercepted by Service Worker from the HAR file. See
  8508. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  8509. using request interception by setting `serviceWorkers` to `'block'`.
  8510. Parameters
  8511. ----------
  8512. har : Union[pathlib.Path, str]
  8513. Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
  8514. relative path, then it is resolved relative to the current working directory.
  8515. url : Union[Pattern[str], str, None]
  8516. A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
  8517. pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
  8518. not_found : Union["abort", "fallback", None]
  8519. - If set to 'abort' any request not found in the HAR file will be aborted.
  8520. - If set to 'fallback' missing requests will be sent to the network.
  8521. Defaults to abort.
  8522. update : Union[bool, None]
  8523. If specified, updates the given HAR with the actual network information instead of serving from file. The file is
  8524. written to disk when `browser_context.close()` is called.
  8525. update_content : Union["attach", "embed", None]
  8526. Optional setting to control resource content management. If `attach` is specified, resources are persisted as
  8527. separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
  8528. update_mode : Union["full", "minimal", None]
  8529. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  8530. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
  8531. `minimal`.
  8532. """
  8533. return mapping.from_maybe_impl(
  8534. await self._impl_obj.route_from_har(
  8535. har=har,
  8536. url=url,
  8537. notFound=not_found,
  8538. update=update,
  8539. updateContent=update_content,
  8540. updateMode=update_mode,
  8541. )
  8542. )
  8543. async def screenshot(
  8544. self,
  8545. *,
  8546. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8547. type: typing.Optional[Literal["jpeg", "png"]] = None,
  8548. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  8549. quality: typing.Optional[int] = None,
  8550. omit_background: typing.Optional[bool] = None,
  8551. full_page: typing.Optional[bool] = None,
  8552. clip: typing.Optional[FloatRect] = None,
  8553. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  8554. caret: typing.Optional[Literal["hide", "initial"]] = None,
  8555. scale: typing.Optional[Literal["css", "device"]] = None,
  8556. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  8557. mask_color: typing.Optional[str] = None,
  8558. style: typing.Optional[str] = None,
  8559. ) -> bytes:
  8560. """Page.screenshot
  8561. Returns the buffer with the captured screenshot.
  8562. Parameters
  8563. ----------
  8564. timeout : Union[float, None]
  8565. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8566. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8567. type : Union["jpeg", "png", None]
  8568. Specify screenshot type, defaults to `png`.
  8569. path : Union[pathlib.Path, str, None]
  8570. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  8571. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  8572. won't be saved to the disk.
  8573. quality : Union[int, None]
  8574. The quality of the image, between 0-100. Not applicable to `png` images.
  8575. omit_background : Union[bool, None]
  8576. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  8577. Defaults to `false`.
  8578. full_page : Union[bool, None]
  8579. When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to
  8580. `false`.
  8581. clip : Union[{x: float, y: float, width: float, height: float}, None]
  8582. An object which specifies clipping of the resulting image.
  8583. animations : Union["allow", "disabled", None]
  8584. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  8585. treatment depending on their duration:
  8586. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  8587. - infinite animations are canceled to initial state, and then played over after the screenshot.
  8588. Defaults to `"allow"` that leaves animations untouched.
  8589. caret : Union["hide", "initial", None]
  8590. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  8591. changed. Defaults to `"hide"`.
  8592. scale : Union["css", "device", None]
  8593. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  8594. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  8595. screenshots of high-dpi devices will be twice as large or even larger.
  8596. Defaults to `"device"`.
  8597. mask : Union[Sequence[Locator], None]
  8598. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  8599. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  8600. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  8601. that.
  8602. mask_color : Union[str, None]
  8603. Specify the color of the overlay box for masked elements, in
  8604. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  8605. style : Union[str, None]
  8606. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  8607. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  8608. the Shadow DOM and applies to the inner frames.
  8609. Returns
  8610. -------
  8611. bytes
  8612. """
  8613. return mapping.from_maybe_impl(
  8614. await self._impl_obj.screenshot(
  8615. timeout=to_milliseconds(timeout),
  8616. type=type,
  8617. path=path,
  8618. quality=quality,
  8619. omitBackground=omit_background,
  8620. fullPage=full_page,
  8621. clip=clip,
  8622. animations=animations,
  8623. caret=caret,
  8624. scale=scale,
  8625. mask=mapping.to_impl(mask),
  8626. maskColor=mask_color,
  8627. style=style,
  8628. )
  8629. )
  8630. async def title(self) -> str:
  8631. """Page.title
  8632. Returns the page's title.
  8633. Returns
  8634. -------
  8635. str
  8636. """
  8637. return mapping.from_maybe_impl(await self._impl_obj.title())
  8638. async def aria_snapshot(
  8639. self,
  8640. *,
  8641. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8642. depth: typing.Optional[int] = None,
  8643. mode: typing.Optional[Literal["ai", "default"]] = None,
  8644. boxes: typing.Optional[bool] = None,
  8645. ) -> str:
  8646. """Page.aria_snapshot
  8647. Captures the aria snapshot of the page. Read more about [aria snapshots](https://playwright.dev/python/docs/aria-snapshots).
  8648. Parameters
  8649. ----------
  8650. timeout : Union[float, None]
  8651. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8652. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8653. depth : Union[int, None]
  8654. When specified, limits the depth of the snapshot.
  8655. mode : Union["ai", "default", None]
  8656. When set to `"ai"`, returns a snapshot optimized for AI consumption: including element references like `[ref=e2]`
  8657. and snapshots of `<iframe>`s. Defaults to `"default"`.
  8658. boxes : Union[bool, None]
  8659. When `true`, appends each element's bounding box as `[box=x,y,width,height]` to the snapshot. Coordinates are
  8660. relative to the viewport, in CSS pixels, as returned by
  8661. [`Element.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  8662. Defaults to `false`.
  8663. Returns
  8664. -------
  8665. str
  8666. """
  8667. return mapping.from_maybe_impl(
  8668. await self._impl_obj.aria_snapshot(
  8669. timeout=to_milliseconds(timeout), depth=depth, mode=mode, boxes=boxes
  8670. )
  8671. )
  8672. async def close(
  8673. self,
  8674. *,
  8675. run_before_unload: typing.Optional[bool] = None,
  8676. reason: typing.Optional[str] = None,
  8677. ) -> None:
  8678. """Page.close
  8679. If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If
  8680. `runBeforeUnload` is `true` the method will run unload handlers, but will **not** wait for the page to close.
  8681. By default, `page.close()` **does not** run `beforeunload` handlers.
  8682. **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned and should be handled
  8683. manually via `page.on('dialog')` event.
  8684. Parameters
  8685. ----------
  8686. run_before_unload : Union[bool, None]
  8687. Defaults to `false`. Whether to run the
  8688. [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) page handlers.
  8689. reason : Union[str, None]
  8690. The reason to be reported to the operations interrupted by the page closure.
  8691. """
  8692. return mapping.from_maybe_impl(
  8693. await self._impl_obj.close(runBeforeUnload=run_before_unload, reason=reason)
  8694. )
  8695. def is_closed(self) -> bool:
  8696. """Page.is_closed
  8697. Indicates that the page has been closed.
  8698. Returns
  8699. -------
  8700. bool
  8701. """
  8702. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  8703. async def click(
  8704. self,
  8705. selector: str,
  8706. *,
  8707. modifiers: typing.Optional[
  8708. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8709. ] = None,
  8710. position: typing.Optional[Position] = None,
  8711. delay: typing.Optional[float] = None,
  8712. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  8713. click_count: typing.Optional[int] = None,
  8714. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8715. force: typing.Optional[bool] = None,
  8716. no_wait_after: typing.Optional[bool] = None,
  8717. trial: typing.Optional[bool] = None,
  8718. strict: typing.Optional[bool] = None,
  8719. ) -> None:
  8720. """Page.click
  8721. This method clicks an element matching `selector` by performing the following steps:
  8722. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8723. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8724. the element is detached during the checks, the whole action is retried.
  8725. 1. Scroll the element into view if needed.
  8726. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  8727. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  8728. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8729. Passing zero timeout disables this.
  8730. Parameters
  8731. ----------
  8732. selector : str
  8733. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8734. used.
  8735. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8736. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8737. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8738. "Control" on Windows and Linux and to "Meta" on macOS.
  8739. position : Union[{x: float, y: float}, None]
  8740. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8741. the element.
  8742. delay : Union[float, None]
  8743. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  8744. button : Union["left", "middle", "right", None]
  8745. Defaults to `left`.
  8746. click_count : Union[int, None]
  8747. defaults to 1. See [UIEvent.detail].
  8748. timeout : Union[float, None]
  8749. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8750. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8751. force : Union[bool, None]
  8752. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8753. no_wait_after : Union[bool, None]
  8754. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  8755. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  8756. navigating to inaccessible pages. Defaults to `false`.
  8757. Deprecated: This option will default to `true` in the future.
  8758. trial : Union[bool, None]
  8759. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8760. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8761. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8762. are pressed.
  8763. strict : Union[bool, None]
  8764. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8765. element, the call throws an exception.
  8766. """
  8767. return mapping.from_maybe_impl(
  8768. await self._impl_obj.click(
  8769. selector=selector,
  8770. modifiers=mapping.to_impl(modifiers),
  8771. position=position,
  8772. delay=delay,
  8773. button=button,
  8774. clickCount=click_count,
  8775. timeout=to_milliseconds(timeout),
  8776. force=force,
  8777. noWaitAfter=no_wait_after,
  8778. trial=trial,
  8779. strict=strict,
  8780. )
  8781. )
  8782. async def dblclick(
  8783. self,
  8784. selector: str,
  8785. *,
  8786. modifiers: typing.Optional[
  8787. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8788. ] = None,
  8789. position: typing.Optional[Position] = None,
  8790. delay: typing.Optional[float] = None,
  8791. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  8792. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8793. force: typing.Optional[bool] = None,
  8794. no_wait_after: typing.Optional[bool] = None,
  8795. strict: typing.Optional[bool] = None,
  8796. trial: typing.Optional[bool] = None,
  8797. ) -> None:
  8798. """Page.dblclick
  8799. This method double clicks an element matching `selector` by performing the following steps:
  8800. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8801. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8802. the element is detached during the checks, the whole action is retried.
  8803. 1. Scroll the element into view if needed.
  8804. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  8805. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8806. Passing zero timeout disables this.
  8807. **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
  8808. Parameters
  8809. ----------
  8810. selector : str
  8811. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8812. used.
  8813. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8814. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8815. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8816. "Control" on Windows and Linux and to "Meta" on macOS.
  8817. position : Union[{x: float, y: float}, None]
  8818. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8819. the element.
  8820. delay : Union[float, None]
  8821. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  8822. button : Union["left", "middle", "right", None]
  8823. Defaults to `left`.
  8824. timeout : Union[float, None]
  8825. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8826. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8827. force : Union[bool, None]
  8828. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8829. no_wait_after : Union[bool, None]
  8830. This option has no effect.
  8831. Deprecated: This option has no effect.
  8832. strict : Union[bool, None]
  8833. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8834. element, the call throws an exception.
  8835. trial : Union[bool, None]
  8836. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8837. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8838. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8839. are pressed.
  8840. """
  8841. return mapping.from_maybe_impl(
  8842. await self._impl_obj.dblclick(
  8843. selector=selector,
  8844. modifiers=mapping.to_impl(modifiers),
  8845. position=position,
  8846. delay=delay,
  8847. button=button,
  8848. timeout=to_milliseconds(timeout),
  8849. force=force,
  8850. noWaitAfter=no_wait_after,
  8851. strict=strict,
  8852. trial=trial,
  8853. )
  8854. )
  8855. async def tap(
  8856. self,
  8857. selector: str,
  8858. *,
  8859. modifiers: typing.Optional[
  8860. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8861. ] = None,
  8862. position: typing.Optional[Position] = None,
  8863. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8864. force: typing.Optional[bool] = None,
  8865. no_wait_after: typing.Optional[bool] = None,
  8866. strict: typing.Optional[bool] = None,
  8867. trial: typing.Optional[bool] = None,
  8868. ) -> None:
  8869. """Page.tap
  8870. This method taps an element matching `selector` by performing the following steps:
  8871. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8872. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8873. the element is detached during the checks, the whole action is retried.
  8874. 1. Scroll the element into view if needed.
  8875. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  8876. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8877. Passing zero timeout disables this.
  8878. **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
  8879. Parameters
  8880. ----------
  8881. selector : str
  8882. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8883. used.
  8884. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8885. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8886. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8887. "Control" on Windows and Linux and to "Meta" on macOS.
  8888. position : Union[{x: float, y: float}, None]
  8889. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8890. the element.
  8891. timeout : Union[float, None]
  8892. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8893. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8894. force : Union[bool, None]
  8895. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8896. no_wait_after : Union[bool, None]
  8897. This option has no effect.
  8898. Deprecated: This option has no effect.
  8899. strict : Union[bool, None]
  8900. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8901. element, the call throws an exception.
  8902. trial : Union[bool, None]
  8903. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8904. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8905. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8906. are pressed.
  8907. """
  8908. return mapping.from_maybe_impl(
  8909. await self._impl_obj.tap(
  8910. selector=selector,
  8911. modifiers=mapping.to_impl(modifiers),
  8912. position=position,
  8913. timeout=to_milliseconds(timeout),
  8914. force=force,
  8915. noWaitAfter=no_wait_after,
  8916. strict=strict,
  8917. trial=trial,
  8918. )
  8919. )
  8920. async def fill(
  8921. self,
  8922. selector: str,
  8923. value: str,
  8924. *,
  8925. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  8926. no_wait_after: typing.Optional[bool] = None,
  8927. strict: typing.Optional[bool] = None,
  8928. force: typing.Optional[bool] = None,
  8929. ) -> None:
  8930. """Page.fill
  8931. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
  8932. focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
  8933. to clear the input field.
  8934. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  8935. error. However, if the element is inside the `<label>` element that has an associated
  8936. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  8937. instead.
  8938. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  8939. Parameters
  8940. ----------
  8941. selector : str
  8942. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8943. used.
  8944. value : str
  8945. Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
  8946. timeout : Union[float, None]
  8947. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8948. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8949. no_wait_after : Union[bool, None]
  8950. This option has no effect.
  8951. Deprecated: This option has no effect.
  8952. strict : Union[bool, None]
  8953. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8954. element, the call throws an exception.
  8955. force : Union[bool, None]
  8956. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8957. """
  8958. return mapping.from_maybe_impl(
  8959. await self._impl_obj.fill(
  8960. selector=selector,
  8961. value=value,
  8962. timeout=to_milliseconds(timeout),
  8963. noWaitAfter=no_wait_after,
  8964. strict=strict,
  8965. force=force,
  8966. )
  8967. )
  8968. def locator(
  8969. self,
  8970. selector: str,
  8971. *,
  8972. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8973. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8974. has: typing.Optional["Locator"] = None,
  8975. has_not: typing.Optional["Locator"] = None,
  8976. ) -> "Locator":
  8977. """Page.locator
  8978. The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
  8979. to the element immediately before performing an action, so a series of actions on the same locator can in fact be
  8980. performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
  8981. [Learn more about locators](https://playwright.dev/python/docs/locators).
  8982. Parameters
  8983. ----------
  8984. selector : str
  8985. A selector to use when resolving DOM element.
  8986. has_text : Union[Pattern[str], str, None]
  8987. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  8988. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  8989. `<article><div>Playwright</div></article>`.
  8990. has_not_text : Union[Pattern[str], str, None]
  8991. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  8992. When passed a [string], matching is case-insensitive and searches for a substring.
  8993. has : Union[Locator, None]
  8994. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  8995. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  8996. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  8997. the document root. For example, you can find `content` that has `div` in
  8998. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  8999. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  9000. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  9001. has_not : Union[Locator, None]
  9002. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  9003. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  9004. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  9005. Returns
  9006. -------
  9007. Locator
  9008. """
  9009. return mapping.from_impl(
  9010. self._impl_obj.locator(
  9011. selector=selector,
  9012. hasText=has_text,
  9013. hasNotText=has_not_text,
  9014. has=has._impl_obj if has else None,
  9015. hasNot=has_not._impl_obj if has_not else None,
  9016. )
  9017. )
  9018. def get_by_alt_text(
  9019. self,
  9020. text: typing.Union[str, typing.Pattern[str]],
  9021. *,
  9022. exact: typing.Optional[bool] = None,
  9023. ) -> "Locator":
  9024. """Page.get_by_alt_text
  9025. Allows locating elements by their alt text.
  9026. **Usage**
  9027. For example, this method will find the image by alt text \"Playwright logo\":
  9028. ```html
  9029. <img alt='Playwright logo'>
  9030. ```
  9031. ```py
  9032. await page.get_by_alt_text(\"Playwright logo\").click()
  9033. ```
  9034. Parameters
  9035. ----------
  9036. text : Union[Pattern[str], str]
  9037. Text to locate the element for.
  9038. exact : Union[bool, None]
  9039. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  9040. regular expression. Note that exact match still trims whitespace.
  9041. Returns
  9042. -------
  9043. Locator
  9044. """
  9045. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  9046. def get_by_label(
  9047. self,
  9048. text: typing.Union[str, typing.Pattern[str]],
  9049. *,
  9050. exact: typing.Optional[bool] = None,
  9051. ) -> "Locator":
  9052. """Page.get_by_label
  9053. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  9054. `aria-label` attribute.
  9055. **Usage**
  9056. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  9057. ```html
  9058. <input aria-label=\"Username\">
  9059. <label for=\"password-input\">Password:</label>
  9060. <input id=\"password-input\">
  9061. ```
  9062. ```py
  9063. await page.get_by_label(\"Username\").fill(\"john\")
  9064. await page.get_by_label(\"Password\").fill(\"secret\")
  9065. ```
  9066. Parameters
  9067. ----------
  9068. text : Union[Pattern[str], str]
  9069. Text to locate the element for.
  9070. exact : Union[bool, None]
  9071. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  9072. regular expression. Note that exact match still trims whitespace.
  9073. Returns
  9074. -------
  9075. Locator
  9076. """
  9077. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  9078. def get_by_placeholder(
  9079. self,
  9080. text: typing.Union[str, typing.Pattern[str]],
  9081. *,
  9082. exact: typing.Optional[bool] = None,
  9083. ) -> "Locator":
  9084. """Page.get_by_placeholder
  9085. Allows locating input elements by the placeholder text.
  9086. **Usage**
  9087. For example, consider the following DOM structure.
  9088. ```html
  9089. <input type=\"email\" placeholder=\"name@example.com\" />
  9090. ```
  9091. You can fill the input after locating it by the placeholder text:
  9092. ```py
  9093. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  9094. ```
  9095. Parameters
  9096. ----------
  9097. text : Union[Pattern[str], str]
  9098. Text to locate the element for.
  9099. exact : Union[bool, None]
  9100. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  9101. regular expression. Note that exact match still trims whitespace.
  9102. Returns
  9103. -------
  9104. Locator
  9105. """
  9106. return mapping.from_impl(
  9107. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  9108. )
  9109. def get_by_role(
  9110. self,
  9111. role: Literal[
  9112. "alert",
  9113. "alertdialog",
  9114. "application",
  9115. "article",
  9116. "banner",
  9117. "blockquote",
  9118. "button",
  9119. "caption",
  9120. "cell",
  9121. "checkbox",
  9122. "code",
  9123. "columnheader",
  9124. "combobox",
  9125. "complementary",
  9126. "contentinfo",
  9127. "definition",
  9128. "deletion",
  9129. "dialog",
  9130. "directory",
  9131. "document",
  9132. "emphasis",
  9133. "feed",
  9134. "figure",
  9135. "form",
  9136. "generic",
  9137. "grid",
  9138. "gridcell",
  9139. "group",
  9140. "heading",
  9141. "img",
  9142. "insertion",
  9143. "link",
  9144. "list",
  9145. "listbox",
  9146. "listitem",
  9147. "log",
  9148. "main",
  9149. "marquee",
  9150. "math",
  9151. "menu",
  9152. "menubar",
  9153. "menuitem",
  9154. "menuitemcheckbox",
  9155. "menuitemradio",
  9156. "meter",
  9157. "navigation",
  9158. "none",
  9159. "note",
  9160. "option",
  9161. "paragraph",
  9162. "presentation",
  9163. "progressbar",
  9164. "radio",
  9165. "radiogroup",
  9166. "region",
  9167. "row",
  9168. "rowgroup",
  9169. "rowheader",
  9170. "scrollbar",
  9171. "search",
  9172. "searchbox",
  9173. "separator",
  9174. "slider",
  9175. "spinbutton",
  9176. "status",
  9177. "strong",
  9178. "subscript",
  9179. "superscript",
  9180. "switch",
  9181. "tab",
  9182. "table",
  9183. "tablist",
  9184. "tabpanel",
  9185. "term",
  9186. "textbox",
  9187. "time",
  9188. "timer",
  9189. "toolbar",
  9190. "tooltip",
  9191. "tree",
  9192. "treegrid",
  9193. "treeitem",
  9194. ],
  9195. *,
  9196. checked: typing.Optional[bool] = None,
  9197. disabled: typing.Optional[bool] = None,
  9198. expanded: typing.Optional[bool] = None,
  9199. include_hidden: typing.Optional[bool] = None,
  9200. level: typing.Optional[int] = None,
  9201. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  9202. pressed: typing.Optional[bool] = None,
  9203. selected: typing.Optional[bool] = None,
  9204. exact: typing.Optional[bool] = None,
  9205. description: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  9206. ) -> "Locator":
  9207. """Page.get_by_role
  9208. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  9209. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  9210. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  9211. **Usage**
  9212. Consider the following DOM structure.
  9213. ```html
  9214. <h3>Sign up</h3>
  9215. <label>
  9216. <input type=\"checkbox\" /> Subscribe
  9217. </label>
  9218. <br/>
  9219. <button>Submit</button>
  9220. ```
  9221. You can locate each element by its implicit role:
  9222. ```py
  9223. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  9224. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  9225. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  9226. ```
  9227. **Details**
  9228. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  9229. about the ARIA guidelines.
  9230. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  9231. that is recognized by the role selector. You can find all the
  9232. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  9233. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  9234. Parameters
  9235. ----------
  9236. 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"]
  9237. Required aria role.
  9238. checked : Union[bool, None]
  9239. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  9240. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  9241. disabled : Union[bool, None]
  9242. An attribute that is usually set by `aria-disabled` or `disabled`.
  9243. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  9244. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  9245. expanded : Union[bool, None]
  9246. An attribute that is usually set by `aria-expanded`.
  9247. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  9248. include_hidden : Union[bool, None]
  9249. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  9250. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  9251. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  9252. level : Union[int, None]
  9253. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  9254. for `<h1>-<h6>` elements.
  9255. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  9256. name : Union[Pattern[str], str, None]
  9257. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  9258. case-insensitive and searches for a substring, use `exact` to control this behavior.
  9259. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  9260. pressed : Union[bool, None]
  9261. An attribute that is usually set by `aria-pressed`.
  9262. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  9263. selected : Union[bool, None]
  9264. An attribute that is usually set by `aria-selected`.
  9265. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  9266. exact : Union[bool, None]
  9267. Whether `name` and `description` are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored
  9268. when the value is a regular expression. Note that exact match still trims whitespace.
  9269. description : Union[Pattern[str], str, None]
  9270. Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By
  9271. default, matching is case-insensitive and searches for a substring, use `exact` to control this behavior.
  9272. Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  9273. Returns
  9274. -------
  9275. Locator
  9276. """
  9277. return mapping.from_impl(
  9278. self._impl_obj.get_by_role(
  9279. role=role,
  9280. checked=checked,
  9281. disabled=disabled,
  9282. expanded=expanded,
  9283. includeHidden=include_hidden,
  9284. level=level,
  9285. name=name,
  9286. pressed=pressed,
  9287. selected=selected,
  9288. exact=exact,
  9289. description=description,
  9290. )
  9291. )
  9292. def get_by_test_id(
  9293. self, test_id: typing.Union[str, typing.Pattern[str]]
  9294. ) -> "Locator":
  9295. """Page.get_by_test_id
  9296. Locate element by the test id.
  9297. **Usage**
  9298. Consider the following DOM structure.
  9299. ```html
  9300. <button data-testid=\"directions\">Itinéraire</button>
  9301. ```
  9302. You can locate the element by its test id:
  9303. ```py
  9304. await page.get_by_test_id(\"directions\").click()
  9305. ```
  9306. **Details**
  9307. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  9308. configure a different test id attribute if necessary.
  9309. Parameters
  9310. ----------
  9311. test_id : Union[Pattern[str], str]
  9312. Id to locate the element by.
  9313. Returns
  9314. -------
  9315. Locator
  9316. """
  9317. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  9318. def get_by_text(
  9319. self,
  9320. text: typing.Union[str, typing.Pattern[str]],
  9321. *,
  9322. exact: typing.Optional[bool] = None,
  9323. ) -> "Locator":
  9324. """Page.get_by_text
  9325. Allows locating elements that contain given text.
  9326. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  9327. filter by the text content.
  9328. **Usage**
  9329. Consider the following DOM structure:
  9330. ```html
  9331. <div>Hello <span>world</span></div>
  9332. <div>Hello</div>
  9333. ```
  9334. You can locate by text substring, exact string, or a regular expression:
  9335. ```py
  9336. # Matches <span>
  9337. page.get_by_text(\"world\")
  9338. # Matches first <div>
  9339. page.get_by_text(\"Hello world\")
  9340. # Matches second <div>
  9341. page.get_by_text(\"Hello\", exact=True)
  9342. # Matches both <div>s
  9343. page.get_by_text(re.compile(\"Hello\"))
  9344. # Matches second <div>
  9345. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  9346. ```
  9347. **Details**
  9348. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  9349. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  9350. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  9351. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  9352. Parameters
  9353. ----------
  9354. text : Union[Pattern[str], str]
  9355. Text to locate the element for.
  9356. exact : Union[bool, None]
  9357. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  9358. regular expression. Note that exact match still trims whitespace.
  9359. Returns
  9360. -------
  9361. Locator
  9362. """
  9363. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  9364. def get_by_title(
  9365. self,
  9366. text: typing.Union[str, typing.Pattern[str]],
  9367. *,
  9368. exact: typing.Optional[bool] = None,
  9369. ) -> "Locator":
  9370. """Page.get_by_title
  9371. Allows locating elements by their title attribute.
  9372. **Usage**
  9373. Consider the following DOM structure.
  9374. ```html
  9375. <span title='Issues count'>25 issues</span>
  9376. ```
  9377. You can check the issues count after locating it by the title text:
  9378. ```py
  9379. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  9380. ```
  9381. Parameters
  9382. ----------
  9383. text : Union[Pattern[str], str]
  9384. Text to locate the element for.
  9385. exact : Union[bool, None]
  9386. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  9387. regular expression. Note that exact match still trims whitespace.
  9388. Returns
  9389. -------
  9390. Locator
  9391. """
  9392. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  9393. def frame_locator(self, selector: str) -> "FrameLocator":
  9394. """Page.frame_locator
  9395. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  9396. in that iframe.
  9397. **Usage**
  9398. Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
  9399. id=\"my-frame\">`:
  9400. ```py
  9401. locator = page.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
  9402. await locator.click()
  9403. ```
  9404. Parameters
  9405. ----------
  9406. selector : str
  9407. A selector to use when resolving DOM element.
  9408. Returns
  9409. -------
  9410. FrameLocator
  9411. """
  9412. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  9413. async def focus(
  9414. self,
  9415. selector: str,
  9416. *,
  9417. strict: typing.Optional[bool] = None,
  9418. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9419. ) -> None:
  9420. """Page.focus
  9421. This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
  9422. method waits until a matching element appears in the DOM.
  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. strict : Union[bool, None]
  9429. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9430. element, the call throws an exception.
  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. """
  9435. return mapping.from_maybe_impl(
  9436. await self._impl_obj.focus(
  9437. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  9438. )
  9439. )
  9440. async def text_content(
  9441. self,
  9442. selector: str,
  9443. *,
  9444. strict: typing.Optional[bool] = None,
  9445. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9446. ) -> typing.Optional[str]:
  9447. """Page.text_content
  9448. Returns `element.textContent`.
  9449. Parameters
  9450. ----------
  9451. selector : str
  9452. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9453. used.
  9454. strict : Union[bool, None]
  9455. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9456. element, the call throws an exception.
  9457. timeout : Union[float, None]
  9458. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9459. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9460. Returns
  9461. -------
  9462. Union[str, None]
  9463. """
  9464. return mapping.from_maybe_impl(
  9465. await self._impl_obj.text_content(
  9466. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  9467. )
  9468. )
  9469. async def inner_text(
  9470. self,
  9471. selector: str,
  9472. *,
  9473. strict: typing.Optional[bool] = None,
  9474. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9475. ) -> str:
  9476. """Page.inner_text
  9477. Returns `element.innerText`.
  9478. Parameters
  9479. ----------
  9480. selector : str
  9481. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9482. used.
  9483. strict : Union[bool, None]
  9484. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9485. element, the call throws an exception.
  9486. timeout : Union[float, None]
  9487. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9488. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9489. Returns
  9490. -------
  9491. str
  9492. """
  9493. return mapping.from_maybe_impl(
  9494. await self._impl_obj.inner_text(
  9495. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  9496. )
  9497. )
  9498. async def inner_html(
  9499. self,
  9500. selector: str,
  9501. *,
  9502. strict: typing.Optional[bool] = None,
  9503. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9504. ) -> str:
  9505. """Page.inner_html
  9506. Returns `element.innerHTML`.
  9507. Parameters
  9508. ----------
  9509. selector : str
  9510. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9511. used.
  9512. strict : Union[bool, None]
  9513. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9514. element, the call throws an exception.
  9515. timeout : Union[float, None]
  9516. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9517. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9518. Returns
  9519. -------
  9520. str
  9521. """
  9522. return mapping.from_maybe_impl(
  9523. await self._impl_obj.inner_html(
  9524. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  9525. )
  9526. )
  9527. async def get_attribute(
  9528. self,
  9529. selector: str,
  9530. name: str,
  9531. *,
  9532. strict: typing.Optional[bool] = None,
  9533. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9534. ) -> typing.Optional[str]:
  9535. """Page.get_attribute
  9536. Returns element attribute value.
  9537. Parameters
  9538. ----------
  9539. selector : str
  9540. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9541. used.
  9542. name : str
  9543. Attribute name to get the value for.
  9544. strict : Union[bool, None]
  9545. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9546. element, the call throws an exception.
  9547. timeout : Union[float, None]
  9548. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9549. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9550. Returns
  9551. -------
  9552. Union[str, None]
  9553. """
  9554. return mapping.from_maybe_impl(
  9555. await self._impl_obj.get_attribute(
  9556. selector=selector,
  9557. name=name,
  9558. strict=strict,
  9559. timeout=to_milliseconds(timeout),
  9560. )
  9561. )
  9562. async def hover(
  9563. self,
  9564. selector: str,
  9565. *,
  9566. modifiers: typing.Optional[
  9567. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  9568. ] = None,
  9569. position: typing.Optional[Position] = None,
  9570. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9571. no_wait_after: typing.Optional[bool] = None,
  9572. force: typing.Optional[bool] = None,
  9573. strict: typing.Optional[bool] = None,
  9574. trial: typing.Optional[bool] = None,
  9575. ) -> None:
  9576. """Page.hover
  9577. This method hovers over an element matching `selector` by performing the following steps:
  9578. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9579. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9580. the element is detached during the checks, the whole action is retried.
  9581. 1. Scroll the element into view if needed.
  9582. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  9583. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9584. Passing zero timeout disables this.
  9585. Parameters
  9586. ----------
  9587. selector : str
  9588. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9589. used.
  9590. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  9591. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  9592. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  9593. "Control" on Windows and Linux and to "Meta" on macOS.
  9594. position : Union[{x: float, y: float}, None]
  9595. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9596. the element.
  9597. timeout : Union[float, None]
  9598. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9599. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9600. no_wait_after : Union[bool, None]
  9601. This option has no effect.
  9602. Deprecated: This option has no effect.
  9603. force : Union[bool, None]
  9604. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9605. strict : Union[bool, None]
  9606. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9607. element, the call throws an exception.
  9608. trial : Union[bool, None]
  9609. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9610. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  9611. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  9612. are pressed.
  9613. """
  9614. return mapping.from_maybe_impl(
  9615. await self._impl_obj.hover(
  9616. selector=selector,
  9617. modifiers=mapping.to_impl(modifiers),
  9618. position=position,
  9619. timeout=to_milliseconds(timeout),
  9620. noWaitAfter=no_wait_after,
  9621. force=force,
  9622. strict=strict,
  9623. trial=trial,
  9624. )
  9625. )
  9626. async def drag_and_drop(
  9627. self,
  9628. source: str,
  9629. target: str,
  9630. *,
  9631. source_position: typing.Optional[Position] = None,
  9632. target_position: typing.Optional[Position] = None,
  9633. force: typing.Optional[bool] = None,
  9634. no_wait_after: typing.Optional[bool] = None,
  9635. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9636. strict: typing.Optional[bool] = None,
  9637. trial: typing.Optional[bool] = None,
  9638. steps: typing.Optional[int] = None,
  9639. ) -> None:
  9640. """Page.drag_and_drop
  9641. This method drags the source element to the target element. It will first move to the source element, perform a
  9642. `mousedown`, then move to the target element and perform a `mouseup`.
  9643. **Usage**
  9644. ```py
  9645. await page.drag_and_drop(\"#source\", \"#target\")
  9646. # or specify exact positions relative to the top-left corners of the elements:
  9647. await page.drag_and_drop(
  9648. \"#source\",
  9649. \"#target\",
  9650. source_position={\"x\": 34, \"y\": 7},
  9651. target_position={\"x\": 10, \"y\": 20}
  9652. )
  9653. ```
  9654. Parameters
  9655. ----------
  9656. source : str
  9657. A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
  9658. be used.
  9659. target : str
  9660. A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
  9661. will be used.
  9662. source_position : Union[{x: float, y: float}, None]
  9663. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  9664. specified, some visible point of the element is used.
  9665. target_position : Union[{x: float, y: float}, None]
  9666. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  9667. specified, some visible point of the element is used.
  9668. force : Union[bool, None]
  9669. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9670. no_wait_after : Union[bool, None]
  9671. This option has no effect.
  9672. Deprecated: This option has no effect.
  9673. timeout : Union[float, None]
  9674. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9675. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9676. strict : Union[bool, None]
  9677. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9678. element, the call throws an exception.
  9679. trial : Union[bool, None]
  9680. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9681. to `false`. Useful to wait until the element is ready for the action without performing it.
  9682. steps : Union[int, None]
  9683. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  9684. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  9685. """
  9686. return mapping.from_maybe_impl(
  9687. await self._impl_obj.drag_and_drop(
  9688. source=source,
  9689. target=target,
  9690. sourcePosition=source_position,
  9691. targetPosition=target_position,
  9692. force=force,
  9693. noWaitAfter=no_wait_after,
  9694. timeout=to_milliseconds(timeout),
  9695. strict=strict,
  9696. trial=trial,
  9697. steps=steps,
  9698. )
  9699. )
  9700. async def select_option(
  9701. self,
  9702. selector: str,
  9703. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  9704. *,
  9705. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  9706. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  9707. element: typing.Optional[
  9708. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  9709. ] = None,
  9710. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9711. no_wait_after: typing.Optional[bool] = None,
  9712. force: typing.Optional[bool] = None,
  9713. strict: typing.Optional[bool] = None,
  9714. ) -> typing.List[str]:
  9715. """Page.select_option
  9716. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
  9717. until all specified options are present in the `<select>` element and selects these options.
  9718. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  9719. the `<label>` element that has an associated
  9720. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  9721. instead.
  9722. Returns the array of option values that have been successfully selected.
  9723. Triggers a `change` and `input` event once all the provided options have been selected.
  9724. **Usage**
  9725. ```py
  9726. # Single selection matching the value or label
  9727. await page.select_option(\"select#colors\", \"blue\")
  9728. # single selection matching the label
  9729. await page.select_option(\"select#colors\", label=\"blue\")
  9730. # multiple selection
  9731. await page.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
  9732. ```
  9733. Parameters
  9734. ----------
  9735. selector : str
  9736. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9737. used.
  9738. value : Union[Sequence[str], str, None]
  9739. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  9740. otherwise only the first option matching one of the passed options is selected. Optional.
  9741. index : Union[Sequence[int], int, None]
  9742. Options to select by index. Optional.
  9743. label : Union[Sequence[str], str, None]
  9744. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  9745. otherwise only the first option matching one of the passed options is selected. Optional.
  9746. element : Union[ElementHandle, Sequence[ElementHandle], None]
  9747. Option elements to select. Optional.
  9748. timeout : Union[float, None]
  9749. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9750. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9751. no_wait_after : Union[bool, None]
  9752. This option has no effect.
  9753. Deprecated: This option has no effect.
  9754. force : Union[bool, None]
  9755. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9756. strict : Union[bool, None]
  9757. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9758. element, the call throws an exception.
  9759. Returns
  9760. -------
  9761. List[str]
  9762. """
  9763. return mapping.from_maybe_impl(
  9764. await self._impl_obj.select_option(
  9765. selector=selector,
  9766. value=mapping.to_impl(value),
  9767. index=mapping.to_impl(index),
  9768. label=mapping.to_impl(label),
  9769. element=mapping.to_impl(element),
  9770. timeout=to_milliseconds(timeout),
  9771. noWaitAfter=no_wait_after,
  9772. force=force,
  9773. strict=strict,
  9774. )
  9775. )
  9776. async def input_value(
  9777. self,
  9778. selector: str,
  9779. *,
  9780. strict: typing.Optional[bool] = None,
  9781. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9782. ) -> str:
  9783. """Page.input_value
  9784. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  9785. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  9786. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  9787. control.
  9788. Parameters
  9789. ----------
  9790. selector : str
  9791. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9792. used.
  9793. strict : Union[bool, None]
  9794. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9795. element, the call throws an exception.
  9796. timeout : Union[float, None]
  9797. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9798. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9799. Returns
  9800. -------
  9801. str
  9802. """
  9803. return mapping.from_maybe_impl(
  9804. await self._impl_obj.input_value(
  9805. selector=selector, strict=strict, timeout=to_milliseconds(timeout)
  9806. )
  9807. )
  9808. async def set_input_files(
  9809. self,
  9810. selector: str,
  9811. files: typing.Union[
  9812. str,
  9813. pathlib.Path,
  9814. FilePayload,
  9815. typing.Sequence[typing.Union[str, pathlib.Path]],
  9816. typing.Sequence[FilePayload],
  9817. ],
  9818. *,
  9819. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9820. strict: typing.Optional[bool] = None,
  9821. no_wait_after: typing.Optional[bool] = None,
  9822. ) -> None:
  9823. """Page.set_input_files
  9824. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  9825. they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
  9826. with a `[webkitdirectory]` attribute, only a single directory path is supported.
  9827. This method expects `selector` to point to an
  9828. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  9829. the `<label>` element that has an associated
  9830. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  9831. Parameters
  9832. ----------
  9833. selector : str
  9834. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9835. used.
  9836. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  9837. timeout : Union[float, None]
  9838. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9839. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9840. strict : Union[bool, None]
  9841. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9842. element, the call throws an exception.
  9843. no_wait_after : Union[bool, None]
  9844. This option has no effect.
  9845. Deprecated: This option has no effect.
  9846. """
  9847. return mapping.from_maybe_impl(
  9848. await self._impl_obj.set_input_files(
  9849. selector=selector,
  9850. files=mapping.to_impl(files),
  9851. timeout=to_milliseconds(timeout),
  9852. strict=strict,
  9853. noWaitAfter=no_wait_after,
  9854. )
  9855. )
  9856. async def type(
  9857. self,
  9858. selector: str,
  9859. text: str,
  9860. *,
  9861. delay: typing.Optional[float] = None,
  9862. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9863. no_wait_after: typing.Optional[bool] = None,
  9864. strict: typing.Optional[bool] = None,
  9865. ) -> None:
  9866. """Page.type
  9867. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to
  9868. send fine-grained keyboard events. To fill values in form fields, use `page.fill()`.
  9869. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  9870. **Usage**
  9871. Parameters
  9872. ----------
  9873. selector : str
  9874. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9875. used.
  9876. text : str
  9877. A text to type into a focused element.
  9878. delay : Union[float, None]
  9879. Time to wait between key presses in milliseconds. Defaults to 0.
  9880. timeout : Union[float, None]
  9881. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9882. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9883. no_wait_after : Union[bool, None]
  9884. This option has no effect.
  9885. Deprecated: This option has no effect.
  9886. strict : Union[bool, None]
  9887. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9888. element, the call throws an exception.
  9889. """
  9890. return mapping.from_maybe_impl(
  9891. await self._impl_obj.type(
  9892. selector=selector,
  9893. text=text,
  9894. delay=delay,
  9895. timeout=to_milliseconds(timeout),
  9896. noWaitAfter=no_wait_after,
  9897. strict=strict,
  9898. )
  9899. )
  9900. async def press(
  9901. self,
  9902. selector: str,
  9903. key: str,
  9904. *,
  9905. delay: typing.Optional[float] = None,
  9906. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9907. no_wait_after: typing.Optional[bool] = None,
  9908. strict: typing.Optional[bool] = None,
  9909. ) -> None:
  9910. """Page.press
  9911. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  9912. `key` can specify the intended
  9913. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  9914. to generate the text for. A superset of the `key` values can be found
  9915. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  9916. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  9917. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  9918. etc.
  9919. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  9920. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  9921. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  9922. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  9923. texts.
  9924. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  9925. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  9926. **Usage**
  9927. ```py
  9928. page = await browser.new_page()
  9929. await page.goto(\"https://keycode.info\")
  9930. await page.press(\"body\", \"A\")
  9931. await page.screenshot(path=\"a.png\")
  9932. await page.press(\"body\", \"ArrowLeft\")
  9933. await page.screenshot(path=\"arrow_left.png\")
  9934. await page.press(\"body\", \"Shift+O\")
  9935. await page.screenshot(path=\"o.png\")
  9936. await browser.close()
  9937. ```
  9938. Parameters
  9939. ----------
  9940. selector : str
  9941. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9942. used.
  9943. key : str
  9944. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  9945. delay : Union[float, None]
  9946. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  9947. timeout : Union[float, None]
  9948. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9949. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9950. no_wait_after : Union[bool, None]
  9951. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  9952. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  9953. navigating to inaccessible pages. Defaults to `false`.
  9954. Deprecated: This option will default to `true` in the future.
  9955. strict : Union[bool, None]
  9956. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9957. element, the call throws an exception.
  9958. """
  9959. return mapping.from_maybe_impl(
  9960. await self._impl_obj.press(
  9961. selector=selector,
  9962. key=key,
  9963. delay=delay,
  9964. timeout=to_milliseconds(timeout),
  9965. noWaitAfter=no_wait_after,
  9966. strict=strict,
  9967. )
  9968. )
  9969. async def check(
  9970. self,
  9971. selector: str,
  9972. *,
  9973. position: typing.Optional[Position] = None,
  9974. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  9975. force: typing.Optional[bool] = None,
  9976. no_wait_after: typing.Optional[bool] = None,
  9977. strict: typing.Optional[bool] = None,
  9978. trial: typing.Optional[bool] = None,
  9979. ) -> None:
  9980. """Page.check
  9981. This method checks an element matching `selector` by performing the following steps:
  9982. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9983. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  9984. already checked, this method returns immediately.
  9985. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9986. the element is detached during the checks, the whole action is retried.
  9987. 1. Scroll the element into view if needed.
  9988. 1. Use `page.mouse` to click in the center of the element.
  9989. 1. Ensure that the element is now checked. If not, this method throws.
  9990. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9991. Passing zero timeout disables this.
  9992. Parameters
  9993. ----------
  9994. selector : str
  9995. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9996. used.
  9997. position : Union[{x: float, y: float}, None]
  9998. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9999. the element.
  10000. timeout : Union[float, None]
  10001. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  10002. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  10003. force : Union[bool, None]
  10004. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  10005. no_wait_after : Union[bool, None]
  10006. This option has no effect.
  10007. Deprecated: This option has no effect.
  10008. strict : Union[bool, None]
  10009. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  10010. element, the call throws an exception.
  10011. trial : Union[bool, None]
  10012. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  10013. to `false`. Useful to wait until the element is ready for the action without performing it.
  10014. """
  10015. return mapping.from_maybe_impl(
  10016. await self._impl_obj.check(
  10017. selector=selector,
  10018. position=position,
  10019. timeout=to_milliseconds(timeout),
  10020. force=force,
  10021. noWaitAfter=no_wait_after,
  10022. strict=strict,
  10023. trial=trial,
  10024. )
  10025. )
  10026. async def uncheck(
  10027. self,
  10028. selector: str,
  10029. *,
  10030. position: typing.Optional[Position] = None,
  10031. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10032. force: typing.Optional[bool] = None,
  10033. no_wait_after: typing.Optional[bool] = None,
  10034. strict: typing.Optional[bool] = None,
  10035. trial: typing.Optional[bool] = None,
  10036. ) -> None:
  10037. """Page.uncheck
  10038. This method unchecks an element matching `selector` by performing the following steps:
  10039. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  10040. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  10041. already unchecked, this method returns immediately.
  10042. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  10043. the element is detached during the checks, the whole action is retried.
  10044. 1. Scroll the element into view if needed.
  10045. 1. Use `page.mouse` to click in the center of the element.
  10046. 1. Ensure that the element is now unchecked. If not, this method throws.
  10047. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  10048. Passing zero timeout disables this.
  10049. Parameters
  10050. ----------
  10051. selector : str
  10052. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  10053. used.
  10054. position : Union[{x: float, y: float}, None]
  10055. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  10056. the element.
  10057. timeout : Union[float, None]
  10058. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  10059. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  10060. force : Union[bool, None]
  10061. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  10062. no_wait_after : Union[bool, None]
  10063. This option has no effect.
  10064. Deprecated: This option has no effect.
  10065. strict : Union[bool, None]
  10066. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  10067. element, the call throws an exception.
  10068. trial : Union[bool, None]
  10069. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  10070. to `false`. Useful to wait until the element is ready for the action without performing it.
  10071. """
  10072. return mapping.from_maybe_impl(
  10073. await self._impl_obj.uncheck(
  10074. selector=selector,
  10075. position=position,
  10076. timeout=to_milliseconds(timeout),
  10077. force=force,
  10078. noWaitAfter=no_wait_after,
  10079. strict=strict,
  10080. trial=trial,
  10081. )
  10082. )
  10083. async def wait_for_timeout(
  10084. self, timeout: typing.Union[float, datetime.timedelta]
  10085. ) -> None:
  10086. """Page.wait_for_timeout
  10087. Waits for the given `timeout` in milliseconds.
  10088. Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
  10089. to be flaky. Use signals such as network events, selectors becoming visible and others instead.
  10090. **Usage**
  10091. ```py
  10092. # wait for 1 second
  10093. await page.wait_for_timeout(1000)
  10094. ```
  10095. Parameters
  10096. ----------
  10097. timeout : float
  10098. A timeout to wait for
  10099. """
  10100. return mapping.from_maybe_impl(
  10101. await self._impl_obj.wait_for_timeout(timeout=to_milliseconds(timeout))
  10102. )
  10103. async def wait_for_function(
  10104. self,
  10105. expression: str,
  10106. *,
  10107. arg: typing.Optional[typing.Any] = None,
  10108. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10109. polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
  10110. ) -> "JSHandle":
  10111. """Page.wait_for_function
  10112. Returns when the `expression` returns a truthy value. It resolves to a JSHandle of the truthy value.
  10113. **Usage**
  10114. The `page.wait_for_function()` can be used to observe viewport size change:
  10115. ```py
  10116. import asyncio
  10117. from playwright.async_api import async_playwright, Playwright
  10118. async def run(playwright: Playwright):
  10119. webkit = playwright.webkit
  10120. browser = await webkit.launch()
  10121. page = await browser.new_page()
  10122. await page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
  10123. await page.wait_for_function(\"() => window.x > 0\")
  10124. await browser.close()
  10125. async def main():
  10126. async with async_playwright() as playwright:
  10127. await run(playwright)
  10128. asyncio.run(main())
  10129. ```
  10130. To pass an argument to the predicate of `page.wait_for_function()` function:
  10131. ```py
  10132. selector = \".foo\"
  10133. await page.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
  10134. ```
  10135. Parameters
  10136. ----------
  10137. expression : str
  10138. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  10139. function is automatically invoked.
  10140. arg : Union[Any, None]
  10141. Optional argument to pass to `expression`.
  10142. timeout : Union[float, None]
  10143. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10144. default value can be changed by using the `browser_context.set_default_timeout()` or
  10145. `page.set_default_timeout()` methods.
  10146. polling : Union["raf", float, None]
  10147. If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
  10148. is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
  10149. `raf`.
  10150. Returns
  10151. -------
  10152. JSHandle
  10153. """
  10154. return mapping.from_impl(
  10155. await self._impl_obj.wait_for_function(
  10156. expression=expression,
  10157. arg=mapping.to_impl(arg),
  10158. timeout=to_milliseconds(timeout),
  10159. polling=polling,
  10160. )
  10161. )
  10162. async def pause(self) -> None:
  10163. """Page.pause
  10164. Pauses script execution. Playwright will stop executing the script and wait for the user to either press the
  10165. 'Resume' button in the page overlay or to call `playwright.resume()` in the DevTools console.
  10166. User can inspect selectors or perform manual steps while paused. Resume will continue running the original script
  10167. from the place it was paused.
  10168. **NOTE** This method requires Playwright to be started in a headed mode, with a falsy `headless` option.
  10169. """
  10170. return mapping.from_maybe_impl(await self._impl_obj.pause())
  10171. async def pdf(
  10172. self,
  10173. *,
  10174. scale: typing.Optional[float] = None,
  10175. display_header_footer: typing.Optional[bool] = None,
  10176. header_template: typing.Optional[str] = None,
  10177. footer_template: typing.Optional[str] = None,
  10178. print_background: typing.Optional[bool] = None,
  10179. landscape: typing.Optional[bool] = None,
  10180. page_ranges: typing.Optional[str] = None,
  10181. format: typing.Optional[str] = None,
  10182. width: typing.Optional[typing.Union[str, float]] = None,
  10183. height: typing.Optional[typing.Union[str, float]] = None,
  10184. prefer_css_page_size: typing.Optional[bool] = None,
  10185. margin: typing.Optional[PdfMargins] = None,
  10186. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  10187. outline: typing.Optional[bool] = None,
  10188. tagged: typing.Optional[bool] = None,
  10189. ) -> bytes:
  10190. """Page.pdf
  10191. Returns the PDF buffer.
  10192. `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
  10193. `page.emulate_media()` before calling `page.pdf()`:
  10194. **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
  10195. [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust)
  10196. property to force rendering of exact colors.
  10197. **Usage**
  10198. ```py
  10199. # generates a pdf with \"screen\" media type.
  10200. await page.emulate_media(media=\"screen\")
  10201. await page.pdf(path=\"page.pdf\")
  10202. ```
  10203. The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as
  10204. pixels.
  10205. A few examples:
  10206. - `page.pdf({width: 100})` - prints with width set to 100 pixels
  10207. - `page.pdf({width: '100px'})` - prints with width set to 100 pixels
  10208. - `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
  10209. All possible units are:
  10210. - `px` - pixel
  10211. - `in` - inch
  10212. - `cm` - centimeter
  10213. - `mm` - millimeter
  10214. The `format` options are:
  10215. - `Letter`: 8.5in x 11in
  10216. - `Legal`: 8.5in x 14in
  10217. - `Tabloid`: 11in x 17in
  10218. - `Ledger`: 17in x 11in
  10219. - `A0`: 33.1in x 46.8in
  10220. - `A1`: 23.4in x 33.1in
  10221. - `A2`: 16.54in x 23.4in
  10222. - `A3`: 11.7in x 16.54in
  10223. - `A4`: 8.27in x 11.7in
  10224. - `A5`: 5.83in x 8.27in
  10225. - `A6`: 4.13in x 5.83in
  10226. **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations: > 1. Script tags inside
  10227. templates are not evaluated. > 2. Page styles are not visible inside templates.
  10228. Parameters
  10229. ----------
  10230. scale : Union[float, None]
  10231. Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
  10232. display_header_footer : Union[bool, None]
  10233. Display header and footer. Defaults to `false`.
  10234. header_template : Union[str, None]
  10235. HTML template for the print header. Should be valid HTML markup with following classes used to inject printing
  10236. values into them:
  10237. - `'date'` formatted print date
  10238. - `'title'` document title
  10239. - `'url'` document location
  10240. - `'pageNumber'` current page number
  10241. - `'totalPages'` total pages in the document
  10242. footer_template : Union[str, None]
  10243. HTML template for the print footer. Should use the same format as the `headerTemplate`.
  10244. print_background : Union[bool, None]
  10245. Print background graphics. Defaults to `false`.
  10246. landscape : Union[bool, None]
  10247. Paper orientation. Defaults to `false`.
  10248. page_ranges : Union[str, None]
  10249. Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
  10250. format : Union[str, None]
  10251. Paper format. If set, takes priority over `width` or `height` options. Defaults to 'Letter'.
  10252. width : Union[float, str, None]
  10253. Paper width, accepts values labeled with units.
  10254. height : Union[float, str, None]
  10255. Paper height, accepts values labeled with units.
  10256. prefer_css_page_size : Union[bool, None]
  10257. Give any CSS `@page` size declared in the page priority over what is declared in `width` and `height` or `format`
  10258. options. Defaults to `false`, which will scale the content to fit the paper size.
  10259. margin : Union[{top: Union[float, str, None], right: Union[float, str, None], bottom: Union[float, str, None], left: Union[float, str, None]}, None]
  10260. Paper margins, defaults to none.
  10261. path : Union[pathlib.Path, str, None]
  10262. The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to the current working
  10263. directory. If no path is provided, the PDF won't be saved to the disk.
  10264. outline : Union[bool, None]
  10265. Whether or not to embed the document outline into the PDF. Defaults to `false`.
  10266. tagged : Union[bool, None]
  10267. Whether or not to generate tagged (accessible) PDF. Defaults to `false`.
  10268. Returns
  10269. -------
  10270. bytes
  10271. """
  10272. return mapping.from_maybe_impl(
  10273. await self._impl_obj.pdf(
  10274. scale=scale,
  10275. displayHeaderFooter=display_header_footer,
  10276. headerTemplate=header_template,
  10277. footerTemplate=footer_template,
  10278. printBackground=print_background,
  10279. landscape=landscape,
  10280. pageRanges=page_ranges,
  10281. format=format,
  10282. width=width,
  10283. height=height,
  10284. preferCSSPageSize=prefer_css_page_size,
  10285. margin=margin,
  10286. path=path,
  10287. outline=outline,
  10288. tagged=tagged,
  10289. )
  10290. )
  10291. @typing.overload
  10292. def expect_event(
  10293. self,
  10294. event: typing.Literal["close"],
  10295. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  10296. *,
  10297. timeout: typing.Optional[float] = None,
  10298. ) -> AsyncEventContextManager["Page"]: ...
  10299. @typing.overload
  10300. def expect_event(
  10301. self,
  10302. event: typing.Literal["console"],
  10303. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  10304. *,
  10305. timeout: typing.Optional[float] = None,
  10306. ) -> AsyncEventContextManager["ConsoleMessage"]: ...
  10307. @typing.overload
  10308. def expect_event(
  10309. self,
  10310. event: typing.Literal["crash"],
  10311. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  10312. *,
  10313. timeout: typing.Optional[float] = None,
  10314. ) -> AsyncEventContextManager["Page"]: ...
  10315. @typing.overload
  10316. def expect_event(
  10317. self,
  10318. event: typing.Literal["dialog"],
  10319. predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None,
  10320. *,
  10321. timeout: typing.Optional[float] = None,
  10322. ) -> AsyncEventContextManager["Dialog"]: ...
  10323. @typing.overload
  10324. def expect_event(
  10325. self,
  10326. event: typing.Literal["domcontentloaded"],
  10327. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  10328. *,
  10329. timeout: typing.Optional[float] = None,
  10330. ) -> AsyncEventContextManager["Page"]: ...
  10331. @typing.overload
  10332. def expect_event(
  10333. self,
  10334. event: typing.Literal["download"],
  10335. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  10336. *,
  10337. timeout: typing.Optional[float] = None,
  10338. ) -> AsyncEventContextManager["Download"]: ...
  10339. @typing.overload
  10340. def expect_event(
  10341. self,
  10342. event: typing.Literal["filechooser"],
  10343. predicate: typing.Optional[typing.Callable[["FileChooser"], bool]] = None,
  10344. *,
  10345. timeout: typing.Optional[float] = None,
  10346. ) -> AsyncEventContextManager["FileChooser"]: ...
  10347. @typing.overload
  10348. def expect_event(
  10349. self,
  10350. event: typing.Literal["frameattached"],
  10351. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  10352. *,
  10353. timeout: typing.Optional[float] = None,
  10354. ) -> AsyncEventContextManager["Frame"]: ...
  10355. @typing.overload
  10356. def expect_event(
  10357. self,
  10358. event: typing.Literal["framedetached"],
  10359. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  10360. *,
  10361. timeout: typing.Optional[float] = None,
  10362. ) -> AsyncEventContextManager["Frame"]: ...
  10363. @typing.overload
  10364. def expect_event(
  10365. self,
  10366. event: typing.Literal["framenavigated"],
  10367. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  10368. *,
  10369. timeout: typing.Optional[float] = None,
  10370. ) -> AsyncEventContextManager["Frame"]: ...
  10371. @typing.overload
  10372. def expect_event(
  10373. self,
  10374. event: typing.Literal["load"],
  10375. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  10376. *,
  10377. timeout: typing.Optional[float] = None,
  10378. ) -> AsyncEventContextManager["Page"]: ...
  10379. @typing.overload
  10380. def expect_event(
  10381. self,
  10382. event: typing.Literal["pageerror"],
  10383. predicate: typing.Optional[typing.Callable[["Error"], bool]] = None,
  10384. *,
  10385. timeout: typing.Optional[float] = None,
  10386. ) -> AsyncEventContextManager["Error"]: ...
  10387. @typing.overload
  10388. def expect_event(
  10389. self,
  10390. event: typing.Literal["popup"],
  10391. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  10392. *,
  10393. timeout: typing.Optional[float] = None,
  10394. ) -> AsyncEventContextManager["Page"]: ...
  10395. @typing.overload
  10396. def expect_event(
  10397. self,
  10398. event: typing.Literal["request"],
  10399. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  10400. *,
  10401. timeout: typing.Optional[float] = None,
  10402. ) -> AsyncEventContextManager["Request"]: ...
  10403. @typing.overload
  10404. def expect_event(
  10405. self,
  10406. event: typing.Literal["requestfailed"],
  10407. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  10408. *,
  10409. timeout: typing.Optional[float] = None,
  10410. ) -> AsyncEventContextManager["Request"]: ...
  10411. @typing.overload
  10412. def expect_event(
  10413. self,
  10414. event: typing.Literal["requestfinished"],
  10415. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  10416. *,
  10417. timeout: typing.Optional[float] = None,
  10418. ) -> AsyncEventContextManager["Request"]: ...
  10419. @typing.overload
  10420. def expect_event(
  10421. self,
  10422. event: typing.Literal["response"],
  10423. predicate: typing.Optional[typing.Callable[["Response"], bool]] = None,
  10424. *,
  10425. timeout: typing.Optional[float] = None,
  10426. ) -> AsyncEventContextManager["Response"]: ...
  10427. @typing.overload
  10428. def expect_event(
  10429. self,
  10430. event: typing.Literal["websocket"],
  10431. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  10432. *,
  10433. timeout: typing.Optional[float] = None,
  10434. ) -> AsyncEventContextManager["WebSocket"]: ...
  10435. @typing.overload
  10436. def expect_event(
  10437. self,
  10438. event: typing.Literal["worker"],
  10439. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  10440. *,
  10441. timeout: typing.Optional[float] = None,
  10442. ) -> AsyncEventContextManager["Worker"]: ...
  10443. @typing.overload
  10444. def expect_event(
  10445. self,
  10446. event: str,
  10447. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  10448. *,
  10449. timeout: typing.Optional[float] = None,
  10450. ) -> AsyncEventContextManager[typing.Any]: ...
  10451. def expect_event(
  10452. self,
  10453. event: str,
  10454. predicate: typing.Optional[typing.Callable] = None,
  10455. *,
  10456. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10457. ) -> AsyncEventContextManager:
  10458. """Page.expect_event
  10459. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  10460. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
  10461. **Usage**
  10462. ```py
  10463. async with page.expect_event(\"framenavigated\") as event_info:
  10464. await page.get_by_role(\"button\")
  10465. frame = await event_info.value
  10466. ```
  10467. Parameters
  10468. ----------
  10469. event : str
  10470. Event name, same one typically passed into `*.on(event)`.
  10471. predicate : Union[Callable, None]
  10472. Receives the event data and resolves to truthy value when the waiting should resolve.
  10473. timeout : Union[float, None]
  10474. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10475. default value can be changed by using the `browser_context.set_default_timeout()`.
  10476. Returns
  10477. -------
  10478. EventContextManager
  10479. """
  10480. return AsyncEventContextManager(
  10481. self._impl_obj.expect_event(
  10482. event=event,
  10483. predicate=self._wrap_handler(predicate),
  10484. timeout=to_milliseconds(timeout),
  10485. ).future
  10486. )
  10487. def expect_console_message(
  10488. self,
  10489. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  10490. *,
  10491. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10492. ) -> AsyncEventContextManager["ConsoleMessage"]:
  10493. """Page.expect_console_message
  10494. Performs action and waits for a `ConsoleMessage` to be logged by in the page. If predicate is provided, it passes
  10495. `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to return a truthy value.
  10496. Will throw an error if the page is closed before the `page.on('console')` event is fired.
  10497. Parameters
  10498. ----------
  10499. predicate : Union[Callable[[ConsoleMessage], bool], None]
  10500. Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
  10501. timeout : Union[float, None]
  10502. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10503. default value can be changed by using the `browser_context.set_default_timeout()`.
  10504. Returns
  10505. -------
  10506. EventContextManager[ConsoleMessage]
  10507. """
  10508. return AsyncEventContextManager(
  10509. self._impl_obj.expect_console_message(
  10510. predicate=self._wrap_handler(predicate),
  10511. timeout=to_milliseconds(timeout),
  10512. ).future
  10513. )
  10514. def expect_download(
  10515. self,
  10516. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  10517. *,
  10518. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10519. ) -> AsyncEventContextManager["Download"]:
  10520. """Page.expect_download
  10521. Performs action and waits for a new `Download`. If predicate is provided, it passes `Download` value into the
  10522. `predicate` function and waits for `predicate(download)` to return a truthy value. Will throw an error if the page
  10523. is closed before the download event is fired.
  10524. Parameters
  10525. ----------
  10526. predicate : Union[Callable[[Download], bool], None]
  10527. Receives the `Download` object and resolves to truthy value when the waiting should resolve.
  10528. timeout : Union[float, None]
  10529. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10530. default value can be changed by using the `browser_context.set_default_timeout()`.
  10531. Returns
  10532. -------
  10533. EventContextManager[Download]
  10534. """
  10535. return AsyncEventContextManager(
  10536. self._impl_obj.expect_download(
  10537. predicate=self._wrap_handler(predicate),
  10538. timeout=to_milliseconds(timeout),
  10539. ).future
  10540. )
  10541. def expect_file_chooser(
  10542. self,
  10543. predicate: typing.Optional[typing.Callable[["FileChooser"], bool]] = None,
  10544. *,
  10545. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10546. ) -> AsyncEventContextManager["FileChooser"]:
  10547. """Page.expect_file_chooser
  10548. Performs action and waits for a new `FileChooser` to be created. If predicate is provided, it passes `FileChooser`
  10549. value into the `predicate` function and waits for `predicate(fileChooser)` to return a truthy value. Will throw an
  10550. error if the page is closed before the file chooser is opened.
  10551. Parameters
  10552. ----------
  10553. predicate : Union[Callable[[FileChooser], bool], None]
  10554. Receives the `FileChooser` object and resolves to truthy value when the waiting should resolve.
  10555. timeout : Union[float, None]
  10556. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10557. default value can be changed by using the `browser_context.set_default_timeout()`.
  10558. Returns
  10559. -------
  10560. EventContextManager[FileChooser]
  10561. """
  10562. return AsyncEventContextManager(
  10563. self._impl_obj.expect_file_chooser(
  10564. predicate=self._wrap_handler(predicate),
  10565. timeout=to_milliseconds(timeout),
  10566. ).future
  10567. )
  10568. def expect_navigation(
  10569. self,
  10570. *,
  10571. url: typing.Optional[
  10572. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  10573. ] = None,
  10574. wait_until: typing.Optional[
  10575. Literal["commit", "domcontentloaded", "load", "networkidle"]
  10576. ] = None,
  10577. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10578. ) -> AsyncEventContextManager["Response"]:
  10579. """Page.expect_navigation
  10580. Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the
  10581. navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
  10582. navigation due to History API usage, the navigation will resolve with `null`.
  10583. **Usage**
  10584. This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will
  10585. indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from
  10586. a `setTimeout`. Consider this example:
  10587. ```py
  10588. async with page.expect_navigation():
  10589. # This action triggers the navigation after a timeout.
  10590. await page.get_by_text(\"Navigate after timeout\").click()
  10591. # Resolves after navigation has finished
  10592. ```
  10593. **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
  10594. is considered a navigation.
  10595. Parameters
  10596. ----------
  10597. url : Union[Callable[[str], bool], Pattern[str], str, None]
  10598. A glob pattern, regex pattern, or predicate receiving [URL] to match while waiting for the navigation. Note that if
  10599. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  10600. equal to the string.
  10601. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  10602. When to consider operation succeeded, defaults to `load`. Events can be either:
  10603. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  10604. - `'load'` - consider operation to be finished when the `load` event is fired.
  10605. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  10606. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  10607. - `'commit'` - consider operation to be finished when network response is received and the document started
  10608. loading.
  10609. timeout : Union[float, None]
  10610. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  10611. be changed by using the `browser_context.set_default_navigation_timeout()`,
  10612. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  10613. `page.set_default_timeout()` methods.
  10614. Returns
  10615. -------
  10616. EventContextManager[Response]
  10617. """
  10618. return AsyncEventContextManager(
  10619. self._impl_obj.expect_navigation(
  10620. url=self._wrap_handler(url),
  10621. waitUntil=wait_until,
  10622. timeout=to_milliseconds(timeout),
  10623. ).future
  10624. )
  10625. def expect_popup(
  10626. self,
  10627. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  10628. *,
  10629. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10630. ) -> AsyncEventContextManager["Page"]:
  10631. """Page.expect_popup
  10632. Performs action and waits for a popup `Page`. If predicate is provided, it passes [Popup] value into the
  10633. `predicate` function and waits for `predicate(page)` to return a truthy value. Will throw an error if the page is
  10634. closed before the popup event is fired.
  10635. Parameters
  10636. ----------
  10637. predicate : Union[Callable[[Page], bool], None]
  10638. Receives the `Page` object and resolves to truthy value when the waiting should resolve.
  10639. timeout : Union[float, None]
  10640. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10641. default value can be changed by using the `browser_context.set_default_timeout()`.
  10642. Returns
  10643. -------
  10644. EventContextManager[Page]
  10645. """
  10646. return AsyncEventContextManager(
  10647. self._impl_obj.expect_popup(
  10648. predicate=self._wrap_handler(predicate),
  10649. timeout=to_milliseconds(timeout),
  10650. ).future
  10651. )
  10652. def expect_request(
  10653. self,
  10654. url_or_predicate: typing.Union[
  10655. str,
  10656. typing.Pattern[str],
  10657. typing.Callable[["Request"], typing.Union[bool, typing.Awaitable[bool]]],
  10658. ],
  10659. *,
  10660. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10661. ) -> AsyncEventContextManager["Request"]:
  10662. """Page.expect_request
  10663. Waits for the matching request and returns it. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more
  10664. details about events.
  10665. **Usage**
  10666. ```py
  10667. async with page.expect_request(\"http://example.com/resource\") as first:
  10668. await page.get_by_text(\"trigger request\").click()
  10669. first_request = await first.value
  10670. # or with a lambda
  10671. async with page.expect_request(lambda request: request.url == \"http://example.com\" and request.method == \"get\") as second:
  10672. await page.get_by_text(\"trigger request\").click()
  10673. second_request = await second.value
  10674. ```
  10675. Parameters
  10676. ----------
  10677. url_or_predicate : Union[Callable[[Request], Union[bool, typing.Awaitable[bool]]], Pattern[str], str]
  10678. Request URL string, regex or predicate receiving `Request` object. When a `baseURL` via the context options was
  10679. provided and the passed URL is a path, it gets merged via the
  10680. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  10681. timeout : Union[float, None]
  10682. Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
  10683. be changed by using the `page.set_default_timeout()` method.
  10684. Returns
  10685. -------
  10686. EventContextManager[Request]
  10687. """
  10688. return AsyncEventContextManager(
  10689. self._impl_obj.expect_request(
  10690. urlOrPredicate=self._wrap_handler(url_or_predicate),
  10691. timeout=to_milliseconds(timeout),
  10692. ).future
  10693. )
  10694. def expect_request_finished(
  10695. self,
  10696. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  10697. *,
  10698. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10699. ) -> AsyncEventContextManager["Request"]:
  10700. """Page.expect_request_finished
  10701. Performs action and waits for a `Request` to finish loading. If predicate is provided, it passes `Request` value
  10702. into the `predicate` function and waits for `predicate(request)` to return a truthy value. Will throw an error if
  10703. the page is closed before the `page.on('request_finished')` event is fired.
  10704. Parameters
  10705. ----------
  10706. predicate : Union[Callable[[Request], bool], None]
  10707. Receives the `Request` object and resolves to truthy value when the waiting should resolve.
  10708. timeout : Union[float, None]
  10709. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10710. default value can be changed by using the `browser_context.set_default_timeout()`.
  10711. Returns
  10712. -------
  10713. EventContextManager[Request]
  10714. """
  10715. return AsyncEventContextManager(
  10716. self._impl_obj.expect_request_finished(
  10717. predicate=self._wrap_handler(predicate),
  10718. timeout=to_milliseconds(timeout),
  10719. ).future
  10720. )
  10721. def expect_response(
  10722. self,
  10723. url_or_predicate: typing.Union[
  10724. str,
  10725. typing.Pattern[str],
  10726. typing.Callable[["Response"], typing.Union[bool, typing.Awaitable[bool]]],
  10727. ],
  10728. *,
  10729. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10730. ) -> AsyncEventContextManager["Response"]:
  10731. """Page.expect_response
  10732. Returns the matched response. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more details about
  10733. events.
  10734. **Usage**
  10735. ```py
  10736. async with page.expect_response(\"https://example.com/resource\") as response_info:
  10737. await page.get_by_text(\"trigger response\").click()
  10738. response = await response_info.value
  10739. return response.ok
  10740. # or with a lambda
  10741. async with page.expect_response(lambda response: response.url == \"https://example.com\" and response.status == 200 and response.request.method == \"get\") as response_info:
  10742. await page.get_by_text(\"trigger response\").click()
  10743. response = await response_info.value
  10744. return response.ok
  10745. ```
  10746. Parameters
  10747. ----------
  10748. url_or_predicate : Union[Callable[[Response], Union[bool, typing.Awaitable[bool]]], Pattern[str], str]
  10749. Request URL string, regex or predicate receiving `Response` object. When a `baseURL` via the context options was
  10750. provided and the passed URL is a path, it gets merged via the
  10751. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  10752. timeout : Union[float, None]
  10753. Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
  10754. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  10755. Returns
  10756. -------
  10757. EventContextManager[Response]
  10758. """
  10759. return AsyncEventContextManager(
  10760. self._impl_obj.expect_response(
  10761. urlOrPredicate=self._wrap_handler(url_or_predicate),
  10762. timeout=to_milliseconds(timeout),
  10763. ).future
  10764. )
  10765. def expect_websocket(
  10766. self,
  10767. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  10768. *,
  10769. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10770. ) -> AsyncEventContextManager["WebSocket"]:
  10771. """Page.expect_websocket
  10772. Performs action and waits for a new `WebSocket`. If predicate is provided, it passes `WebSocket` value into the
  10773. `predicate` function and waits for `predicate(webSocket)` to return a truthy value. Will throw an error if the page
  10774. is closed before the WebSocket event is fired.
  10775. Parameters
  10776. ----------
  10777. predicate : Union[Callable[[WebSocket], bool], None]
  10778. Receives the `WebSocket` object and resolves to truthy value when the waiting should resolve.
  10779. timeout : Union[float, None]
  10780. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10781. default value can be changed by using the `browser_context.set_default_timeout()`.
  10782. Returns
  10783. -------
  10784. EventContextManager[WebSocket]
  10785. """
  10786. return AsyncEventContextManager(
  10787. self._impl_obj.expect_websocket(
  10788. predicate=self._wrap_handler(predicate),
  10789. timeout=to_milliseconds(timeout),
  10790. ).future
  10791. )
  10792. def expect_worker(
  10793. self,
  10794. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  10795. *,
  10796. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10797. ) -> AsyncEventContextManager["Worker"]:
  10798. """Page.expect_worker
  10799. Performs action and waits for a new `Worker`. If predicate is provided, it passes `Worker` value into the
  10800. `predicate` function and waits for `predicate(worker)` to return a truthy value. Will throw an error if the page is
  10801. closed before the worker event is fired.
  10802. Parameters
  10803. ----------
  10804. predicate : Union[Callable[[Worker], bool], None]
  10805. Receives the `Worker` object and resolves to truthy value when the waiting should resolve.
  10806. timeout : Union[float, None]
  10807. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  10808. default value can be changed by using the `browser_context.set_default_timeout()`.
  10809. Returns
  10810. -------
  10811. EventContextManager[Worker]
  10812. """
  10813. return AsyncEventContextManager(
  10814. self._impl_obj.expect_worker(
  10815. predicate=self._wrap_handler(predicate),
  10816. timeout=to_milliseconds(timeout),
  10817. ).future
  10818. )
  10819. async def set_checked(
  10820. self,
  10821. selector: str,
  10822. checked: bool,
  10823. *,
  10824. position: typing.Optional[Position] = None,
  10825. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  10826. force: typing.Optional[bool] = None,
  10827. no_wait_after: typing.Optional[bool] = None,
  10828. strict: typing.Optional[bool] = None,
  10829. trial: typing.Optional[bool] = None,
  10830. ) -> None:
  10831. """Page.set_checked
  10832. This method checks or unchecks an element matching `selector` by performing the following steps:
  10833. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  10834. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  10835. 1. If the element already has the right checked state, this method returns immediately.
  10836. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  10837. the element is detached during the checks, the whole action is retried.
  10838. 1. Scroll the element into view if needed.
  10839. 1. Use `page.mouse` to click in the center of the element.
  10840. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  10841. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  10842. Passing zero timeout disables this.
  10843. Parameters
  10844. ----------
  10845. selector : str
  10846. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  10847. used.
  10848. checked : bool
  10849. Whether to check or uncheck the checkbox.
  10850. position : Union[{x: float, y: float}, None]
  10851. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  10852. the element.
  10853. timeout : Union[float, None]
  10854. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  10855. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  10856. force : Union[bool, None]
  10857. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  10858. no_wait_after : Union[bool, None]
  10859. This option has no effect.
  10860. Deprecated: This option has no effect.
  10861. strict : Union[bool, None]
  10862. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  10863. element, the call throws an exception.
  10864. trial : Union[bool, None]
  10865. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  10866. to `false`. Useful to wait until the element is ready for the action without performing it.
  10867. """
  10868. return mapping.from_maybe_impl(
  10869. await self._impl_obj.set_checked(
  10870. selector=selector,
  10871. checked=checked,
  10872. position=position,
  10873. timeout=to_milliseconds(timeout),
  10874. force=force,
  10875. noWaitAfter=no_wait_after,
  10876. strict=strict,
  10877. trial=trial,
  10878. )
  10879. )
  10880. async def add_locator_handler(
  10881. self,
  10882. locator: "Locator",
  10883. handler: typing.Union[
  10884. typing.Callable[["Locator"], typing.Any], typing.Callable[[], typing.Any]
  10885. ],
  10886. *,
  10887. no_wait_after: typing.Optional[bool] = None,
  10888. times: typing.Optional[int] = None,
  10889. ) -> None:
  10890. """Page.add_locator_handler
  10891. When testing a web page, sometimes unexpected overlays like a \"Sign up\" dialog appear and block actions you want to
  10892. automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making
  10893. them tricky to handle in automated tests.
  10894. This method lets you set up a special function, called a handler, that activates when it detects that overlay is
  10895. visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
  10896. Things to keep in mind:
  10897. - When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as
  10898. a part of your normal test flow, instead of using `page.add_locator_handler()`.
  10899. - Playwright checks for the overlay every time before executing or retrying an action that requires an
  10900. [actionability check](https://playwright.dev/python/docs/actionability), or before performing an auto-waiting assertion check. When overlay
  10901. is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the
  10902. handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't
  10903. perform any actions, the handler will not be triggered.
  10904. - After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible
  10905. anymore. You can opt-out of this behavior with `noWaitAfter`.
  10906. - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler.
  10907. If your handler takes too long, it might cause timeouts.
  10908. - You can register multiple handlers. However, only a single handler will be running at a time. Make sure the
  10909. actions within a handler don't depend on another handler.
  10910. **NOTE** Running the handler will alter your page state mid-test. For example it will change the currently focused
  10911. element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on
  10912. the focus and mouse state being unchanged.
  10913. For example, consider a test that calls `locator.focus()` followed by `keyboard.press()`. If your
  10914. handler clicks a button between these two actions, the focused element most likely will be wrong, and key press
  10915. will happen on the unexpected element. Use `locator.press()` instead to avoid this problem.
  10916. Another example is a series of mouse actions, where `mouse.move()` is followed by `mouse.down()`.
  10917. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down.
  10918. Prefer self-contained actions like `locator.click()` that do not rely on the state being unchanged by a
  10919. handler.
  10920. **Usage**
  10921. An example that closes a \"Sign up to the newsletter\" dialog when it appears:
  10922. ```py
  10923. # Setup the handler.
  10924. def handler():
  10925. page.get_by_role(\"button\", name=\"No thanks\").click()
  10926. page.add_locator_handler(page.get_by_text(\"Sign up to the newsletter\"), handler)
  10927. # Write the test as usual.
  10928. page.goto(\"https://example.com\")
  10929. page.get_by_role(\"button\", name=\"Start here\").click()
  10930. ```
  10931. An example that skips the \"Confirm your security details\" page when it is shown:
  10932. ```py
  10933. # Setup the handler.
  10934. def handler():
  10935. page.get_by_role(\"button\", name=\"Remind me later\").click()
  10936. page.add_locator_handler(page.get_by_text(\"Confirm your security details\"), handler)
  10937. # Write the test as usual.
  10938. page.goto(\"https://example.com\")
  10939. page.get_by_role(\"button\", name=\"Start here\").click()
  10940. ```
  10941. An example with a custom callback on every actionability check. It uses a `<body>` locator that is always visible,
  10942. so the handler is called before every actionability check. It is important to specify `noWaitAfter`, because the
  10943. handler does not hide the `<body>` element.
  10944. ```py
  10945. # Setup the handler.
  10946. def handler():
  10947. page.evaluate(\"window.removeObstructionsForTestIfNeeded()\")
  10948. page.add_locator_handler(page.locator(\"body\"), handler, no_wait_after=True)
  10949. # Write the test as usual.
  10950. page.goto(\"https://example.com\")
  10951. page.get_by_role(\"button\", name=\"Start here\").click()
  10952. ```
  10953. Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
  10954. invocations by setting `times`:
  10955. ```py
  10956. def handler(locator):
  10957. locator.click()
  10958. page.add_locator_handler(page.get_by_label(\"Close\"), handler, times=1)
  10959. ```
  10960. Parameters
  10961. ----------
  10962. locator : Locator
  10963. Locator that triggers the handler.
  10964. handler : Union[Callable[[Locator], Any], Callable[[], Any]]
  10965. Function that should be run once `locator` appears. This function should get rid of the element that blocks actions
  10966. like click.
  10967. no_wait_after : Union[bool, None]
  10968. By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then
  10969. Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of
  10970. this behavior, so that overlay can stay visible after the handler has run.
  10971. times : Union[int, None]
  10972. Specifies the maximum number of times this handler should be called. Unlimited by default.
  10973. """
  10974. return mapping.from_maybe_impl(
  10975. await self._impl_obj.add_locator_handler(
  10976. locator=locator._impl_obj,
  10977. handler=self._wrap_handler(handler),
  10978. noWaitAfter=no_wait_after,
  10979. times=times,
  10980. )
  10981. )
  10982. async def remove_locator_handler(self, locator: "Locator") -> None:
  10983. """Page.remove_locator_handler
  10984. Removes all locator handlers added by `page.add_locator_handler()` for a specific locator.
  10985. Parameters
  10986. ----------
  10987. locator : Locator
  10988. Locator passed to `page.add_locator_handler()`.
  10989. """
  10990. return mapping.from_maybe_impl(
  10991. await self._impl_obj.remove_locator_handler(locator=locator._impl_obj)
  10992. )
  10993. async def requests(self) -> typing.List["Request"]:
  10994. """Page.requests
  10995. Returns up to (currently) 100 last network request from this page. See `page.on('request')` for more details.
  10996. Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory
  10997. growth as new requests come in. Once collected, retrieving most information about the request is impossible.
  10998. Note that requests reported through the `page.on('request')` request are not collected, so there is a trade off
  10999. between efficient memory usage with `page.requests()` and the amount of available information reported
  11000. through `page.on('request')`.
  11001. Returns
  11002. -------
  11003. List[Request]
  11004. """
  11005. return mapping.from_impl_list(await self._impl_obj.requests())
  11006. async def console_messages(
  11007. self, *, filter: typing.Optional[Literal["all", "since-navigation"]] = None
  11008. ) -> typing.List["ConsoleMessage"]:
  11009. """Page.console_messages
  11010. Returns up to (currently) 200 last console messages from this page. See `page.on('console')` for more details.
  11011. Parameters
  11012. ----------
  11013. filter : Union["all", "since-navigation", None]
  11014. Controls which messages are returned:
  11015. Returns
  11016. -------
  11017. List[ConsoleMessage]
  11018. """
  11019. return mapping.from_impl_list(
  11020. await self._impl_obj.console_messages(filter=filter)
  11021. )
  11022. async def page_errors(
  11023. self, *, filter: typing.Optional[Literal["all", "since-navigation"]] = None
  11024. ) -> typing.List["Error"]:
  11025. """Page.page_errors
  11026. Returns up to (currently) 200 last page errors from this page. See `page.on('page_error')` for more details.
  11027. Parameters
  11028. ----------
  11029. filter : Union["all", "since-navigation", None]
  11030. Controls which errors are returned:
  11031. Returns
  11032. -------
  11033. List[Error]
  11034. """
  11035. return mapping.from_impl_list(await self._impl_obj.page_errors(filter=filter))
  11036. async def clear_console_messages(self) -> None:
  11037. """Page.clear_console_messages
  11038. Clears all stored console messages from this page. Subsequent calls to `page.console_messages()` will only
  11039. return messages logged after the clear.
  11040. """
  11041. return mapping.from_maybe_impl(await self._impl_obj.clear_console_messages())
  11042. async def clear_page_errors(self) -> None:
  11043. """Page.clear_page_errors
  11044. Clears all stored page errors from this page. Subsequent calls to `page.page_errors()` will only return
  11045. errors thrown after the clear.
  11046. """
  11047. return mapping.from_maybe_impl(await self._impl_obj.clear_page_errors())
  11048. async def pick_locator(self) -> "Locator":
  11049. """Page.pick_locator
  11050. Enters pick locator mode where hovering over page elements highlights them and shows the corresponding locator.
  11051. Once the user clicks an element, the mode is deactivated and the `Locator` for the picked element is returned.
  11052. **Usage**
  11053. ```py
  11054. locator = await page.pick_locator()
  11055. print(locator)
  11056. ```
  11057. Returns
  11058. -------
  11059. Locator
  11060. """
  11061. return mapping.from_impl(await self._impl_obj.pick_locator())
  11062. async def cancel_pick_locator(self) -> None:
  11063. """Page.cancel_pick_locator
  11064. Cancels an ongoing `page.pick_locator()` call by deactivating pick locator mode. If no pick locator mode is
  11065. active, this method is a no-op.
  11066. """
  11067. return mapping.from_maybe_impl(await self._impl_obj.cancel_pick_locator())
  11068. mapping.register(PageImpl, Page)
  11069. class WebError(AsyncBase):
  11070. @property
  11071. def page(self) -> typing.Optional["Page"]:
  11072. """WebError.page
  11073. The page that produced this unhandled exception, if any.
  11074. Returns
  11075. -------
  11076. Union[Page, None]
  11077. """
  11078. return mapping.from_impl_nullable(self._impl_obj.page)
  11079. @property
  11080. def error(self) -> "Error":
  11081. """WebError.error
  11082. Unhandled error that was thrown.
  11083. Returns
  11084. -------
  11085. Error
  11086. """
  11087. return mapping.from_impl(self._impl_obj.error)
  11088. @property
  11089. def location(self) -> WebErrorLocation:
  11090. """WebError.location
  11091. Returns
  11092. -------
  11093. {url: str, line: int, column: int}
  11094. """
  11095. return mapping.from_impl(self._impl_obj.location)
  11096. mapping.register(WebErrorImpl, WebError)
  11097. class BrowserContext(AsyncContextManager):
  11098. @typing.overload
  11099. def on(
  11100. self,
  11101. event: Literal["backgroundpage"],
  11102. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11103. ) -> None:
  11104. """
  11105. This event is not emitted."""
  11106. @typing.overload
  11107. def on(
  11108. self,
  11109. event: Literal["close"],
  11110. f: typing.Callable[
  11111. ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]"
  11112. ],
  11113. ) -> None:
  11114. """
  11115. Emitted when Browser context gets closed. This might happen because of one of the following:
  11116. - Browser context is closed.
  11117. - Browser application is closed or crashed.
  11118. - The `browser.close()` method was called."""
  11119. @typing.overload
  11120. def on(
  11121. self,
  11122. event: Literal["console"],
  11123. f: typing.Callable[
  11124. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  11125. ],
  11126. ) -> None:
  11127. """
  11128. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  11129. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
  11130. **Usage**
  11131. ```py
  11132. async def print_args(msg):
  11133. values = []
  11134. for arg in msg.args:
  11135. values.append(await arg.json_value())
  11136. print(values)
  11137. context.on(\"console\", print_args)
  11138. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  11139. ```"""
  11140. @typing.overload
  11141. def on(
  11142. self,
  11143. event: Literal["dialog"],
  11144. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  11145. ) -> None:
  11146. """
  11147. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  11148. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  11149. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  11150. and actions like click will never finish.
  11151. **Usage**
  11152. ```python
  11153. context.on(\"dialog\", lambda dialog: dialog.accept())
  11154. ```
  11155. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  11156. automatically dismissed."""
  11157. @typing.overload
  11158. def on(
  11159. self,
  11160. event: Literal["download"],
  11161. f: typing.Callable[["Download"], "typing.Union[typing.Awaitable[None], None]"],
  11162. ) -> None:
  11163. """
  11164. Emitted when attachment download started in any page belonging to this context. User can access basic file
  11165. operations on downloaded content via the passed `Download` instance. See also `page.on('download')` to receive
  11166. events about a specific page."""
  11167. @typing.overload
  11168. def on(
  11169. self,
  11170. event: Literal["frameattached"],
  11171. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  11172. ) -> None:
  11173. """
  11174. Emitted when a frame is attached in any page belonging to this context. See also `page.on('frame_attached')` to
  11175. receive events about a specific page."""
  11176. @typing.overload
  11177. def on(
  11178. self,
  11179. event: Literal["framedetached"],
  11180. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  11181. ) -> None:
  11182. """
  11183. Emitted when a frame is detached in any page belonging to this context. See also `page.on('frame_detached')` to
  11184. receive events about a specific page."""
  11185. @typing.overload
  11186. def on(
  11187. self,
  11188. event: Literal["framenavigated"],
  11189. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  11190. ) -> None:
  11191. """
  11192. Emitted when a frame is navigated to a new url in any page belonging to this context. See also
  11193. `page.on('frame_navigated')` to receive events about navigations in a specific page.
  11194. """
  11195. @typing.overload
  11196. def on(
  11197. self,
  11198. event: Literal["page"],
  11199. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11200. ) -> None:
  11201. """
  11202. The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
  11203. will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
  11204. specific page.
  11205. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  11206. popup with `window.open('http://example.com')`, this event will fire when the network request to
  11207. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  11208. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  11209. instead of similar methods on the `Page`.
  11210. ```py
  11211. async with context.expect_page() as page_info:
  11212. await page.get_by_text(\"open new page\").click(),
  11213. page = await page_info.value
  11214. print(await page.evaluate(\"location.href\"))
  11215. ```
  11216. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  11217. need it in most cases)."""
  11218. @typing.overload
  11219. def on(
  11220. self,
  11221. event: Literal["pageclose"],
  11222. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11223. ) -> None:
  11224. """
  11225. Emitted when a page in this context is closed. See also `page.on('close')` to receive events about a specific
  11226. page."""
  11227. @typing.overload
  11228. def on(
  11229. self,
  11230. event: Literal["pageload"],
  11231. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11232. ) -> None:
  11233. """
  11234. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched
  11235. in any page belonging to this context. See also `page.on('load')` to receive events about a specific page.
  11236. """
  11237. @typing.overload
  11238. def on(
  11239. self,
  11240. event: Literal["weberror"],
  11241. f: typing.Callable[["WebError"], "typing.Union[typing.Awaitable[None], None]"],
  11242. ) -> None:
  11243. """
  11244. Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
  11245. page, use `page.on('page_error')` instead."""
  11246. @typing.overload
  11247. def on(
  11248. self,
  11249. event: Literal["request"],
  11250. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  11251. ) -> None:
  11252. """
  11253. Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
  11254. only listen for requests from a particular page, use `page.on('request')`.
  11255. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
  11256. """
  11257. @typing.overload
  11258. def on(
  11259. self,
  11260. event: Literal["requestfailed"],
  11261. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  11262. ) -> None:
  11263. """
  11264. Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
  11265. use `page.on('request_failed')`.
  11266. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  11267. will complete with `browser_context.on('request_finished')` event and not with
  11268. `browser_context.on('request_failed')`."""
  11269. @typing.overload
  11270. def on(
  11271. self,
  11272. event: Literal["requestfinished"],
  11273. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  11274. ) -> None:
  11275. """
  11276. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  11277. sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
  11278. particular page, use `page.on('request_finished')`."""
  11279. @typing.overload
  11280. def on(
  11281. self,
  11282. event: Literal["response"],
  11283. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  11284. ) -> None:
  11285. """
  11286. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  11287. events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
  11288. `page.on('response')`."""
  11289. @typing.overload
  11290. def on(
  11291. self,
  11292. event: Literal["serviceworker"],
  11293. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  11294. ) -> None:
  11295. """
  11296. **NOTE** Service workers are only supported on Chromium-based browsers.
  11297. Emitted when new service worker is created in the context."""
  11298. def on(
  11299. self,
  11300. event: str,
  11301. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  11302. ) -> None:
  11303. return super().on(event=event, f=f)
  11304. @typing.overload
  11305. def once(
  11306. self,
  11307. event: Literal["backgroundpage"],
  11308. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11309. ) -> None:
  11310. """
  11311. This event is not emitted."""
  11312. @typing.overload
  11313. def once(
  11314. self,
  11315. event: Literal["close"],
  11316. f: typing.Callable[
  11317. ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]"
  11318. ],
  11319. ) -> None:
  11320. """
  11321. Emitted when Browser context gets closed. This might happen because of one of the following:
  11322. - Browser context is closed.
  11323. - Browser application is closed or crashed.
  11324. - The `browser.close()` method was called."""
  11325. @typing.overload
  11326. def once(
  11327. self,
  11328. event: Literal["console"],
  11329. f: typing.Callable[
  11330. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  11331. ],
  11332. ) -> None:
  11333. """
  11334. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  11335. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
  11336. **Usage**
  11337. ```py
  11338. async def print_args(msg):
  11339. values = []
  11340. for arg in msg.args:
  11341. values.append(await arg.json_value())
  11342. print(values)
  11343. context.on(\"console\", print_args)
  11344. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  11345. ```"""
  11346. @typing.overload
  11347. def once(
  11348. self,
  11349. event: Literal["dialog"],
  11350. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  11351. ) -> None:
  11352. """
  11353. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  11354. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  11355. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  11356. and actions like click will never finish.
  11357. **Usage**
  11358. ```python
  11359. context.on(\"dialog\", lambda dialog: dialog.accept())
  11360. ```
  11361. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  11362. automatically dismissed."""
  11363. @typing.overload
  11364. def once(
  11365. self,
  11366. event: Literal["download"],
  11367. f: typing.Callable[["Download"], "typing.Union[typing.Awaitable[None], None]"],
  11368. ) -> None:
  11369. """
  11370. Emitted when attachment download started in any page belonging to this context. User can access basic file
  11371. operations on downloaded content via the passed `Download` instance. See also `page.on('download')` to receive
  11372. events about a specific page."""
  11373. @typing.overload
  11374. def once(
  11375. self,
  11376. event: Literal["frameattached"],
  11377. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  11378. ) -> None:
  11379. """
  11380. Emitted when a frame is attached in any page belonging to this context. See also `page.on('frame_attached')` to
  11381. receive events about a specific page."""
  11382. @typing.overload
  11383. def once(
  11384. self,
  11385. event: Literal["framedetached"],
  11386. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  11387. ) -> None:
  11388. """
  11389. Emitted when a frame is detached in any page belonging to this context. See also `page.on('frame_detached')` to
  11390. receive events about a specific page."""
  11391. @typing.overload
  11392. def once(
  11393. self,
  11394. event: Literal["framenavigated"],
  11395. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  11396. ) -> None:
  11397. """
  11398. Emitted when a frame is navigated to a new url in any page belonging to this context. See also
  11399. `page.on('frame_navigated')` to receive events about navigations in a specific page.
  11400. """
  11401. @typing.overload
  11402. def once(
  11403. self,
  11404. event: Literal["page"],
  11405. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11406. ) -> None:
  11407. """
  11408. The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
  11409. will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
  11410. specific page.
  11411. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  11412. popup with `window.open('http://example.com')`, this event will fire when the network request to
  11413. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  11414. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  11415. instead of similar methods on the `Page`.
  11416. ```py
  11417. async with context.expect_page() as page_info:
  11418. await page.get_by_text(\"open new page\").click(),
  11419. page = await page_info.value
  11420. print(await page.evaluate(\"location.href\"))
  11421. ```
  11422. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  11423. need it in most cases)."""
  11424. @typing.overload
  11425. def once(
  11426. self,
  11427. event: Literal["pageclose"],
  11428. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11429. ) -> None:
  11430. """
  11431. Emitted when a page in this context is closed. See also `page.on('close')` to receive events about a specific
  11432. page."""
  11433. @typing.overload
  11434. def once(
  11435. self,
  11436. event: Literal["pageload"],
  11437. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  11438. ) -> None:
  11439. """
  11440. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched
  11441. in any page belonging to this context. See also `page.on('load')` to receive events about a specific page.
  11442. """
  11443. @typing.overload
  11444. def once(
  11445. self,
  11446. event: Literal["weberror"],
  11447. f: typing.Callable[["WebError"], "typing.Union[typing.Awaitable[None], None]"],
  11448. ) -> None:
  11449. """
  11450. Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
  11451. page, use `page.on('page_error')` instead."""
  11452. @typing.overload
  11453. def once(
  11454. self,
  11455. event: Literal["request"],
  11456. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  11457. ) -> None:
  11458. """
  11459. Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
  11460. only listen for requests from a particular page, use `page.on('request')`.
  11461. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
  11462. """
  11463. @typing.overload
  11464. def once(
  11465. self,
  11466. event: Literal["requestfailed"],
  11467. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  11468. ) -> None:
  11469. """
  11470. Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
  11471. use `page.on('request_failed')`.
  11472. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  11473. will complete with `browser_context.on('request_finished')` event and not with
  11474. `browser_context.on('request_failed')`."""
  11475. @typing.overload
  11476. def once(
  11477. self,
  11478. event: Literal["requestfinished"],
  11479. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  11480. ) -> None:
  11481. """
  11482. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  11483. sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
  11484. particular page, use `page.on('request_finished')`."""
  11485. @typing.overload
  11486. def once(
  11487. self,
  11488. event: Literal["response"],
  11489. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  11490. ) -> None:
  11491. """
  11492. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  11493. events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
  11494. `page.on('response')`."""
  11495. @typing.overload
  11496. def once(
  11497. self,
  11498. event: Literal["serviceworker"],
  11499. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  11500. ) -> None:
  11501. """
  11502. **NOTE** Service workers are only supported on Chromium-based browsers.
  11503. Emitted when new service worker is created in the context."""
  11504. def once(
  11505. self,
  11506. event: str,
  11507. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  11508. ) -> None:
  11509. return super().once(event=event, f=f)
  11510. @property
  11511. def pages(self) -> typing.List["Page"]:
  11512. """BrowserContext.pages
  11513. Returns all open pages in the context.
  11514. Returns
  11515. -------
  11516. List[Page]
  11517. """
  11518. return mapping.from_impl_list(self._impl_obj.pages)
  11519. @property
  11520. def browser(self) -> typing.Optional["Browser"]:
  11521. """BrowserContext.browser
  11522. Gets the browser instance that owns the context. Returns `null` if the context is created outside of normal
  11523. browser, e.g. Android or Electron.
  11524. Returns
  11525. -------
  11526. Union[Browser, None]
  11527. """
  11528. return mapping.from_impl_nullable(self._impl_obj.browser)
  11529. @property
  11530. def background_pages(self) -> typing.List["Page"]:
  11531. """BrowserContext.background_pages
  11532. Returns an empty list.
  11533. Returns
  11534. -------
  11535. List[Page]
  11536. """
  11537. return mapping.from_impl_list(self._impl_obj.background_pages)
  11538. @property
  11539. def service_workers(self) -> typing.List["Worker"]:
  11540. """BrowserContext.service_workers
  11541. **NOTE** Service workers are only supported on Chromium-based browsers.
  11542. All existing service workers in the context.
  11543. Returns
  11544. -------
  11545. List[Worker]
  11546. """
  11547. return mapping.from_impl_list(self._impl_obj.service_workers)
  11548. @property
  11549. def tracing(self) -> "Tracing":
  11550. """BrowserContext.tracing
  11551. Returns
  11552. -------
  11553. Tracing
  11554. """
  11555. return mapping.from_impl(self._impl_obj.tracing)
  11556. @property
  11557. def debugger(self) -> "Debugger":
  11558. """BrowserContext.debugger
  11559. Debugger allows to pause and resume the execution.
  11560. Returns
  11561. -------
  11562. Debugger
  11563. """
  11564. return mapping.from_impl(self._impl_obj.debugger)
  11565. @property
  11566. def request(self) -> "APIRequestContext":
  11567. """BrowserContext.request
  11568. API testing helper associated with this context. Requests made with this API will use context cookies.
  11569. Returns
  11570. -------
  11571. APIRequestContext
  11572. """
  11573. return mapping.from_impl(self._impl_obj.request)
  11574. @property
  11575. def clock(self) -> "Clock":
  11576. """BrowserContext.clock
  11577. Playwright has ability to mock clock and passage of time.
  11578. Returns
  11579. -------
  11580. Clock
  11581. """
  11582. return mapping.from_impl(self._impl_obj.clock)
  11583. def set_default_navigation_timeout(
  11584. self, timeout: typing.Union[float, datetime.timedelta]
  11585. ) -> None:
  11586. """BrowserContext.set_default_navigation_timeout
  11587. This setting will change the default maximum navigation time for the following methods and related shortcuts:
  11588. - `page.go_back()`
  11589. - `page.go_forward()`
  11590. - `page.goto()`
  11591. - `page.reload()`
  11592. - `page.set_content()`
  11593. - `page.expect_navigation()`
  11594. **NOTE** `page.set_default_navigation_timeout()` and `page.set_default_timeout()` take priority over
  11595. `browser_context.set_default_navigation_timeout()`.
  11596. Parameters
  11597. ----------
  11598. timeout : float
  11599. Maximum navigation time in milliseconds
  11600. """
  11601. return mapping.from_maybe_impl(
  11602. self._impl_obj.set_default_navigation_timeout(
  11603. timeout=to_milliseconds(timeout)
  11604. )
  11605. )
  11606. def set_default_timeout(
  11607. self, timeout: typing.Union[float, datetime.timedelta]
  11608. ) -> None:
  11609. """BrowserContext.set_default_timeout
  11610. This setting will change the default maximum time for all the methods accepting `timeout` option.
  11611. **NOTE** `page.set_default_navigation_timeout()`, `page.set_default_timeout()` and
  11612. `browser_context.set_default_navigation_timeout()` take priority over
  11613. `browser_context.set_default_timeout()`.
  11614. Parameters
  11615. ----------
  11616. timeout : float
  11617. Maximum time in milliseconds. Pass `0` to disable timeout.
  11618. """
  11619. return mapping.from_maybe_impl(
  11620. self._impl_obj.set_default_timeout(timeout=to_milliseconds(timeout))
  11621. )
  11622. async def new_page(self) -> "Page":
  11623. """BrowserContext.new_page
  11624. Creates a new page in the browser context.
  11625. Returns
  11626. -------
  11627. Page
  11628. """
  11629. return mapping.from_impl(await self._impl_obj.new_page())
  11630. async def cookies(
  11631. self, urls: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None
  11632. ) -> typing.List[Cookie]:
  11633. """BrowserContext.cookies
  11634. If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
  11635. URLs are returned.
  11636. Parameters
  11637. ----------
  11638. urls : Union[Sequence[str], str, None]
  11639. Optional list of URLs.
  11640. Returns
  11641. -------
  11642. List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}]
  11643. """
  11644. return mapping.from_impl_list(
  11645. await self._impl_obj.cookies(urls=mapping.to_impl(urls))
  11646. )
  11647. async def add_cookies(self, cookies: typing.Sequence[SetCookieParam]) -> None:
  11648. """BrowserContext.add_cookies
  11649. Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies
  11650. can be obtained via `browser_context.cookies()`.
  11651. **Usage**
  11652. ```py
  11653. await browser_context.add_cookies([cookie_object1, cookie_object2])
  11654. ```
  11655. Parameters
  11656. ----------
  11657. 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]}]
  11658. """
  11659. return mapping.from_maybe_impl(
  11660. await self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies))
  11661. )
  11662. async def clear_cookies(
  11663. self,
  11664. *,
  11665. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  11666. domain: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  11667. path: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  11668. ) -> None:
  11669. """BrowserContext.clear_cookies
  11670. Removes cookies from context. Accepts optional filter.
  11671. **Usage**
  11672. ```py
  11673. await context.clear_cookies()
  11674. await context.clear_cookies(name=\"session-id\")
  11675. await context.clear_cookies(domain=\"my-origin.com\")
  11676. await context.clear_cookies(path=\"/api/v1\")
  11677. await context.clear_cookies(name=\"session-id\", domain=\"my-origin.com\")
  11678. ```
  11679. Parameters
  11680. ----------
  11681. name : Union[Pattern[str], str, None]
  11682. Only removes cookies with the given name.
  11683. domain : Union[Pattern[str], str, None]
  11684. Only removes cookies with the given domain.
  11685. path : Union[Pattern[str], str, None]
  11686. Only removes cookies with the given path.
  11687. """
  11688. return mapping.from_maybe_impl(
  11689. await self._impl_obj.clear_cookies(name=name, domain=domain, path=path)
  11690. )
  11691. async def grant_permissions(
  11692. self, permissions: typing.Sequence[str], *, origin: typing.Optional[str] = None
  11693. ) -> None:
  11694. """BrowserContext.grant_permissions
  11695. Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
  11696. specified.
  11697. Parameters
  11698. ----------
  11699. permissions : Sequence[str]
  11700. A list of permissions to grant.
  11701. **NOTE** Supported permissions differ between browsers, and even between different versions of the same browser.
  11702. Any permission may stop working after an update.
  11703. Here are some permissions that may be supported by some browsers:
  11704. - `'accelerometer'`
  11705. - `'ambient-light-sensor'`
  11706. - `'background-sync'`
  11707. - `'camera'`
  11708. - `'clipboard-read'`
  11709. - `'clipboard-write'`
  11710. - `'geolocation'`
  11711. - `'gyroscope'`
  11712. - `'local-fonts'`
  11713. - `'local-network-access'`
  11714. - `'magnetometer'`
  11715. - `'microphone'`
  11716. - `'midi-sysex'` (system-exclusive midi)
  11717. - `'midi'`
  11718. - `'notifications'`
  11719. - `'payment-handler'`
  11720. - `'storage-access'`
  11721. - `'screen-wake-lock'`
  11722. origin : Union[str, None]
  11723. The [origin] to grant permissions to, e.g. "https://example.com".
  11724. """
  11725. return mapping.from_maybe_impl(
  11726. await self._impl_obj.grant_permissions(
  11727. permissions=mapping.to_impl(permissions), origin=origin
  11728. )
  11729. )
  11730. async def clear_permissions(self) -> None:
  11731. """BrowserContext.clear_permissions
  11732. Clears all permission overrides for the browser context.
  11733. **Usage**
  11734. ```py
  11735. context = await browser.new_context()
  11736. await context.grant_permissions([\"clipboard-read\"])
  11737. # do stuff ..
  11738. context.clear_permissions()
  11739. ```
  11740. """
  11741. return mapping.from_maybe_impl(await self._impl_obj.clear_permissions())
  11742. async def set_geolocation(
  11743. self, geolocation: typing.Optional[Geolocation] = None
  11744. ) -> None:
  11745. """BrowserContext.set_geolocation
  11746. Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
  11747. **Usage**
  11748. ```py
  11749. await browser_context.set_geolocation({\"latitude\": 59.95, \"longitude\": 30.31667})
  11750. ```
  11751. **NOTE** Consider using `browser_context.grant_permissions()` to grant permissions for the browser context
  11752. pages to read its geolocation.
  11753. Parameters
  11754. ----------
  11755. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  11756. """
  11757. return mapping.from_maybe_impl(
  11758. await self._impl_obj.set_geolocation(geolocation=geolocation)
  11759. )
  11760. async def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
  11761. """BrowserContext.set_extra_http_headers
  11762. The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are
  11763. merged with page-specific extra HTTP headers set with `page.set_extra_http_headers()`. If page overrides a
  11764. particular header, page-specific header value will be used instead of the browser context header value.
  11765. **NOTE** `browser_context.set_extra_http_headers()` does not guarantee the order of headers in the outgoing
  11766. requests.
  11767. Parameters
  11768. ----------
  11769. headers : Dict[str, str]
  11770. An object containing additional HTTP headers to be sent with every request. All header values must be strings.
  11771. """
  11772. return mapping.from_maybe_impl(
  11773. await self._impl_obj.set_extra_http_headers(
  11774. headers=mapping.to_impl(headers)
  11775. )
  11776. )
  11777. async def set_offline(self, offline: bool) -> None:
  11778. """BrowserContext.set_offline
  11779. Parameters
  11780. ----------
  11781. offline : bool
  11782. Whether to emulate network being offline for the browser context.
  11783. """
  11784. return mapping.from_maybe_impl(
  11785. await self._impl_obj.set_offline(offline=offline)
  11786. )
  11787. async def add_init_script(
  11788. self,
  11789. script: typing.Optional[str] = None,
  11790. *,
  11791. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11792. ) -> "AsyncContextManager":
  11793. """BrowserContext.add_init_script
  11794. Adds a script which would be evaluated in one of the following scenarios:
  11795. - Whenever a page is created in the browser context or is navigated.
  11796. - Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is
  11797. evaluated in the context of the newly attached frame.
  11798. The script is evaluated after the document was created but before any of its scripts were run. This is useful to
  11799. amend the JavaScript environment, e.g. to seed `Math.random`.
  11800. **Usage**
  11801. An example of overriding `Math.random` before the page loads:
  11802. ```py
  11803. # in your playwright script, assuming the preload.js file is in same directory.
  11804. await browser_context.add_init_script(path=\"preload.js\")
  11805. ```
  11806. **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
  11807. `page.add_init_script()` is not defined.
  11808. Parameters
  11809. ----------
  11810. script : Union[str, None]
  11811. Script to be evaluated in all pages in the browser context. Optional.
  11812. path : Union[pathlib.Path, str, None]
  11813. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  11814. directory. Optional.
  11815. Returns
  11816. -------
  11817. AsyncContextManager
  11818. """
  11819. return mapping.from_impl(
  11820. await self._impl_obj.add_init_script(script=script, path=path)
  11821. )
  11822. async def expose_binding(
  11823. self, name: str, callback: typing.Callable
  11824. ) -> "AsyncContextManager":
  11825. """BrowserContext.expose_binding
  11826. The method adds a function called `name` on the `window` object of every frame in every page in the context. When
  11827. called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  11828. If the `callback` returns a [Promise], it will be awaited.
  11829. The first argument of the `callback` function contains information about the caller: `{ browserContext:
  11830. BrowserContext, page: Page, frame: Frame }`.
  11831. See `page.expose_binding()` for page-only version.
  11832. **Usage**
  11833. An example of exposing page URL to all frames in all pages in the context:
  11834. ```py
  11835. import asyncio
  11836. from playwright.async_api import async_playwright, Playwright
  11837. async def run(playwright: Playwright):
  11838. webkit = playwright.webkit
  11839. browser = await webkit.launch(headless=False)
  11840. context = await browser.new_context()
  11841. await context.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
  11842. page = await context.new_page()
  11843. await page.set_content(\"\"\"
  11844. <script>
  11845. async function onClick() {
  11846. document.querySelector('div').textContent = await window.pageURL();
  11847. }
  11848. </script>
  11849. <button onclick=\"onClick()\">Click me</button>
  11850. <div></div>
  11851. \"\"\")
  11852. await page.get_by_role(\"button\").click()
  11853. async def main():
  11854. async with async_playwright() as playwright:
  11855. await run(playwright)
  11856. asyncio.run(main())
  11857. ```
  11858. Parameters
  11859. ----------
  11860. name : str
  11861. Name of the function on the window object.
  11862. callback : Callable
  11863. Callback function that will be called in the Playwright's context.
  11864. Returns
  11865. -------
  11866. AsyncContextManager
  11867. """
  11868. return mapping.from_impl(
  11869. await self._impl_obj.expose_binding(
  11870. name=name, callback=self._wrap_handler(callback)
  11871. )
  11872. )
  11873. async def expose_function(
  11874. self, name: str, callback: typing.Callable
  11875. ) -> "AsyncContextManager":
  11876. """BrowserContext.expose_function
  11877. The method adds a function called `name` on the `window` object of every frame in every page in the context. When
  11878. called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  11879. If the `callback` returns a [Promise], it will be awaited.
  11880. See `page.expose_function()` for page-only version.
  11881. **Usage**
  11882. An example of adding a `sha256` function to all pages in the context:
  11883. ```py
  11884. import asyncio
  11885. import hashlib
  11886. from playwright.async_api import async_playwright, Playwright
  11887. def sha256(text: str) -> str:
  11888. m = hashlib.sha256()
  11889. m.update(bytes(text, \"utf8\"))
  11890. return m.hexdigest()
  11891. async def run(playwright: Playwright):
  11892. webkit = playwright.webkit
  11893. browser = await webkit.launch(headless=False)
  11894. context = await browser.new_context()
  11895. await context.expose_function(\"sha256\", sha256)
  11896. page = await context.new_page()
  11897. await page.set_content(\"\"\"
  11898. <script>
  11899. async function onClick() {
  11900. document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  11901. }
  11902. </script>
  11903. <button onclick=\"onClick()\">Click me</button>
  11904. <div></div>
  11905. \"\"\")
  11906. await page.get_by_role(\"button\").click()
  11907. async def main():
  11908. async with async_playwright() as playwright:
  11909. await run(playwright)
  11910. asyncio.run(main())
  11911. ```
  11912. Parameters
  11913. ----------
  11914. name : str
  11915. Name of the function on the window object.
  11916. callback : Callable
  11917. Callback function that will be called in the Playwright's context.
  11918. Returns
  11919. -------
  11920. AsyncContextManager
  11921. """
  11922. return mapping.from_impl(
  11923. await self._impl_obj.expose_function(
  11924. name=name, callback=self._wrap_handler(callback)
  11925. )
  11926. )
  11927. async def route(
  11928. self,
  11929. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  11930. handler: typing.Union[
  11931. typing.Callable[["Route"], typing.Any],
  11932. typing.Callable[["Route", "Request"], typing.Any],
  11933. ],
  11934. *,
  11935. times: typing.Optional[int] = None,
  11936. ) -> "AsyncContextManager":
  11937. """BrowserContext.route
  11938. Routing provides the capability to modify network requests that are made by any page in the browser context. Once
  11939. route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
  11940. **NOTE** `browser_context.route()` will not intercept requests intercepted by Service Worker. See
  11941. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  11942. using request interception by setting `serviceWorkers` to `'block'`.
  11943. **Usage**
  11944. An example of a naive handler that aborts all image requests:
  11945. ```py
  11946. context = await browser.new_context()
  11947. page = await context.new_page()
  11948. await context.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
  11949. await page.goto(\"https://example.com\")
  11950. await browser.close()
  11951. ```
  11952. or the same snippet using a regex pattern instead:
  11953. ```py
  11954. context = await browser.new_context()
  11955. page = await context.new_page()
  11956. await context.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
  11957. page = await context.new_page()
  11958. await page.goto(\"https://example.com\")
  11959. await browser.close()
  11960. ```
  11961. It is possible to examine the request to decide the route action. For example, mocking all requests that contain
  11962. some post data, and leaving all other requests as is:
  11963. ```py
  11964. async def handle_route(route: Route):
  11965. if (\"my-string\" in route.request.post_data):
  11966. await route.fulfill(body=\"mocked-data\")
  11967. else:
  11968. await route.continue_()
  11969. await context.route(\"/api/**\", handle_route)
  11970. ```
  11971. Page routes (set up with `page.route()`) take precedence over browser context routes when request matches
  11972. both handlers.
  11973. To remove a route with its handler you can use `browser_context.unroute()`.
  11974. **NOTE** Enabling routing disables http cache.
  11975. Parameters
  11976. ----------
  11977. url : Union[Callable[[str], bool], Pattern[str], str]
  11978. A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
  11979. the context options and the provided URL is a string that does not start with `*`, it is resolved using the
  11980. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  11981. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
  11982. handler function to route the request.
  11983. times : Union[int, None]
  11984. How often a route should be used. By default it will be used every time.
  11985. Returns
  11986. -------
  11987. AsyncContextManager
  11988. """
  11989. return mapping.from_impl(
  11990. await self._impl_obj.route(
  11991. url=self._wrap_handler(url),
  11992. handler=self._wrap_handler(handler),
  11993. times=times,
  11994. )
  11995. )
  11996. async def unroute(
  11997. self,
  11998. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  11999. handler: typing.Optional[
  12000. typing.Union[
  12001. typing.Callable[["Route"], typing.Any],
  12002. typing.Callable[["Route", "Request"], typing.Any],
  12003. ]
  12004. ] = None,
  12005. ) -> None:
  12006. """BrowserContext.unroute
  12007. Removes a route created with `browser_context.route()`. When `handler` is not specified, removes all routes
  12008. for the `url`.
  12009. Parameters
  12010. ----------
  12011. url : Union[Callable[[str], bool], Pattern[str], str]
  12012. A glob pattern, regex pattern, or predicate receiving [URL] used to register a routing with
  12013. `browser_context.route()`.
  12014. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
  12015. Optional handler function used to register a routing with `browser_context.route()`.
  12016. """
  12017. return mapping.from_maybe_impl(
  12018. await self._impl_obj.unroute(
  12019. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  12020. )
  12021. )
  12022. async def route_web_socket(
  12023. self,
  12024. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  12025. handler: typing.Callable[["WebSocketRoute"], typing.Any],
  12026. ) -> None:
  12027. """BrowserContext.route_web_socket
  12028. This method allows to modify websocket connections that are made by any page in the browser context.
  12029. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
  12030. method before creating any pages.
  12031. **Usage**
  12032. Below is an example of a simple handler that blocks some websocket messages. See `WebSocketRoute` for more details
  12033. and examples.
  12034. ```py
  12035. def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  12036. if message == \"to-be-blocked\":
  12037. return
  12038. ws.send(message)
  12039. async def handler(ws: WebSocketRoute):
  12040. ws.route_send(lambda message: message_handler(ws, message))
  12041. await ws.connect()
  12042. await context.route_web_socket(\"/ws\", handler)
  12043. ```
  12044. Parameters
  12045. ----------
  12046. url : Union[Callable[[str], bool], Pattern[str], str]
  12047. Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
  12048. `baseURL` context option.
  12049. handler : Callable[[WebSocketRoute], Any]
  12050. Handler function to route the WebSocket.
  12051. """
  12052. return mapping.from_maybe_impl(
  12053. await self._impl_obj.route_web_socket(
  12054. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  12055. )
  12056. )
  12057. async def unroute_all(
  12058. self,
  12059. *,
  12060. behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
  12061. ) -> None:
  12062. """BrowserContext.unroute_all
  12063. Removes all routes created with `browser_context.route()` and `browser_context.route_from_har()`.
  12064. Parameters
  12065. ----------
  12066. behavior : Union["default", "ignoreErrors", "wait", None]
  12067. Specifies whether to wait for already running handlers and what to do if they throw errors:
  12068. - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
  12069. result in unhandled error
  12070. - `'wait'` - wait for current handler calls (if any) to finish
  12071. - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
  12072. after unrouting are silently caught
  12073. """
  12074. return mapping.from_maybe_impl(
  12075. await self._impl_obj.unroute_all(behavior=behavior)
  12076. )
  12077. async def route_from_har(
  12078. self,
  12079. har: typing.Union[pathlib.Path, str],
  12080. *,
  12081. url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  12082. not_found: typing.Optional[Literal["abort", "fallback"]] = None,
  12083. update: typing.Optional[bool] = None,
  12084. update_content: typing.Optional[Literal["attach", "embed"]] = None,
  12085. update_mode: typing.Optional[Literal["full", "minimal"]] = None,
  12086. ) -> None:
  12087. """BrowserContext.route_from_har
  12088. If specified the network requests that are made in the context will be served from the HAR file. Read more about
  12089. [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
  12090. Playwright will not serve requests intercepted by Service Worker from the HAR file. See
  12091. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  12092. using request interception by setting `serviceWorkers` to `'block'`.
  12093. Parameters
  12094. ----------
  12095. har : Union[pathlib.Path, str]
  12096. Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
  12097. relative path, then it is resolved relative to the current working directory.
  12098. url : Union[Pattern[str], str, None]
  12099. A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
  12100. pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
  12101. not_found : Union["abort", "fallback", None]
  12102. - If set to 'abort' any request not found in the HAR file will be aborted.
  12103. - If set to 'fallback' falls through to the next route handler in the handler chain.
  12104. Defaults to abort.
  12105. update : Union[bool, None]
  12106. If specified, updates the given HAR with the actual network information instead of serving from file. The file is
  12107. written to disk when `browser_context.close()` is called.
  12108. update_content : Union["attach", "embed", None]
  12109. Optional setting to control resource content management. If `attach` is specified, resources are persisted as
  12110. separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
  12111. update_mode : Union["full", "minimal", None]
  12112. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  12113. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
  12114. `minimal`.
  12115. """
  12116. return mapping.from_maybe_impl(
  12117. await self._impl_obj.route_from_har(
  12118. har=har,
  12119. url=url,
  12120. notFound=not_found,
  12121. update=update,
  12122. updateContent=update_content,
  12123. updateMode=update_mode,
  12124. )
  12125. )
  12126. @typing.overload
  12127. def expect_event(
  12128. self,
  12129. event: typing.Literal["backgroundpage"],
  12130. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12131. *,
  12132. timeout: typing.Optional[float] = None,
  12133. ) -> AsyncEventContextManager["Page"]: ...
  12134. @typing.overload
  12135. def expect_event(
  12136. self,
  12137. event: typing.Literal["close"],
  12138. predicate: typing.Optional[typing.Callable[["BrowserContext"], bool]] = None,
  12139. *,
  12140. timeout: typing.Optional[float] = None,
  12141. ) -> AsyncEventContextManager["BrowserContext"]: ...
  12142. @typing.overload
  12143. def expect_event(
  12144. self,
  12145. event: typing.Literal["console"],
  12146. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  12147. *,
  12148. timeout: typing.Optional[float] = None,
  12149. ) -> AsyncEventContextManager["ConsoleMessage"]: ...
  12150. @typing.overload
  12151. def expect_event(
  12152. self,
  12153. event: typing.Literal["dialog"],
  12154. predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None,
  12155. *,
  12156. timeout: typing.Optional[float] = None,
  12157. ) -> AsyncEventContextManager["Dialog"]: ...
  12158. @typing.overload
  12159. def expect_event(
  12160. self,
  12161. event: typing.Literal["download"],
  12162. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  12163. *,
  12164. timeout: typing.Optional[float] = None,
  12165. ) -> AsyncEventContextManager["Download"]: ...
  12166. @typing.overload
  12167. def expect_event(
  12168. self,
  12169. event: typing.Literal["frameattached"],
  12170. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  12171. *,
  12172. timeout: typing.Optional[float] = None,
  12173. ) -> AsyncEventContextManager["Frame"]: ...
  12174. @typing.overload
  12175. def expect_event(
  12176. self,
  12177. event: typing.Literal["framedetached"],
  12178. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  12179. *,
  12180. timeout: typing.Optional[float] = None,
  12181. ) -> AsyncEventContextManager["Frame"]: ...
  12182. @typing.overload
  12183. def expect_event(
  12184. self,
  12185. event: typing.Literal["framenavigated"],
  12186. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  12187. *,
  12188. timeout: typing.Optional[float] = None,
  12189. ) -> AsyncEventContextManager["Frame"]: ...
  12190. @typing.overload
  12191. def expect_event(
  12192. self,
  12193. event: typing.Literal["page"],
  12194. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12195. *,
  12196. timeout: typing.Optional[float] = None,
  12197. ) -> AsyncEventContextManager["Page"]: ...
  12198. @typing.overload
  12199. def expect_event(
  12200. self,
  12201. event: typing.Literal["pageclose"],
  12202. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12203. *,
  12204. timeout: typing.Optional[float] = None,
  12205. ) -> AsyncEventContextManager["Page"]: ...
  12206. @typing.overload
  12207. def expect_event(
  12208. self,
  12209. event: typing.Literal["pageload"],
  12210. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12211. *,
  12212. timeout: typing.Optional[float] = None,
  12213. ) -> AsyncEventContextManager["Page"]: ...
  12214. @typing.overload
  12215. def expect_event(
  12216. self,
  12217. event: typing.Literal["weberror"],
  12218. predicate: typing.Optional[typing.Callable[["WebError"], bool]] = None,
  12219. *,
  12220. timeout: typing.Optional[float] = None,
  12221. ) -> AsyncEventContextManager["WebError"]: ...
  12222. @typing.overload
  12223. def expect_event(
  12224. self,
  12225. event: typing.Literal["request"],
  12226. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  12227. *,
  12228. timeout: typing.Optional[float] = None,
  12229. ) -> AsyncEventContextManager["Request"]: ...
  12230. @typing.overload
  12231. def expect_event(
  12232. self,
  12233. event: typing.Literal["requestfailed"],
  12234. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  12235. *,
  12236. timeout: typing.Optional[float] = None,
  12237. ) -> AsyncEventContextManager["Request"]: ...
  12238. @typing.overload
  12239. def expect_event(
  12240. self,
  12241. event: typing.Literal["requestfinished"],
  12242. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  12243. *,
  12244. timeout: typing.Optional[float] = None,
  12245. ) -> AsyncEventContextManager["Request"]: ...
  12246. @typing.overload
  12247. def expect_event(
  12248. self,
  12249. event: typing.Literal["response"],
  12250. predicate: typing.Optional[typing.Callable[["Response"], bool]] = None,
  12251. *,
  12252. timeout: typing.Optional[float] = None,
  12253. ) -> AsyncEventContextManager["Response"]: ...
  12254. @typing.overload
  12255. def expect_event(
  12256. self,
  12257. event: typing.Literal["serviceworker"],
  12258. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  12259. *,
  12260. timeout: typing.Optional[float] = None,
  12261. ) -> AsyncEventContextManager["Worker"]: ...
  12262. @typing.overload
  12263. def expect_event(
  12264. self,
  12265. event: str,
  12266. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  12267. *,
  12268. timeout: typing.Optional[float] = None,
  12269. ) -> AsyncEventContextManager[typing.Any]: ...
  12270. def expect_event(
  12271. self,
  12272. event: str,
  12273. predicate: typing.Optional[typing.Callable] = None,
  12274. *,
  12275. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  12276. ) -> AsyncEventContextManager:
  12277. """BrowserContext.expect_event
  12278. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  12279. value. Will throw an error if the context closes before the event is fired. Returns the event data value.
  12280. **Usage**
  12281. ```py
  12282. async with context.expect_event(\"page\") as event_info:
  12283. await page.get_by_role(\"button\").click()
  12284. page = await event_info.value
  12285. ```
  12286. Parameters
  12287. ----------
  12288. event : str
  12289. Event name, same one would pass into `browserContext.on(event)`.
  12290. predicate : Union[Callable, None]
  12291. Receives the event data and resolves to truthy value when the waiting should resolve.
  12292. timeout : Union[float, None]
  12293. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  12294. default value can be changed by using the `browser_context.set_default_timeout()`.
  12295. Returns
  12296. -------
  12297. EventContextManager
  12298. """
  12299. return AsyncEventContextManager(
  12300. self._impl_obj.expect_event(
  12301. event=event,
  12302. predicate=self._wrap_handler(predicate),
  12303. timeout=to_milliseconds(timeout),
  12304. ).future
  12305. )
  12306. def is_closed(self) -> bool:
  12307. """BrowserContext.is_closed
  12308. Indicates that the browser context is in the process of closing or has already been closed.
  12309. Returns
  12310. -------
  12311. bool
  12312. """
  12313. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  12314. async def close(self, *, reason: typing.Optional[str] = None) -> None:
  12315. """BrowserContext.close
  12316. Closes the browser context. All the pages that belong to the browser context will be closed.
  12317. **NOTE** The default browser context cannot be closed.
  12318. Parameters
  12319. ----------
  12320. reason : Union[str, None]
  12321. The reason to be reported to the operations interrupted by the context closure.
  12322. """
  12323. return mapping.from_maybe_impl(await self._impl_obj.close(reason=reason))
  12324. async def storage_state(
  12325. self,
  12326. *,
  12327. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12328. indexed_db: typing.Optional[bool] = None,
  12329. ) -> StorageState:
  12330. """BrowserContext.storage_state
  12331. Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB
  12332. snapshot.
  12333. Parameters
  12334. ----------
  12335. path : Union[pathlib.Path, str, None]
  12336. The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
  12337. working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
  12338. indexed_db : Union[bool, None]
  12339. Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage
  12340. state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication,
  12341. enable this.
  12342. Returns
  12343. -------
  12344. {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}]}]}
  12345. """
  12346. return mapping.from_impl(
  12347. await self._impl_obj.storage_state(path=path, indexedDB=indexed_db)
  12348. )
  12349. async def set_storage_state(
  12350. self, storage_state: typing.Union[StorageState, str, pathlib.Path]
  12351. ) -> None:
  12352. """BrowserContext.set_storage_state
  12353. Clears the existing cookies, local storage and IndexedDB entries for all origins and sets the new storage state.
  12354. **Usage**
  12355. ```py
  12356. # Load storage state from a file and apply it to the context.
  12357. await context.set_storage_state(\"state.json\")
  12358. ```
  12359. Parameters
  12360. ----------
  12361. 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}]}]}]
  12362. Learn more about [storage state and auth](../auth.md).
  12363. Populates context with given storage state. This option can be used to initialize context with logged-in
  12364. information obtained via `browser_context.storage_state()`.
  12365. """
  12366. return mapping.from_maybe_impl(
  12367. await self._impl_obj.set_storage_state(storageState=storage_state)
  12368. )
  12369. @typing.overload
  12370. async def wait_for_event(
  12371. self,
  12372. event: typing.Literal["backgroundpage"],
  12373. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12374. *,
  12375. timeout: typing.Optional[float] = None,
  12376. ) -> "Page": ...
  12377. @typing.overload
  12378. async def wait_for_event(
  12379. self,
  12380. event: typing.Literal["close"],
  12381. predicate: typing.Optional[typing.Callable[["BrowserContext"], bool]] = None,
  12382. *,
  12383. timeout: typing.Optional[float] = None,
  12384. ) -> "BrowserContext": ...
  12385. @typing.overload
  12386. async def wait_for_event(
  12387. self,
  12388. event: typing.Literal["console"],
  12389. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  12390. *,
  12391. timeout: typing.Optional[float] = None,
  12392. ) -> "ConsoleMessage": ...
  12393. @typing.overload
  12394. async def wait_for_event(
  12395. self,
  12396. event: typing.Literal["dialog"],
  12397. predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None,
  12398. *,
  12399. timeout: typing.Optional[float] = None,
  12400. ) -> "Dialog": ...
  12401. @typing.overload
  12402. async def wait_for_event(
  12403. self,
  12404. event: typing.Literal["download"],
  12405. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  12406. *,
  12407. timeout: typing.Optional[float] = None,
  12408. ) -> "Download": ...
  12409. @typing.overload
  12410. async def wait_for_event(
  12411. self,
  12412. event: typing.Literal["frameattached"],
  12413. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  12414. *,
  12415. timeout: typing.Optional[float] = None,
  12416. ) -> "Frame": ...
  12417. @typing.overload
  12418. async def wait_for_event(
  12419. self,
  12420. event: typing.Literal["framedetached"],
  12421. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  12422. *,
  12423. timeout: typing.Optional[float] = None,
  12424. ) -> "Frame": ...
  12425. @typing.overload
  12426. async def wait_for_event(
  12427. self,
  12428. event: typing.Literal["framenavigated"],
  12429. predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None,
  12430. *,
  12431. timeout: typing.Optional[float] = None,
  12432. ) -> "Frame": ...
  12433. @typing.overload
  12434. async def wait_for_event(
  12435. self,
  12436. event: typing.Literal["page"],
  12437. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12438. *,
  12439. timeout: typing.Optional[float] = None,
  12440. ) -> "Page": ...
  12441. @typing.overload
  12442. async def wait_for_event(
  12443. self,
  12444. event: typing.Literal["pageclose"],
  12445. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12446. *,
  12447. timeout: typing.Optional[float] = None,
  12448. ) -> "Page": ...
  12449. @typing.overload
  12450. async def wait_for_event(
  12451. self,
  12452. event: typing.Literal["pageload"],
  12453. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12454. *,
  12455. timeout: typing.Optional[float] = None,
  12456. ) -> "Page": ...
  12457. @typing.overload
  12458. async def wait_for_event(
  12459. self,
  12460. event: typing.Literal["weberror"],
  12461. predicate: typing.Optional[typing.Callable[["WebError"], bool]] = None,
  12462. *,
  12463. timeout: typing.Optional[float] = None,
  12464. ) -> "WebError": ...
  12465. @typing.overload
  12466. async def wait_for_event(
  12467. self,
  12468. event: typing.Literal["request"],
  12469. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  12470. *,
  12471. timeout: typing.Optional[float] = None,
  12472. ) -> "Request": ...
  12473. @typing.overload
  12474. async def wait_for_event(
  12475. self,
  12476. event: typing.Literal["requestfailed"],
  12477. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  12478. *,
  12479. timeout: typing.Optional[float] = None,
  12480. ) -> "Request": ...
  12481. @typing.overload
  12482. async def wait_for_event(
  12483. self,
  12484. event: typing.Literal["requestfinished"],
  12485. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  12486. *,
  12487. timeout: typing.Optional[float] = None,
  12488. ) -> "Request": ...
  12489. @typing.overload
  12490. async def wait_for_event(
  12491. self,
  12492. event: typing.Literal["response"],
  12493. predicate: typing.Optional[typing.Callable[["Response"], bool]] = None,
  12494. *,
  12495. timeout: typing.Optional[float] = None,
  12496. ) -> "Response": ...
  12497. @typing.overload
  12498. async def wait_for_event(
  12499. self,
  12500. event: typing.Literal["serviceworker"],
  12501. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  12502. *,
  12503. timeout: typing.Optional[float] = None,
  12504. ) -> "Worker": ...
  12505. @typing.overload
  12506. async def wait_for_event(
  12507. self,
  12508. event: str,
  12509. predicate: typing.Optional[typing.Callable[..., bool]] = None,
  12510. *,
  12511. timeout: typing.Optional[float] = None,
  12512. ) -> typing.Any: ...
  12513. async def wait_for_event(
  12514. self,
  12515. event: str,
  12516. predicate: typing.Optional[typing.Callable] = None,
  12517. *,
  12518. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  12519. ) -> typing.Any:
  12520. """BrowserContext.wait_for_event
  12521. **NOTE** In most cases, you should use `browser_context.expect_event()`.
  12522. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  12523. and waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed
  12524. before the `event` is fired.
  12525. Parameters
  12526. ----------
  12527. event : str
  12528. Event name, same one typically passed into `*.on(event)`.
  12529. predicate : Union[Callable, None]
  12530. Receives the event data and resolves to truthy value when the waiting should resolve.
  12531. timeout : Union[float, None]
  12532. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  12533. default value can be changed by using the `browser_context.set_default_timeout()`.
  12534. Returns
  12535. -------
  12536. Any
  12537. """
  12538. return mapping.from_maybe_impl(
  12539. await self._impl_obj.wait_for_event(
  12540. event=event,
  12541. predicate=self._wrap_handler(predicate),
  12542. timeout=to_milliseconds(timeout),
  12543. )
  12544. )
  12545. def expect_console_message(
  12546. self,
  12547. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  12548. *,
  12549. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  12550. ) -> AsyncEventContextManager["ConsoleMessage"]:
  12551. """BrowserContext.expect_console_message
  12552. Performs action and waits for a `ConsoleMessage` to be logged by in the pages in the context. If predicate is
  12553. provided, it passes `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to
  12554. return a truthy value. Will throw an error if the page is closed before the `browser_context.on('console')` event
  12555. is fired.
  12556. Parameters
  12557. ----------
  12558. predicate : Union[Callable[[ConsoleMessage], bool], None]
  12559. Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
  12560. timeout : Union[float, None]
  12561. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  12562. default value can be changed by using the `browser_context.set_default_timeout()`.
  12563. Returns
  12564. -------
  12565. EventContextManager[ConsoleMessage]
  12566. """
  12567. return AsyncEventContextManager(
  12568. self._impl_obj.expect_console_message(
  12569. predicate=self._wrap_handler(predicate),
  12570. timeout=to_milliseconds(timeout),
  12571. ).future
  12572. )
  12573. def expect_page(
  12574. self,
  12575. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  12576. *,
  12577. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  12578. ) -> AsyncEventContextManager["Page"]:
  12579. """BrowserContext.expect_page
  12580. Performs action and waits for a new `Page` to be created in the context. If predicate is provided, it passes `Page`
  12581. value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error
  12582. if the context closes before new `Page` is created.
  12583. Parameters
  12584. ----------
  12585. predicate : Union[Callable[[Page], bool], None]
  12586. Receives the `Page` object and resolves to truthy value when the waiting should resolve.
  12587. timeout : Union[float, None]
  12588. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  12589. default value can be changed by using the `browser_context.set_default_timeout()`.
  12590. Returns
  12591. -------
  12592. EventContextManager[Page]
  12593. """
  12594. return AsyncEventContextManager(
  12595. self._impl_obj.expect_page(
  12596. predicate=self._wrap_handler(predicate),
  12597. timeout=to_milliseconds(timeout),
  12598. ).future
  12599. )
  12600. async def new_cdp_session(
  12601. self, page: typing.Union["Page", "Frame"]
  12602. ) -> "CDPSession":
  12603. """BrowserContext.new_cdp_session
  12604. **NOTE** CDP sessions are only supported on Chromium-based browsers.
  12605. Returns the newly created session.
  12606. Parameters
  12607. ----------
  12608. page : Union[Frame, Page]
  12609. Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a
  12610. `Page` or `Frame` type.
  12611. Returns
  12612. -------
  12613. CDPSession
  12614. """
  12615. return mapping.from_impl(await self._impl_obj.new_cdp_session(page=page))
  12616. mapping.register(BrowserContextImpl, BrowserContext)
  12617. class CDPSession(AsyncBase):
  12618. @typing.overload
  12619. def on(
  12620. self,
  12621. event: Literal["close"],
  12622. f: typing.Callable[
  12623. ["CDPSession"], "typing.Union[typing.Awaitable[None], None]"
  12624. ],
  12625. ) -> None:
  12626. """
  12627. Emitted when the session is closed, either because the target was closed or `session.detach()` was called.
  12628. """
  12629. @typing.overload
  12630. def on(
  12631. self,
  12632. event: str,
  12633. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  12634. ) -> None: ...
  12635. def on(
  12636. self,
  12637. event: str,
  12638. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  12639. ) -> None:
  12640. return super().on(event=event, f=f)
  12641. @typing.overload
  12642. def once(
  12643. self,
  12644. event: Literal["close"],
  12645. f: typing.Callable[
  12646. ["CDPSession"], "typing.Union[typing.Awaitable[None], None]"
  12647. ],
  12648. ) -> None:
  12649. """
  12650. Emitted when the session is closed, either because the target was closed or `session.detach()` was called.
  12651. """
  12652. @typing.overload
  12653. def once(
  12654. self,
  12655. event: str,
  12656. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  12657. ) -> None: ...
  12658. def once(
  12659. self,
  12660. event: str,
  12661. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  12662. ) -> None:
  12663. return super().once(event=event, f=f)
  12664. async def send(
  12665. self, method: str, params: typing.Optional[typing.Dict] = None
  12666. ) -> typing.Dict:
  12667. """CDPSession.send
  12668. Parameters
  12669. ----------
  12670. method : str
  12671. Protocol method name.
  12672. params : Union[Dict, None]
  12673. Optional method parameters.
  12674. Returns
  12675. -------
  12676. Dict
  12677. """
  12678. return mapping.from_maybe_impl(
  12679. await self._impl_obj.send(method=method, params=mapping.to_impl(params))
  12680. )
  12681. async def detach(self) -> None:
  12682. """CDPSession.detach
  12683. Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
  12684. used to send messages.
  12685. """
  12686. return mapping.from_maybe_impl(await self._impl_obj.detach())
  12687. mapping.register(CDPSessionImpl, CDPSession)
  12688. class Browser(AsyncContextManager):
  12689. @typing.overload
  12690. def on(
  12691. self,
  12692. event: Literal["context"],
  12693. f: typing.Callable[
  12694. ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]"
  12695. ],
  12696. ) -> None:
  12697. """
  12698. Emitted when a new browser context is created."""
  12699. @typing.overload
  12700. def on(
  12701. self,
  12702. event: Literal["disconnected"],
  12703. f: typing.Callable[["Browser"], "typing.Union[typing.Awaitable[None], None]"],
  12704. ) -> None:
  12705. """
  12706. Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
  12707. following:
  12708. - Browser application is closed or crashed.
  12709. - The `browser.close()` method was called."""
  12710. def on(
  12711. self,
  12712. event: str,
  12713. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  12714. ) -> None:
  12715. return super().on(event=event, f=f)
  12716. @typing.overload
  12717. def once(
  12718. self,
  12719. event: Literal["context"],
  12720. f: typing.Callable[
  12721. ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]"
  12722. ],
  12723. ) -> None:
  12724. """
  12725. Emitted when a new browser context is created."""
  12726. @typing.overload
  12727. def once(
  12728. self,
  12729. event: Literal["disconnected"],
  12730. f: typing.Callable[["Browser"], "typing.Union[typing.Awaitable[None], None]"],
  12731. ) -> None:
  12732. """
  12733. Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
  12734. following:
  12735. - Browser application is closed or crashed.
  12736. - The `browser.close()` method was called."""
  12737. def once(
  12738. self,
  12739. event: str,
  12740. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  12741. ) -> None:
  12742. return super().once(event=event, f=f)
  12743. @property
  12744. def contexts(self) -> typing.List["BrowserContext"]:
  12745. """Browser.contexts
  12746. Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
  12747. **Usage**
  12748. ```py
  12749. browser = await pw.webkit.launch()
  12750. print(len(browser.contexts)) # prints `0`
  12751. context = await browser.new_context()
  12752. print(len(browser.contexts)) # prints `1`
  12753. ```
  12754. Returns
  12755. -------
  12756. List[BrowserContext]
  12757. """
  12758. return mapping.from_impl_list(self._impl_obj.contexts)
  12759. @property
  12760. def browser_type(self) -> "BrowserType":
  12761. """Browser.browser_type
  12762. Get the browser type (chromium, firefox or webkit) that the browser belongs to.
  12763. Returns
  12764. -------
  12765. BrowserType
  12766. """
  12767. return mapping.from_impl(self._impl_obj.browser_type)
  12768. @property
  12769. def version(self) -> str:
  12770. """Browser.version
  12771. Returns the browser version.
  12772. Returns
  12773. -------
  12774. str
  12775. """
  12776. return mapping.from_maybe_impl(self._impl_obj.version)
  12777. def is_connected(self) -> bool:
  12778. """Browser.is_connected
  12779. Indicates that the browser is connected.
  12780. Returns
  12781. -------
  12782. bool
  12783. """
  12784. return mapping.from_maybe_impl(self._impl_obj.is_connected())
  12785. async def new_context(
  12786. self,
  12787. *,
  12788. viewport: typing.Optional[ViewportSize] = None,
  12789. screen: typing.Optional[ViewportSize] = None,
  12790. no_viewport: typing.Optional[bool] = None,
  12791. ignore_https_errors: typing.Optional[bool] = None,
  12792. java_script_enabled: typing.Optional[bool] = None,
  12793. bypass_csp: typing.Optional[bool] = None,
  12794. user_agent: typing.Optional[str] = None,
  12795. locale: typing.Optional[str] = None,
  12796. timezone_id: typing.Optional[str] = None,
  12797. geolocation: typing.Optional[Geolocation] = None,
  12798. permissions: typing.Optional[typing.Sequence[str]] = None,
  12799. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  12800. offline: typing.Optional[bool] = None,
  12801. http_credentials: typing.Optional[HttpCredentials] = None,
  12802. device_scale_factor: typing.Optional[float] = None,
  12803. is_mobile: typing.Optional[bool] = None,
  12804. has_touch: typing.Optional[bool] = None,
  12805. color_scheme: typing.Optional[
  12806. Literal["dark", "light", "no-preference", "null"]
  12807. ] = None,
  12808. reduced_motion: typing.Optional[
  12809. Literal["no-preference", "null", "reduce"]
  12810. ] = None,
  12811. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  12812. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  12813. accept_downloads: typing.Optional[bool] = None,
  12814. default_browser_type: typing.Optional[str] = None,
  12815. proxy: typing.Optional[ProxySettings] = None,
  12816. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12817. record_har_omit_content: typing.Optional[bool] = None,
  12818. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12819. record_video_size: typing.Optional[ViewportSize] = None,
  12820. storage_state: typing.Optional[
  12821. typing.Union[StorageState, str, pathlib.Path]
  12822. ] = None,
  12823. base_url: typing.Optional[str] = None,
  12824. strict_selectors: typing.Optional[bool] = None,
  12825. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  12826. record_har_url_filter: typing.Optional[
  12827. typing.Union[typing.Pattern[str], str]
  12828. ] = None,
  12829. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  12830. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  12831. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  12832. ) -> "BrowserContext":
  12833. """Browser.new_context
  12834. Creates a new browser context. It won't share cookies/cache with other browser contexts.
  12835. **NOTE** If directly using this method to create `BrowserContext`s, it is best practice to explicitly close the
  12836. returned context via `browser_context.close()` when your code is done with the `BrowserContext`, and before
  12837. calling `browser.close()`. This will ensure the `context` is closed gracefully and any artifacts—like HARs
  12838. and videos—are fully flushed and saved.
  12839. **Usage**
  12840. ```py
  12841. browser = await playwright.firefox.launch() # or \"chromium\" or \"webkit\".
  12842. # create a new incognito browser context.
  12843. context = await browser.new_context()
  12844. # create a new page in a pristine context.
  12845. page = await context.new_page()
  12846. await page.goto(\"https://example.com\")
  12847. # gracefully close up everything
  12848. await context.close()
  12849. await browser.close()
  12850. ```
  12851. Parameters
  12852. ----------
  12853. viewport : Union[{width: int, height: int}, None]
  12854. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  12855. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  12856. screen : Union[{width: int, height: int}, None]
  12857. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  12858. `viewport` is set.
  12859. no_viewport : Union[bool, None]
  12860. Does not enforce fixed viewport, allows resizing window in the headed mode.
  12861. ignore_https_errors : Union[bool, None]
  12862. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  12863. java_script_enabled : Union[bool, None]
  12864. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  12865. [disabling JavaScript](../emulation.md#javascript-enabled).
  12866. bypass_csp : Union[bool, None]
  12867. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  12868. user_agent : Union[str, None]
  12869. Specific user agent to use in this context.
  12870. locale : Union[str, None]
  12871. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  12872. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  12873. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  12874. timezone_id : Union[str, None]
  12875. Changes the timezone of the context. See
  12876. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  12877. for a list of supported timezone IDs. Defaults to the system timezone.
  12878. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  12879. permissions : Union[Sequence[str], None]
  12880. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  12881. more details. Defaults to none.
  12882. extra_http_headers : Union[Dict[str, str], None]
  12883. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  12884. offline : Union[bool, None]
  12885. Whether to emulate network being offline. Defaults to `false`. Learn more about
  12886. [network emulation](../emulation.md#offline).
  12887. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  12888. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  12889. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  12890. device_scale_factor : Union[float, None]
  12891. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  12892. [emulating devices with device scale factor](../emulation.md#devices).
  12893. is_mobile : Union[bool, None]
  12894. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  12895. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  12896. about [mobile emulation](../emulation.md#ismobile).
  12897. has_touch : Union[bool, None]
  12898. Specifies if viewport supports touch events. Defaults to false. Learn more about
  12899. [mobile emulation](../emulation.md#devices).
  12900. color_scheme : Union["dark", "light", "no-preference", "null", None]
  12901. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  12902. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  12903. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  12904. reduced_motion : Union["no-preference", "null", "reduce", None]
  12905. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  12906. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12907. `'no-preference'`.
  12908. forced_colors : Union["active", "none", "null", None]
  12909. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  12910. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12911. `'none'`.
  12912. contrast : Union["more", "no-preference", "null", None]
  12913. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  12914. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12915. `'no-preference'`.
  12916. accept_downloads : Union[bool, None]
  12917. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  12918. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  12919. Network proxy settings to use with this context. Defaults to none.
  12920. record_har_path : Union[pathlib.Path, str, None]
  12921. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  12922. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  12923. for the HAR to be saved.
  12924. record_har_omit_content : Union[bool, None]
  12925. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  12926. record_video_dir : Union[pathlib.Path, str, None]
  12927. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  12928. sure to call `browser_context.close()` for videos to be saved.
  12929. record_video_size : Union[{width: int, height: int}, None]
  12930. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  12931. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  12932. will be scaled down if necessary to fit the specified size.
  12933. 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]
  12934. Learn more about [storage state and auth](../auth.md).
  12935. Populates context with given storage state. This option can be used to initialize context with logged-in
  12936. information obtained via `browser_context.storage_state()`.
  12937. base_url : Union[str, None]
  12938. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  12939. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  12940. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  12941. corresponding URL. Unset by default. Examples:
  12942. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  12943. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  12944. `http://localhost:3000/foo/bar.html`
  12945. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  12946. `http://localhost:3000/bar.html`
  12947. strict_selectors : Union[bool, None]
  12948. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  12949. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  12950. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  12951. more about the strict mode.
  12952. service_workers : Union["allow", "block", None]
  12953. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  12954. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  12955. registered.
  12956. - `'block'`: Playwright will block all registration of Service Workers.
  12957. record_har_url_filter : Union[Pattern[str], str, None]
  12958. record_har_mode : Union["full", "minimal", None]
  12959. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  12960. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  12961. record_har_content : Union["attach", "embed", "omit", None]
  12962. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  12963. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  12964. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  12965. 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]
  12966. TLS Client Authentication allows the server to request a client certificate and verify it.
  12967. **Details**
  12968. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  12969. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  12970. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  12971. with an exact match to the request origin that the certificate is valid for.
  12972. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  12973. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  12974. does not match any of the domains you plan to visit.
  12975. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  12976. work by replacing `localhost` with `local.playwright`.
  12977. Returns
  12978. -------
  12979. BrowserContext
  12980. """
  12981. return mapping.from_impl(
  12982. await self._impl_obj.new_context(
  12983. viewport=viewport,
  12984. screen=screen,
  12985. noViewport=no_viewport,
  12986. ignoreHTTPSErrors=ignore_https_errors,
  12987. javaScriptEnabled=java_script_enabled,
  12988. bypassCSP=bypass_csp,
  12989. userAgent=user_agent,
  12990. locale=locale,
  12991. timezoneId=timezone_id,
  12992. geolocation=geolocation,
  12993. permissions=mapping.to_impl(permissions),
  12994. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  12995. offline=offline,
  12996. httpCredentials=http_credentials,
  12997. deviceScaleFactor=device_scale_factor,
  12998. isMobile=is_mobile,
  12999. hasTouch=has_touch,
  13000. colorScheme=color_scheme,
  13001. reducedMotion=reduced_motion,
  13002. forcedColors=forced_colors,
  13003. contrast=contrast,
  13004. acceptDownloads=accept_downloads,
  13005. defaultBrowserType=default_browser_type,
  13006. proxy=proxy,
  13007. recordHarPath=record_har_path,
  13008. recordHarOmitContent=record_har_omit_content,
  13009. recordVideoDir=record_video_dir,
  13010. recordVideoSize=record_video_size,
  13011. storageState=storage_state,
  13012. baseURL=base_url,
  13013. strictSelectors=strict_selectors,
  13014. serviceWorkers=service_workers,
  13015. recordHarUrlFilter=record_har_url_filter,
  13016. recordHarMode=record_har_mode,
  13017. recordHarContent=record_har_content,
  13018. clientCertificates=client_certificates,
  13019. )
  13020. )
  13021. async def new_page(
  13022. self,
  13023. *,
  13024. viewport: typing.Optional[ViewportSize] = None,
  13025. screen: typing.Optional[ViewportSize] = None,
  13026. no_viewport: typing.Optional[bool] = None,
  13027. ignore_https_errors: typing.Optional[bool] = None,
  13028. java_script_enabled: typing.Optional[bool] = None,
  13029. bypass_csp: typing.Optional[bool] = None,
  13030. user_agent: typing.Optional[str] = None,
  13031. locale: typing.Optional[str] = None,
  13032. timezone_id: typing.Optional[str] = None,
  13033. geolocation: typing.Optional[Geolocation] = None,
  13034. permissions: typing.Optional[typing.Sequence[str]] = None,
  13035. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  13036. offline: typing.Optional[bool] = None,
  13037. http_credentials: typing.Optional[HttpCredentials] = None,
  13038. device_scale_factor: typing.Optional[float] = None,
  13039. is_mobile: typing.Optional[bool] = None,
  13040. has_touch: typing.Optional[bool] = None,
  13041. color_scheme: typing.Optional[
  13042. Literal["dark", "light", "no-preference", "null"]
  13043. ] = None,
  13044. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  13045. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  13046. reduced_motion: typing.Optional[
  13047. Literal["no-preference", "null", "reduce"]
  13048. ] = None,
  13049. accept_downloads: typing.Optional[bool] = None,
  13050. default_browser_type: typing.Optional[str] = None,
  13051. proxy: typing.Optional[ProxySettings] = None,
  13052. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13053. record_har_omit_content: typing.Optional[bool] = None,
  13054. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13055. record_video_size: typing.Optional[ViewportSize] = None,
  13056. storage_state: typing.Optional[
  13057. typing.Union[StorageState, str, pathlib.Path]
  13058. ] = None,
  13059. base_url: typing.Optional[str] = None,
  13060. strict_selectors: typing.Optional[bool] = None,
  13061. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  13062. record_har_url_filter: typing.Optional[
  13063. typing.Union[typing.Pattern[str], str]
  13064. ] = None,
  13065. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  13066. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  13067. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  13068. ) -> "Page":
  13069. """Browser.new_page
  13070. Creates a new page in a new browser context. Closing this page will close the context as well.
  13071. This is a convenience API that should only be used for the single-page scenarios and short snippets. Production
  13072. code and testing frameworks should explicitly create `browser.new_context()` followed by the
  13073. `browser_context.new_page()` to control their exact life times.
  13074. Parameters
  13075. ----------
  13076. viewport : Union[{width: int, height: int}, None]
  13077. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  13078. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  13079. screen : Union[{width: int, height: int}, None]
  13080. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  13081. `viewport` is set.
  13082. no_viewport : Union[bool, None]
  13083. Does not enforce fixed viewport, allows resizing window in the headed mode.
  13084. ignore_https_errors : Union[bool, None]
  13085. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  13086. java_script_enabled : Union[bool, None]
  13087. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  13088. [disabling JavaScript](../emulation.md#javascript-enabled).
  13089. bypass_csp : Union[bool, None]
  13090. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  13091. user_agent : Union[str, None]
  13092. Specific user agent to use in this context.
  13093. locale : Union[str, None]
  13094. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  13095. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  13096. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  13097. timezone_id : Union[str, None]
  13098. Changes the timezone of the context. See
  13099. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  13100. for a list of supported timezone IDs. Defaults to the system timezone.
  13101. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  13102. permissions : Union[Sequence[str], None]
  13103. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  13104. more details. Defaults to none.
  13105. extra_http_headers : Union[Dict[str, str], None]
  13106. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  13107. offline : Union[bool, None]
  13108. Whether to emulate network being offline. Defaults to `false`. Learn more about
  13109. [network emulation](../emulation.md#offline).
  13110. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  13111. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  13112. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  13113. device_scale_factor : Union[float, None]
  13114. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  13115. [emulating devices with device scale factor](../emulation.md#devices).
  13116. is_mobile : Union[bool, None]
  13117. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  13118. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  13119. about [mobile emulation](../emulation.md#ismobile).
  13120. has_touch : Union[bool, None]
  13121. Specifies if viewport supports touch events. Defaults to false. Learn more about
  13122. [mobile emulation](../emulation.md#devices).
  13123. color_scheme : Union["dark", "light", "no-preference", "null", None]
  13124. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  13125. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  13126. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  13127. forced_colors : Union["active", "none", "null", None]
  13128. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  13129. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  13130. `'none'`.
  13131. contrast : Union["more", "no-preference", "null", None]
  13132. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  13133. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  13134. `'no-preference'`.
  13135. reduced_motion : Union["no-preference", "null", "reduce", None]
  13136. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  13137. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  13138. `'no-preference'`.
  13139. accept_downloads : Union[bool, None]
  13140. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  13141. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  13142. Network proxy settings to use with this context. Defaults to none.
  13143. record_har_path : Union[pathlib.Path, str, None]
  13144. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  13145. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  13146. for the HAR to be saved.
  13147. record_har_omit_content : Union[bool, None]
  13148. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  13149. record_video_dir : Union[pathlib.Path, str, None]
  13150. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  13151. sure to call `browser_context.close()` for videos to be saved.
  13152. record_video_size : Union[{width: int, height: int}, None]
  13153. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  13154. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  13155. will be scaled down if necessary to fit the specified size.
  13156. 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]
  13157. Learn more about [storage state and auth](../auth.md).
  13158. Populates context with given storage state. This option can be used to initialize context with logged-in
  13159. information obtained via `browser_context.storage_state()`.
  13160. base_url : Union[str, None]
  13161. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  13162. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  13163. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  13164. corresponding URL. Unset by default. Examples:
  13165. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  13166. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  13167. `http://localhost:3000/foo/bar.html`
  13168. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  13169. `http://localhost:3000/bar.html`
  13170. strict_selectors : Union[bool, None]
  13171. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  13172. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  13173. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  13174. more about the strict mode.
  13175. service_workers : Union["allow", "block", None]
  13176. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  13177. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  13178. registered.
  13179. - `'block'`: Playwright will block all registration of Service Workers.
  13180. record_har_url_filter : Union[Pattern[str], str, None]
  13181. record_har_mode : Union["full", "minimal", None]
  13182. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  13183. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  13184. record_har_content : Union["attach", "embed", "omit", None]
  13185. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  13186. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  13187. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  13188. 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]
  13189. TLS Client Authentication allows the server to request a client certificate and verify it.
  13190. **Details**
  13191. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  13192. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  13193. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  13194. with an exact match to the request origin that the certificate is valid for.
  13195. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  13196. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  13197. does not match any of the domains you plan to visit.
  13198. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  13199. work by replacing `localhost` with `local.playwright`.
  13200. Returns
  13201. -------
  13202. Page
  13203. """
  13204. return mapping.from_impl(
  13205. await self._impl_obj.new_page(
  13206. viewport=viewport,
  13207. screen=screen,
  13208. noViewport=no_viewport,
  13209. ignoreHTTPSErrors=ignore_https_errors,
  13210. javaScriptEnabled=java_script_enabled,
  13211. bypassCSP=bypass_csp,
  13212. userAgent=user_agent,
  13213. locale=locale,
  13214. timezoneId=timezone_id,
  13215. geolocation=geolocation,
  13216. permissions=mapping.to_impl(permissions),
  13217. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  13218. offline=offline,
  13219. httpCredentials=http_credentials,
  13220. deviceScaleFactor=device_scale_factor,
  13221. isMobile=is_mobile,
  13222. hasTouch=has_touch,
  13223. colorScheme=color_scheme,
  13224. forcedColors=forced_colors,
  13225. contrast=contrast,
  13226. reducedMotion=reduced_motion,
  13227. acceptDownloads=accept_downloads,
  13228. defaultBrowserType=default_browser_type,
  13229. proxy=proxy,
  13230. recordHarPath=record_har_path,
  13231. recordHarOmitContent=record_har_omit_content,
  13232. recordVideoDir=record_video_dir,
  13233. recordVideoSize=record_video_size,
  13234. storageState=storage_state,
  13235. baseURL=base_url,
  13236. strictSelectors=strict_selectors,
  13237. serviceWorkers=service_workers,
  13238. recordHarUrlFilter=record_har_url_filter,
  13239. recordHarMode=record_har_mode,
  13240. recordHarContent=record_har_content,
  13241. clientCertificates=client_certificates,
  13242. )
  13243. )
  13244. async def close(self, *, reason: typing.Optional[str] = None) -> None:
  13245. """Browser.close
  13246. In case this browser is obtained using `browser_type.launch()`, closes the browser and all of its pages (if
  13247. any were opened).
  13248. In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from
  13249. the browser server.
  13250. **NOTE** This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close
  13251. events, call `browser_context.close()` on any `BrowserContext` instances you explicitly created earlier
  13252. using `browser.new_context()` **before** calling `browser.close()`.
  13253. The `Browser` object itself is considered to be disposed and cannot be used anymore.
  13254. Parameters
  13255. ----------
  13256. reason : Union[str, None]
  13257. The reason to be reported to the operations interrupted by the browser closure.
  13258. """
  13259. return mapping.from_maybe_impl(await self._impl_obj.close(reason=reason))
  13260. async def new_browser_cdp_session(self) -> "CDPSession":
  13261. """Browser.new_browser_cdp_session
  13262. **NOTE** CDP Sessions are only supported on Chromium-based browsers.
  13263. Returns the newly created browser session.
  13264. Returns
  13265. -------
  13266. CDPSession
  13267. """
  13268. return mapping.from_impl(await self._impl_obj.new_browser_cdp_session())
  13269. async def bind(
  13270. self,
  13271. title: str,
  13272. *,
  13273. workspace_dir: typing.Optional[str] = None,
  13274. host: typing.Optional[str] = None,
  13275. port: typing.Optional[int] = None,
  13276. ) -> BrowserBindResult:
  13277. """Browser.bind
  13278. Binds the browser to a named pipe or web socket, making it available for other clients to connect to.
  13279. Parameters
  13280. ----------
  13281. title : str
  13282. Title of the browser server, used for identification.
  13283. workspace_dir : Union[str, None]
  13284. Working directory associated with this browser server.
  13285. host : Union[str, None]
  13286. Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe.
  13287. port : Union[int, None]
  13288. Port to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. Use
  13289. `0` to let the OS pick an available port.
  13290. Returns
  13291. -------
  13292. {endpoint: str}
  13293. """
  13294. return mapping.from_impl(
  13295. await self._impl_obj.bind(
  13296. title=title, workspaceDir=workspace_dir, host=host, port=port
  13297. )
  13298. )
  13299. async def unbind(self) -> None:
  13300. """Browser.unbind
  13301. Unbinds the browser server previously bound with `browser.bind()`.
  13302. """
  13303. return mapping.from_maybe_impl(await self._impl_obj.unbind())
  13304. async def start_tracing(
  13305. self,
  13306. *,
  13307. page: typing.Optional["Page"] = None,
  13308. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13309. screenshots: typing.Optional[bool] = None,
  13310. categories: typing.Optional[typing.Sequence[str]] = None,
  13311. ) -> None:
  13312. """Browser.start_tracing
  13313. **NOTE** This API controls
  13314. [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
  13315. chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
  13316. [here](https://playwright.dev/python/docs/api/class-tracing).
  13317. You can use `browser.start_tracing()` and `browser.stop_tracing()` to create a trace file that can be
  13318. opened in Chrome DevTools performance panel.
  13319. **Usage**
  13320. ```py
  13321. await browser.start_tracing(page, path=\"trace.json\")
  13322. await page.goto(\"https://www.google.com\")
  13323. await browser.stop_tracing()
  13324. ```
  13325. Parameters
  13326. ----------
  13327. page : Union[Page, None]
  13328. Optional, if specified, tracing includes screenshots of the given page.
  13329. path : Union[pathlib.Path, str, None]
  13330. A path to write the trace file to.
  13331. screenshots : Union[bool, None]
  13332. captures screenshots in the trace.
  13333. categories : Union[Sequence[str], None]
  13334. specify custom categories to use instead of default.
  13335. """
  13336. return mapping.from_maybe_impl(
  13337. await self._impl_obj.start_tracing(
  13338. page=page._impl_obj if page else None,
  13339. path=path,
  13340. screenshots=screenshots,
  13341. categories=mapping.to_impl(categories),
  13342. )
  13343. )
  13344. async def stop_tracing(self) -> bytes:
  13345. """Browser.stop_tracing
  13346. **NOTE** This API controls
  13347. [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
  13348. chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
  13349. [here](https://playwright.dev/python/docs/api/class-tracing).
  13350. Returns the buffer with trace data.
  13351. Returns
  13352. -------
  13353. bytes
  13354. """
  13355. return mapping.from_maybe_impl(await self._impl_obj.stop_tracing())
  13356. mapping.register(BrowserImpl, Browser)
  13357. class BrowserType(AsyncBase):
  13358. @property
  13359. def name(self) -> str:
  13360. """BrowserType.name
  13361. Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
  13362. Returns
  13363. -------
  13364. str
  13365. """
  13366. return mapping.from_maybe_impl(self._impl_obj.name)
  13367. @property
  13368. def executable_path(self) -> str:
  13369. """BrowserType.executable_path
  13370. A path where Playwright expects to find a bundled browser executable.
  13371. Returns
  13372. -------
  13373. str
  13374. """
  13375. return mapping.from_maybe_impl(self._impl_obj.executable_path)
  13376. async def launch(
  13377. self,
  13378. *,
  13379. executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13380. channel: typing.Optional[str] = None,
  13381. args: typing.Optional[typing.Sequence[str]] = None,
  13382. ignore_default_args: typing.Optional[
  13383. typing.Union[bool, typing.Sequence[str]]
  13384. ] = None,
  13385. handle_sigint: typing.Optional[bool] = None,
  13386. handle_sigterm: typing.Optional[bool] = None,
  13387. handle_sighup: typing.Optional[bool] = None,
  13388. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  13389. env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  13390. headless: typing.Optional[bool] = None,
  13391. proxy: typing.Optional[ProxySettings] = None,
  13392. downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13393. slow_mo: typing.Optional[float] = None,
  13394. traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13395. artifacts_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13396. chromium_sandbox: typing.Optional[bool] = None,
  13397. firefox_user_prefs: typing.Optional[
  13398. typing.Dict[str, typing.Union[str, float, bool]]
  13399. ] = None,
  13400. ) -> "Browser":
  13401. """BrowserType.launch
  13402. Returns the browser instance.
  13403. **Usage**
  13404. You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
  13405. ```py
  13406. browser = await playwright.chromium.launch( # or \"firefox\" or \"webkit\".
  13407. ignore_default_args=[\"--mute-audio\"]
  13408. )
  13409. ```
  13410. > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it
  13411. works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other
  13412. version. Use `executablePath` option with extreme caution.
  13413. >
  13414. > If Google Chrome (rather than Chromium) is preferred, a
  13415. [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
  13416. [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
  13417. >
  13418. > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs
  13419. for video playback. See
  13420. [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
  13421. other differences between Chromium and Chrome.
  13422. [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
  13423. describes some differences for Linux users.
  13424. Parameters
  13425. ----------
  13426. executable_path : Union[pathlib.Path, str, None]
  13427. Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
  13428. resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
  13429. Firefox or WebKit, use at your own risk.
  13430. channel : Union[str, None]
  13431. Browser distribution channel.
  13432. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
  13433. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
  13434. "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
  13435. args : Union[Sequence[str], None]
  13436. **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
  13437. Additional arguments to pass to the browser instance. The list of Chromium flags can be found
  13438. [here](https://peter.sh/experiments/chromium-command-line-switches/).
  13439. ignore_default_args : Union[Sequence[str], bool, None]
  13440. If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
  13441. given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
  13442. handle_sigint : Union[bool, None]
  13443. Close the browser process on Ctrl-C. Defaults to `true`.
  13444. handle_sigterm : Union[bool, None]
  13445. Close the browser process on SIGTERM. Defaults to `true`.
  13446. handle_sighup : Union[bool, None]
  13447. Close the browser process on SIGHUP. Defaults to `true`.
  13448. timeout : Union[float, None]
  13449. Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
  13450. to disable timeout.
  13451. env : Union[Dict[str, Union[bool, float, str]], None]
  13452. Specify environment variables that will be visible to the browser. Defaults to `process.env`.
  13453. headless : Union[bool, None]
  13454. Whether to run browser in headless mode. More details for
  13455. [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
  13456. [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
  13457. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  13458. Network proxy settings.
  13459. downloads_path : Union[pathlib.Path, str, None]
  13460. If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
  13461. is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
  13462. created in is closed.
  13463. slow_mo : Union[float, None]
  13464. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  13465. on.
  13466. traces_dir : Union[pathlib.Path, str, None]
  13467. If specified, traces are saved into this directory.
  13468. artifacts_dir : Union[pathlib.Path, str, None]
  13469. If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory
  13470. is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the
  13471. browser closes.
  13472. chromium_sandbox : Union[bool, None]
  13473. Enable Chromium sandboxing. Defaults to `false`.
  13474. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
  13475. Firefox user preferences. Learn more about the Firefox user preferences at
  13476. [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
  13477. You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
  13478. `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
  13479. Returns
  13480. -------
  13481. Browser
  13482. """
  13483. return mapping.from_impl(
  13484. await self._impl_obj.launch(
  13485. executablePath=executable_path,
  13486. channel=channel,
  13487. args=mapping.to_impl(args),
  13488. ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
  13489. handleSIGINT=handle_sigint,
  13490. handleSIGTERM=handle_sigterm,
  13491. handleSIGHUP=handle_sighup,
  13492. timeout=to_milliseconds(timeout),
  13493. env=mapping.to_impl(env),
  13494. headless=headless,
  13495. proxy=proxy,
  13496. downloadsPath=downloads_path,
  13497. slowMo=slow_mo,
  13498. tracesDir=traces_dir,
  13499. artifactsDir=artifacts_dir,
  13500. chromiumSandbox=chromium_sandbox,
  13501. firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
  13502. )
  13503. )
  13504. async def launch_persistent_context(
  13505. self,
  13506. user_data_dir: typing.Union[str, pathlib.Path],
  13507. *,
  13508. channel: typing.Optional[str] = None,
  13509. executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13510. args: typing.Optional[typing.Sequence[str]] = None,
  13511. ignore_default_args: typing.Optional[
  13512. typing.Union[bool, typing.Sequence[str]]
  13513. ] = None,
  13514. handle_sigint: typing.Optional[bool] = None,
  13515. handle_sigterm: typing.Optional[bool] = None,
  13516. handle_sighup: typing.Optional[bool] = None,
  13517. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  13518. env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  13519. headless: typing.Optional[bool] = None,
  13520. proxy: typing.Optional[ProxySettings] = None,
  13521. downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13522. slow_mo: typing.Optional[float] = None,
  13523. viewport: typing.Optional[ViewportSize] = None,
  13524. screen: typing.Optional[ViewportSize] = None,
  13525. no_viewport: typing.Optional[bool] = None,
  13526. ignore_https_errors: typing.Optional[bool] = None,
  13527. java_script_enabled: typing.Optional[bool] = None,
  13528. bypass_csp: typing.Optional[bool] = None,
  13529. user_agent: typing.Optional[str] = None,
  13530. locale: typing.Optional[str] = None,
  13531. timezone_id: typing.Optional[str] = None,
  13532. geolocation: typing.Optional[Geolocation] = None,
  13533. permissions: typing.Optional[typing.Sequence[str]] = None,
  13534. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  13535. offline: typing.Optional[bool] = None,
  13536. http_credentials: typing.Optional[HttpCredentials] = None,
  13537. device_scale_factor: typing.Optional[float] = None,
  13538. is_mobile: typing.Optional[bool] = None,
  13539. has_touch: typing.Optional[bool] = None,
  13540. color_scheme: typing.Optional[
  13541. Literal["dark", "light", "no-preference", "null"]
  13542. ] = None,
  13543. reduced_motion: typing.Optional[
  13544. Literal["no-preference", "null", "reduce"]
  13545. ] = None,
  13546. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  13547. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  13548. accept_downloads: typing.Optional[bool] = None,
  13549. traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13550. artifacts_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13551. chromium_sandbox: typing.Optional[bool] = None,
  13552. firefox_user_prefs: typing.Optional[
  13553. typing.Dict[str, typing.Union[str, float, bool]]
  13554. ] = None,
  13555. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13556. record_har_omit_content: typing.Optional[bool] = None,
  13557. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  13558. record_video_size: typing.Optional[ViewportSize] = None,
  13559. base_url: typing.Optional[str] = None,
  13560. strict_selectors: typing.Optional[bool] = None,
  13561. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  13562. record_har_url_filter: typing.Optional[
  13563. typing.Union[typing.Pattern[str], str]
  13564. ] = None,
  13565. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  13566. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  13567. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  13568. ) -> "BrowserContext":
  13569. """BrowserType.launch_persistent_context
  13570. Returns the persistent browser context instance.
  13571. Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
  13572. context will automatically close the browser.
  13573. Parameters
  13574. ----------
  13575. user_data_dir : Union[pathlib.Path, str]
  13576. Path to a User Data Directory, which stores browser session data like cookies and local storage. Pass an empty
  13577. string to create a temporary directory.
  13578. More details for
  13579. [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
  13580. [Firefox](https://wiki.mozilla.org/Firefox/CommandLineOptions#User_profile). Chromium's user data directory is the
  13581. **parent** directory of the "Profile Path" seen at `chrome://version`.
  13582. Note that browsers do not allow launching multiple instances with the same User Data Directory.
  13583. **NOTE** Chromium/Chrome: Due to recent Chrome policy changes, automating the default Chrome user profile is not
  13584. supported. Pointing `userDataDir` to Chrome's main "User Data" directory (the profile used for your regular
  13585. browsing) may result in pages not loading or the browser exiting. Create and use a separate directory (for example,
  13586. an empty folder) as your automation profile instead. See https://developer.chrome.com/blog/remote-debugging-port
  13587. for details.
  13588. channel : Union[str, None]
  13589. Browser distribution channel.
  13590. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
  13591. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
  13592. "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
  13593. executable_path : Union[pathlib.Path, str, None]
  13594. Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
  13595. resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
  13596. Firefox or WebKit, use at your own risk.
  13597. args : Union[Sequence[str], None]
  13598. **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
  13599. Additional arguments to pass to the browser instance. The list of Chromium flags can be found
  13600. [here](https://peter.sh/experiments/chromium-command-line-switches/).
  13601. ignore_default_args : Union[Sequence[str], bool, None]
  13602. If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
  13603. given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
  13604. handle_sigint : Union[bool, None]
  13605. Close the browser process on Ctrl-C. Defaults to `true`.
  13606. handle_sigterm : Union[bool, None]
  13607. Close the browser process on SIGTERM. Defaults to `true`.
  13608. handle_sighup : Union[bool, None]
  13609. Close the browser process on SIGHUP. Defaults to `true`.
  13610. timeout : Union[float, None]
  13611. Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
  13612. to disable timeout.
  13613. env : Union[Dict[str, Union[bool, float, str]], None]
  13614. Specify environment variables that will be visible to the browser. Defaults to `process.env`.
  13615. headless : Union[bool, None]
  13616. Whether to run browser in headless mode. More details for
  13617. [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
  13618. [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
  13619. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  13620. Network proxy settings.
  13621. downloads_path : Union[pathlib.Path, str, None]
  13622. If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
  13623. is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
  13624. created in is closed.
  13625. slow_mo : Union[float, None]
  13626. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  13627. on.
  13628. viewport : Union[{width: int, height: int}, None]
  13629. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  13630. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  13631. screen : Union[{width: int, height: int}, None]
  13632. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  13633. `viewport` is set.
  13634. no_viewport : Union[bool, None]
  13635. Does not enforce fixed viewport, allows resizing window in the headed mode.
  13636. ignore_https_errors : Union[bool, None]
  13637. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  13638. java_script_enabled : Union[bool, None]
  13639. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  13640. [disabling JavaScript](../emulation.md#javascript-enabled).
  13641. bypass_csp : Union[bool, None]
  13642. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  13643. user_agent : Union[str, None]
  13644. Specific user agent to use in this context.
  13645. locale : Union[str, None]
  13646. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  13647. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  13648. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  13649. timezone_id : Union[str, None]
  13650. Changes the timezone of the context. See
  13651. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  13652. for a list of supported timezone IDs. Defaults to the system timezone.
  13653. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  13654. permissions : Union[Sequence[str], None]
  13655. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  13656. more details. Defaults to none.
  13657. extra_http_headers : Union[Dict[str, str], None]
  13658. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  13659. offline : Union[bool, None]
  13660. Whether to emulate network being offline. Defaults to `false`. Learn more about
  13661. [network emulation](../emulation.md#offline).
  13662. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  13663. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  13664. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  13665. device_scale_factor : Union[float, None]
  13666. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  13667. [emulating devices with device scale factor](../emulation.md#devices).
  13668. is_mobile : Union[bool, None]
  13669. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  13670. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  13671. about [mobile emulation](../emulation.md#ismobile).
  13672. has_touch : Union[bool, None]
  13673. Specifies if viewport supports touch events. Defaults to false. Learn more about
  13674. [mobile emulation](../emulation.md#devices).
  13675. color_scheme : Union["dark", "light", "no-preference", "null", None]
  13676. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  13677. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  13678. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  13679. reduced_motion : Union["no-preference", "null", "reduce", None]
  13680. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  13681. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  13682. `'no-preference'`.
  13683. forced_colors : Union["active", "none", "null", None]
  13684. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  13685. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  13686. `'none'`.
  13687. contrast : Union["more", "no-preference", "null", None]
  13688. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  13689. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  13690. `'no-preference'`.
  13691. accept_downloads : Union[bool, None]
  13692. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  13693. traces_dir : Union[pathlib.Path, str, None]
  13694. If specified, traces are saved into this directory.
  13695. artifacts_dir : Union[pathlib.Path, str, None]
  13696. If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory
  13697. is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the
  13698. browser closes.
  13699. chromium_sandbox : Union[bool, None]
  13700. Enable Chromium sandboxing. Defaults to `false`.
  13701. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
  13702. Firefox user preferences. Learn more about the Firefox user preferences at
  13703. [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
  13704. You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
  13705. `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
  13706. record_har_path : Union[pathlib.Path, str, None]
  13707. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  13708. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  13709. for the HAR to be saved.
  13710. record_har_omit_content : Union[bool, None]
  13711. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  13712. record_video_dir : Union[pathlib.Path, str, None]
  13713. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  13714. sure to call `browser_context.close()` for videos to be saved.
  13715. record_video_size : Union[{width: int, height: int}, None]
  13716. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  13717. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  13718. will be scaled down if necessary to fit the specified size.
  13719. base_url : Union[str, None]
  13720. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  13721. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  13722. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  13723. corresponding URL. Unset by default. Examples:
  13724. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  13725. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  13726. `http://localhost:3000/foo/bar.html`
  13727. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  13728. `http://localhost:3000/bar.html`
  13729. strict_selectors : Union[bool, None]
  13730. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  13731. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  13732. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  13733. more about the strict mode.
  13734. service_workers : Union["allow", "block", None]
  13735. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  13736. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  13737. registered.
  13738. - `'block'`: Playwright will block all registration of Service Workers.
  13739. record_har_url_filter : Union[Pattern[str], str, None]
  13740. record_har_mode : Union["full", "minimal", None]
  13741. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  13742. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  13743. record_har_content : Union["attach", "embed", "omit", None]
  13744. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  13745. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  13746. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  13747. 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]
  13748. TLS Client Authentication allows the server to request a client certificate and verify it.
  13749. **Details**
  13750. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  13751. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  13752. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  13753. with an exact match to the request origin that the certificate is valid for.
  13754. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  13755. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  13756. does not match any of the domains you plan to visit.
  13757. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  13758. work by replacing `localhost` with `local.playwright`.
  13759. Returns
  13760. -------
  13761. BrowserContext
  13762. """
  13763. return mapping.from_impl(
  13764. await self._impl_obj.launch_persistent_context(
  13765. userDataDir=user_data_dir,
  13766. channel=channel,
  13767. executablePath=executable_path,
  13768. args=mapping.to_impl(args),
  13769. ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
  13770. handleSIGINT=handle_sigint,
  13771. handleSIGTERM=handle_sigterm,
  13772. handleSIGHUP=handle_sighup,
  13773. timeout=to_milliseconds(timeout),
  13774. env=mapping.to_impl(env),
  13775. headless=headless,
  13776. proxy=proxy,
  13777. downloadsPath=downloads_path,
  13778. slowMo=slow_mo,
  13779. viewport=viewport,
  13780. screen=screen,
  13781. noViewport=no_viewport,
  13782. ignoreHTTPSErrors=ignore_https_errors,
  13783. javaScriptEnabled=java_script_enabled,
  13784. bypassCSP=bypass_csp,
  13785. userAgent=user_agent,
  13786. locale=locale,
  13787. timezoneId=timezone_id,
  13788. geolocation=geolocation,
  13789. permissions=mapping.to_impl(permissions),
  13790. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  13791. offline=offline,
  13792. httpCredentials=http_credentials,
  13793. deviceScaleFactor=device_scale_factor,
  13794. isMobile=is_mobile,
  13795. hasTouch=has_touch,
  13796. colorScheme=color_scheme,
  13797. reducedMotion=reduced_motion,
  13798. forcedColors=forced_colors,
  13799. contrast=contrast,
  13800. acceptDownloads=accept_downloads,
  13801. tracesDir=traces_dir,
  13802. artifactsDir=artifacts_dir,
  13803. chromiumSandbox=chromium_sandbox,
  13804. firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
  13805. recordHarPath=record_har_path,
  13806. recordHarOmitContent=record_har_omit_content,
  13807. recordVideoDir=record_video_dir,
  13808. recordVideoSize=record_video_size,
  13809. baseURL=base_url,
  13810. strictSelectors=strict_selectors,
  13811. serviceWorkers=service_workers,
  13812. recordHarUrlFilter=record_har_url_filter,
  13813. recordHarMode=record_har_mode,
  13814. recordHarContent=record_har_content,
  13815. clientCertificates=client_certificates,
  13816. )
  13817. )
  13818. async def connect_over_cdp(
  13819. self,
  13820. endpoint_url: str,
  13821. *,
  13822. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  13823. slow_mo: typing.Optional[float] = None,
  13824. headers: typing.Optional[typing.Dict[str, str]] = None,
  13825. is_local: typing.Optional[bool] = None,
  13826. no_defaults: typing.Optional[bool] = None,
  13827. ) -> "Browser":
  13828. """BrowserType.connect_over_cdp
  13829. This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
  13830. The default browser context is accessible via `browser.contexts()`.
  13831. **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
  13832. **NOTE** This connection is significantly lower fidelity than the Playwright protocol connection via
  13833. `browser_type.connect()`. If you are experiencing issues or attempting to use advanced functionality, you
  13834. probably want to use `browser_type.connect()`.
  13835. **Usage**
  13836. ```py
  13837. browser = await playwright.chromium.connect_over_cdp(\"http://localhost:9222\")
  13838. default_context = browser.contexts[0]
  13839. page = default_context.pages[0]
  13840. ```
  13841. Parameters
  13842. ----------
  13843. endpoint_url : str
  13844. A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
  13845. `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
  13846. timeout : Union[float, None]
  13847. Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
  13848. `0` to disable timeout.
  13849. slow_mo : Union[float, None]
  13850. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  13851. on. Defaults to 0.
  13852. headers : Union[Dict[str, str], None]
  13853. Additional HTTP headers to be sent with connect request. Optional.
  13854. is_local : Union[bool, None]
  13855. Tells Playwright that it runs on the same host as the CDP server. It will enable certain optimizations that rely
  13856. upon the file system being the same between Playwright and the Browser.
  13857. no_defaults : Union[bool, None]
  13858. When true, Playwright will not apply its default overrides to the existing default browser context. Specifically,
  13859. `acceptDownloads` is left at the browser's setting, focus emulation is not enabled, and media emulation options
  13860. (such as `colorScheme`, `reducedMotion`, `forcedColors`, and `contrast`) are not applied. Useful when attaching to
  13861. a user's daily-driver browser where these overrides would interfere with existing browser state. New contexts
  13862. created via `browser.new_context()` are not affected. Defaults to `false`.
  13863. Returns
  13864. -------
  13865. Browser
  13866. """
  13867. return mapping.from_impl(
  13868. await self._impl_obj.connect_over_cdp(
  13869. endpointURL=endpoint_url,
  13870. timeout=to_milliseconds(timeout),
  13871. slowMo=slow_mo,
  13872. headers=mapping.to_impl(headers),
  13873. isLocal=is_local,
  13874. noDefaults=no_defaults,
  13875. )
  13876. )
  13877. async def connect(
  13878. self,
  13879. endpoint: str,
  13880. *,
  13881. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  13882. slow_mo: typing.Optional[float] = None,
  13883. headers: typing.Optional[typing.Dict[str, str]] = None,
  13884. expose_network: typing.Optional[str] = None,
  13885. ) -> "Browser":
  13886. """BrowserType.connect
  13887. This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js.
  13888. **NOTE** The major and minor version of the Playwright instance that connects needs to match the version of
  13889. Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
  13890. Parameters
  13891. ----------
  13892. endpoint : str
  13893. A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`.
  13894. timeout : Union[float, None]
  13895. Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout).
  13896. slow_mo : Union[float, None]
  13897. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  13898. on. Defaults to 0.
  13899. headers : Union[Dict[str, str], None]
  13900. Additional HTTP headers to be sent with web socket connect request. Optional.
  13901. expose_network : Union[str, None]
  13902. This option exposes network available on the connecting client to the browser being connected to. Consists of a
  13903. list of rules separated by comma.
  13904. Available rules:
  13905. 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
  13906. 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
  13907. 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
  13908. Some common examples:
  13909. 1. `"*"` to expose all network.
  13910. 1. `"<loopback>"` to expose localhost network.
  13911. 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to expose test/staging deployments and
  13912. localhost.
  13913. Returns
  13914. -------
  13915. Browser
  13916. """
  13917. return mapping.from_impl(
  13918. await self._impl_obj.connect(
  13919. endpoint=endpoint,
  13920. timeout=to_milliseconds(timeout),
  13921. slowMo=slow_mo,
  13922. headers=mapping.to_impl(headers),
  13923. exposeNetwork=expose_network,
  13924. )
  13925. )
  13926. mapping.register(BrowserTypeImpl, BrowserType)
  13927. class Playwright(AsyncBase):
  13928. @property
  13929. def devices(self) -> typing.Dict:
  13930. """Playwright.devices
  13931. Returns a dictionary of devices to be used with `browser.new_context()` or `browser.new_page()`.
  13932. ```py
  13933. import asyncio
  13934. from playwright.async_api import async_playwright, Playwright
  13935. async def run(playwright: Playwright):
  13936. webkit = playwright.webkit
  13937. iphone = playwright.devices[\"iPhone 6\"]
  13938. browser = await webkit.launch()
  13939. context = await browser.new_context(**iphone)
  13940. page = await context.new_page()
  13941. await page.goto(\"http://example.com\")
  13942. # other actions...
  13943. await browser.close()
  13944. async def main():
  13945. async with async_playwright() as playwright:
  13946. await run(playwright)
  13947. asyncio.run(main())
  13948. ```
  13949. Returns
  13950. -------
  13951. Dict
  13952. """
  13953. return mapping.from_maybe_impl(self._impl_obj.devices)
  13954. @property
  13955. def selectors(self) -> "Selectors":
  13956. """Playwright.selectors
  13957. Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/python/docs/extensibility) for more
  13958. information.
  13959. Returns
  13960. -------
  13961. Selectors
  13962. """
  13963. return mapping.from_impl(self._impl_obj.selectors)
  13964. @property
  13965. def chromium(self) -> "BrowserType":
  13966. """Playwright.chromium
  13967. This object can be used to launch or connect to Chromium, returning instances of `Browser`.
  13968. Returns
  13969. -------
  13970. BrowserType
  13971. """
  13972. return mapping.from_impl(self._impl_obj.chromium)
  13973. @property
  13974. def firefox(self) -> "BrowserType":
  13975. """Playwright.firefox
  13976. This object can be used to launch or connect to Firefox, returning instances of `Browser`.
  13977. Returns
  13978. -------
  13979. BrowserType
  13980. """
  13981. return mapping.from_impl(self._impl_obj.firefox)
  13982. @property
  13983. def webkit(self) -> "BrowserType":
  13984. """Playwright.webkit
  13985. This object can be used to launch or connect to WebKit, returning instances of `Browser`.
  13986. Returns
  13987. -------
  13988. BrowserType
  13989. """
  13990. return mapping.from_impl(self._impl_obj.webkit)
  13991. @property
  13992. def request(self) -> "APIRequest":
  13993. """Playwright.request
  13994. Exposes API that can be used for the Web API testing.
  13995. Returns
  13996. -------
  13997. APIRequest
  13998. """
  13999. return mapping.from_impl(self._impl_obj.request)
  14000. def __getitem__(self, value: str) -> "BrowserType":
  14001. return mapping.from_impl(self._impl_obj.__getitem__(value=value))
  14002. async def stop(self) -> None:
  14003. """Playwright.stop
  14004. Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful
  14005. in REPL applications.
  14006. ```py
  14007. from playwright.sync_api import sync_playwright
  14008. playwright = sync_playwright().start()
  14009. browser = playwright.chromium.launch()
  14010. page = browser.new_page()
  14011. page.goto(\"https://playwright.dev/\")
  14012. page.screenshot(path=\"example.png\")
  14013. browser.close()
  14014. playwright.stop()
  14015. ```
  14016. """
  14017. return mapping.from_maybe_impl(await self._impl_obj.stop())
  14018. mapping.register(PlaywrightImpl, Playwright)
  14019. class Tracing(AsyncBase):
  14020. async def start(
  14021. self,
  14022. *,
  14023. name: typing.Optional[str] = None,
  14024. title: typing.Optional[str] = None,
  14025. snapshots: typing.Optional[bool] = None,
  14026. screenshots: typing.Optional[bool] = None,
  14027. sources: typing.Optional[bool] = None,
  14028. live: typing.Optional[bool] = None,
  14029. ) -> None:
  14030. """Tracing.start
  14031. Start tracing.
  14032. **NOTE** You probably want to
  14033. [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead
  14034. of using `Tracing.start`.
  14035. The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions
  14036. (like `expect` calls). We recommend
  14037. [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),
  14038. which includes those assertions and provides a more complete trace for debugging test failures.
  14039. **Usage**
  14040. ```py
  14041. await context.tracing.start(screenshots=True, snapshots=True)
  14042. page = await context.new_page()
  14043. await page.goto(\"https://playwright.dev\")
  14044. await context.tracing.stop(path = \"trace.zip\")
  14045. ```
  14046. Parameters
  14047. ----------
  14048. name : Union[str, None]
  14049. If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
  14050. `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
  14051. need to pass `path` option to `tracing.stop()` instead.
  14052. title : Union[str, None]
  14053. Trace name to be shown in the Trace Viewer.
  14054. snapshots : Union[bool, None]
  14055. If this option is true tracing will
  14056. - capture DOM snapshot on every action
  14057. - record network activity
  14058. screenshots : Union[bool, None]
  14059. Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.
  14060. sources : Union[bool, None]
  14061. Whether to include source files for trace actions.
  14062. live : Union[bool, None]
  14063. When enabled, the trace is written to an unarchived file that is updated in real time as actions occur, instead of
  14064. caching changes and archiving them into a zip file at the end. This is useful for live trace viewing during test
  14065. execution.
  14066. """
  14067. return mapping.from_maybe_impl(
  14068. await self._impl_obj.start(
  14069. name=name,
  14070. title=title,
  14071. snapshots=snapshots,
  14072. screenshots=screenshots,
  14073. sources=sources,
  14074. live=live,
  14075. )
  14076. )
  14077. async def start_chunk(
  14078. self, *, title: typing.Optional[str] = None, name: typing.Optional[str] = None
  14079. ) -> None:
  14080. """Tracing.start_chunk
  14081. Start a new trace chunk. If you'd like to record multiple traces on the same `BrowserContext`, use
  14082. `tracing.start()` once, and then create multiple trace chunks with `tracing.start_chunk()` and
  14083. `tracing.stop_chunk()`.
  14084. **Usage**
  14085. ```py
  14086. await context.tracing.start(screenshots=True, snapshots=True)
  14087. page = await context.new_page()
  14088. await page.goto(\"https://playwright.dev\")
  14089. await context.tracing.start_chunk()
  14090. await page.get_by_text(\"Get Started\").click()
  14091. # Everything between start_chunk and stop_chunk will be recorded in the trace.
  14092. await context.tracing.stop_chunk(path = \"trace1.zip\")
  14093. await context.tracing.start_chunk()
  14094. await page.goto(\"http://example.com\")
  14095. # Save a second trace file with different actions.
  14096. await context.tracing.stop_chunk(path = \"trace2.zip\")
  14097. ```
  14098. Parameters
  14099. ----------
  14100. title : Union[str, None]
  14101. Trace name to be shown in the Trace Viewer.
  14102. name : Union[str, None]
  14103. If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
  14104. `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
  14105. need to pass `path` option to `tracing.stop_chunk()` instead.
  14106. """
  14107. return mapping.from_maybe_impl(
  14108. await self._impl_obj.start_chunk(title=title, name=name)
  14109. )
  14110. async def stop_chunk(
  14111. self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
  14112. ) -> None:
  14113. """Tracing.stop_chunk
  14114. Stop the trace chunk. See `tracing.start_chunk()` for more details about multiple trace chunks.
  14115. Parameters
  14116. ----------
  14117. path : Union[pathlib.Path, str, None]
  14118. Export trace collected since the last `tracing.start_chunk()` call into the file with the given path.
  14119. """
  14120. return mapping.from_maybe_impl(await self._impl_obj.stop_chunk(path=path))
  14121. async def stop(
  14122. self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
  14123. ) -> None:
  14124. """Tracing.stop
  14125. Stop tracing.
  14126. Parameters
  14127. ----------
  14128. path : Union[pathlib.Path, str, None]
  14129. Export trace into the file with the given path.
  14130. """
  14131. return mapping.from_maybe_impl(await self._impl_obj.stop(path=path))
  14132. async def group(
  14133. self, name: str, *, location: typing.Optional[TracingGroupLocation] = None
  14134. ) -> "AsyncContextManager":
  14135. """Tracing.group
  14136. **NOTE** Use `test.step` instead when available.
  14137. Creates a new group within the trace, assigning any subsequent API calls to this group, until
  14138. `tracing.group_end()` is called. Groups can be nested and will be visible in the trace viewer.
  14139. **Usage**
  14140. ```py
  14141. # All actions between group and group_end
  14142. # will be shown in the trace viewer as a group.
  14143. page.context.tracing.group(\"Open Playwright.dev > API\")
  14144. page.goto(\"https://playwright.dev/\")
  14145. page.get_by_role(\"link\", name=\"API\").click()
  14146. page.context.tracing.group_end()
  14147. ```
  14148. Parameters
  14149. ----------
  14150. name : str
  14151. Group name shown in the trace viewer.
  14152. location : Union[{file: str, line: Union[int, None], column: Union[int, None]}, None]
  14153. Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the
  14154. `tracing.group()` call.
  14155. Returns
  14156. -------
  14157. AsyncContextManager
  14158. """
  14159. return mapping.from_impl(
  14160. await self._impl_obj.group(name=name, location=location)
  14161. )
  14162. async def group_end(self) -> None:
  14163. """Tracing.group_end
  14164. Closes the last group created by `tracing.group()`.
  14165. """
  14166. return mapping.from_maybe_impl(await self._impl_obj.group_end())
  14167. async def start_har(
  14168. self,
  14169. path: typing.Union[pathlib.Path, str],
  14170. *,
  14171. content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  14172. mode: typing.Optional[Literal["full", "minimal"]] = None,
  14173. url_filter: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  14174. ) -> "AsyncContextManager":
  14175. """Tracing.start_har
  14176. Start recording a HAR (HTTP Archive) of network activity in this context. The HAR file is written to disk when
  14177. `tracing.stop_har()` is called, or when the returned `Disposable` is disposed.
  14178. Only one HAR recording can be active at a time per `BrowserContext`.
  14179. **Usage**
  14180. ```py
  14181. await context.tracing.start_har(\"trace.har\")
  14182. page = await context.new_page()
  14183. await page.goto(\"https://playwright.dev\")
  14184. await context.tracing.stop_har()
  14185. ```
  14186. Parameters
  14187. ----------
  14188. path : Union[pathlib.Path, str]
  14189. Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, the HAR is saved as a zip
  14190. archive with response bodies attached as separate files.
  14191. content : Union["attach", "embed", "omit", None]
  14192. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  14193. `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
  14194. specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
  14195. files and to `embed` for all other file extensions.
  14196. mode : Union["full", "minimal", None]
  14197. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  14198. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  14199. url_filter : Union[Pattern[str], str, None]
  14200. A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.
  14201. Returns
  14202. -------
  14203. AsyncContextManager
  14204. """
  14205. return mapping.from_impl(
  14206. await self._impl_obj.start_har(
  14207. path=path, content=content, mode=mode, urlFilter=url_filter
  14208. )
  14209. )
  14210. async def stop_har(self) -> None:
  14211. """Tracing.stop_har
  14212. Stop HAR recording and save the HAR file to the path given to `tracing.start_har()`.
  14213. """
  14214. return mapping.from_maybe_impl(await self._impl_obj.stop_har())
  14215. mapping.register(TracingImpl, Tracing)
  14216. class Locator(AsyncBase):
  14217. @property
  14218. def page(self) -> "Page":
  14219. """Locator.page
  14220. A page this locator belongs to.
  14221. Returns
  14222. -------
  14223. Page
  14224. """
  14225. return mapping.from_impl(self._impl_obj.page)
  14226. @property
  14227. def first(self) -> "Locator":
  14228. """Locator.first
  14229. Returns locator to the first matching element.
  14230. Returns
  14231. -------
  14232. Locator
  14233. """
  14234. return mapping.from_impl(self._impl_obj.first)
  14235. @property
  14236. def last(self) -> "Locator":
  14237. """Locator.last
  14238. Returns locator to the last matching element.
  14239. **Usage**
  14240. ```py
  14241. banana = await page.get_by_role(\"listitem\").last
  14242. ```
  14243. Returns
  14244. -------
  14245. Locator
  14246. """
  14247. return mapping.from_impl(self._impl_obj.last)
  14248. @property
  14249. def content_frame(self) -> "FrameLocator":
  14250. """Locator.content_frame
  14251. Returns a `FrameLocator` object pointing to the same `iframe` as this locator.
  14252. Useful when you have a `Locator` object obtained somewhere, and later on would like to interact with the content
  14253. inside the frame.
  14254. For a reverse operation, use `frame_locator.owner()`.
  14255. **Usage**
  14256. ```py
  14257. locator = page.locator(\"iframe[name=\\\"embedded\\\"]\")
  14258. # ...
  14259. frame_locator = locator.content_frame
  14260. await frame_locator.get_by_role(\"button\").click()
  14261. ```
  14262. Returns
  14263. -------
  14264. FrameLocator
  14265. """
  14266. return mapping.from_impl(self._impl_obj.content_frame)
  14267. @property
  14268. def description(self) -> typing.Optional[str]:
  14269. """Locator.description
  14270. Returns locator description previously set with `locator.describe()`. Returns `null` if no custom
  14271. description has been set.
  14272. **Usage**
  14273. ```py
  14274. button = page.get_by_role(\"button\").describe(\"Subscribe button\")
  14275. print(button.description()) # \"Subscribe button\"
  14276. input = page.get_by_role(\"textbox\")
  14277. print(input.description()) # None
  14278. ```
  14279. Returns
  14280. -------
  14281. Union[str, None]
  14282. """
  14283. return mapping.from_maybe_impl(self._impl_obj.description)
  14284. async def bounding_box(
  14285. self,
  14286. *,
  14287. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14288. ) -> typing.Optional[FloatRect]:
  14289. """Locator.bounding_box
  14290. This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
  14291. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
  14292. window.
  14293. **Details**
  14294. Scrolling affects the returned bounding box, similarly to
  14295. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  14296. That means `x` and/or `y` may be negative.
  14297. Elements from child frames return the bounding box relative to the main frame, unlike the
  14298. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  14299. Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
  14300. following snippet should click the center of the element.
  14301. **Usage**
  14302. ```py
  14303. box = await page.get_by_role(\"button\").bounding_box()
  14304. await page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
  14305. ```
  14306. Parameters
  14307. ----------
  14308. timeout : Union[float, None]
  14309. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14310. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14311. Returns
  14312. -------
  14313. Union[{x: float, y: float, width: float, height: float}, None]
  14314. """
  14315. return mapping.from_impl_nullable(
  14316. await self._impl_obj.bounding_box(timeout=to_milliseconds(timeout))
  14317. )
  14318. async def check(
  14319. self,
  14320. *,
  14321. position: typing.Optional[Position] = None,
  14322. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14323. force: typing.Optional[bool] = None,
  14324. no_wait_after: typing.Optional[bool] = None,
  14325. trial: typing.Optional[bool] = None,
  14326. ) -> None:
  14327. """Locator.check
  14328. Ensure that checkbox or radio element is checked.
  14329. **Details**
  14330. Performs the following steps:
  14331. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  14332. checked, this method returns immediately.
  14333. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14334. 1. Scroll the element into view if needed.
  14335. 1. Use `page.mouse` to click in the center of the element.
  14336. 1. Ensure that the element is now checked. If not, this method throws.
  14337. If the element is detached from the DOM at any moment during the action, this method throws.
  14338. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14339. Passing zero timeout disables this.
  14340. **Usage**
  14341. ```py
  14342. await page.get_by_role(\"checkbox\").check()
  14343. ```
  14344. Parameters
  14345. ----------
  14346. position : Union[{x: float, y: float}, None]
  14347. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14348. the element.
  14349. timeout : Union[float, None]
  14350. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14351. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14352. force : Union[bool, None]
  14353. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14354. no_wait_after : Union[bool, None]
  14355. This option has no effect.
  14356. Deprecated: This option has no effect.
  14357. trial : Union[bool, None]
  14358. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14359. to `false`. Useful to wait until the element is ready for the action without performing it.
  14360. """
  14361. return mapping.from_maybe_impl(
  14362. await self._impl_obj.check(
  14363. position=position,
  14364. timeout=to_milliseconds(timeout),
  14365. force=force,
  14366. noWaitAfter=no_wait_after,
  14367. trial=trial,
  14368. )
  14369. )
  14370. async def click(
  14371. self,
  14372. *,
  14373. modifiers: typing.Optional[
  14374. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  14375. ] = None,
  14376. position: typing.Optional[Position] = None,
  14377. delay: typing.Optional[float] = None,
  14378. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  14379. click_count: typing.Optional[int] = None,
  14380. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14381. force: typing.Optional[bool] = None,
  14382. no_wait_after: typing.Optional[bool] = None,
  14383. trial: typing.Optional[bool] = None,
  14384. steps: typing.Optional[int] = None,
  14385. ) -> None:
  14386. """Locator.click
  14387. Click an element.
  14388. **Details**
  14389. This method clicks the element by performing the following steps:
  14390. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14391. 1. Scroll the element into view if needed.
  14392. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  14393. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  14394. If the element is detached from the DOM at any moment during the action, this method throws.
  14395. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14396. Passing zero timeout disables this.
  14397. **Usage**
  14398. Click a button:
  14399. ```py
  14400. await page.get_by_role(\"button\").click()
  14401. ```
  14402. Shift-right-click at a specific position on a canvas:
  14403. ```py
  14404. await page.locator(\"canvas\").click(
  14405. button=\"right\", modifiers=[\"Shift\"], position={\"x\": 23, \"y\": 32}
  14406. )
  14407. ```
  14408. Parameters
  14409. ----------
  14410. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  14411. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  14412. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  14413. "Control" on Windows and Linux and to "Meta" on macOS.
  14414. position : Union[{x: float, y: float}, None]
  14415. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14416. the element.
  14417. delay : Union[float, None]
  14418. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  14419. button : Union["left", "middle", "right", None]
  14420. Defaults to `left`.
  14421. click_count : Union[int, None]
  14422. defaults to 1. See [UIEvent.detail].
  14423. timeout : Union[float, None]
  14424. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14425. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14426. force : Union[bool, None]
  14427. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14428. no_wait_after : Union[bool, None]
  14429. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  14430. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  14431. navigating to inaccessible pages. Defaults to `false`.
  14432. Deprecated: This option will default to `true` in the future.
  14433. trial : Union[bool, None]
  14434. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14435. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  14436. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  14437. are pressed.
  14438. steps : Union[int, None]
  14439. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  14440. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  14441. """
  14442. return mapping.from_maybe_impl(
  14443. await self._impl_obj.click(
  14444. modifiers=mapping.to_impl(modifiers),
  14445. position=position,
  14446. delay=delay,
  14447. button=button,
  14448. clickCount=click_count,
  14449. timeout=to_milliseconds(timeout),
  14450. force=force,
  14451. noWaitAfter=no_wait_after,
  14452. trial=trial,
  14453. steps=steps,
  14454. )
  14455. )
  14456. async def dblclick(
  14457. self,
  14458. *,
  14459. modifiers: typing.Optional[
  14460. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  14461. ] = None,
  14462. position: typing.Optional[Position] = None,
  14463. delay: typing.Optional[float] = None,
  14464. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  14465. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14466. force: typing.Optional[bool] = None,
  14467. no_wait_after: typing.Optional[bool] = None,
  14468. trial: typing.Optional[bool] = None,
  14469. steps: typing.Optional[int] = None,
  14470. ) -> None:
  14471. """Locator.dblclick
  14472. Double-click an element.
  14473. **Details**
  14474. This method double clicks the element by performing the following steps:
  14475. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14476. 1. Scroll the element into view if needed.
  14477. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  14478. If the element is detached from the DOM at any moment during the action, this method throws.
  14479. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14480. Passing zero timeout disables this.
  14481. **NOTE** `element.dblclick()` dispatches two `click` events and a single `dblclick` event.
  14482. Parameters
  14483. ----------
  14484. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  14485. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  14486. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  14487. "Control" on Windows and Linux and to "Meta" on macOS.
  14488. position : Union[{x: float, y: float}, None]
  14489. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14490. the element.
  14491. delay : Union[float, None]
  14492. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  14493. button : Union["left", "middle", "right", None]
  14494. Defaults to `left`.
  14495. timeout : Union[float, None]
  14496. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14497. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14498. force : Union[bool, None]
  14499. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14500. no_wait_after : Union[bool, None]
  14501. This option has no effect.
  14502. Deprecated: This option has no effect.
  14503. trial : Union[bool, None]
  14504. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14505. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  14506. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  14507. are pressed.
  14508. steps : Union[int, None]
  14509. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  14510. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  14511. """
  14512. return mapping.from_maybe_impl(
  14513. await self._impl_obj.dblclick(
  14514. modifiers=mapping.to_impl(modifiers),
  14515. position=position,
  14516. delay=delay,
  14517. button=button,
  14518. timeout=to_milliseconds(timeout),
  14519. force=force,
  14520. noWaitAfter=no_wait_after,
  14521. trial=trial,
  14522. steps=steps,
  14523. )
  14524. )
  14525. async def dispatch_event(
  14526. self,
  14527. type: str,
  14528. event_init: typing.Optional[typing.Dict] = None,
  14529. *,
  14530. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14531. ) -> None:
  14532. """Locator.dispatch_event
  14533. Programmatically dispatch an event on the matching element.
  14534. **Usage**
  14535. ```py
  14536. await locator.dispatch_event(\"click\")
  14537. ```
  14538. **Details**
  14539. The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
  14540. `click` is dispatched. This is equivalent to calling
  14541. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  14542. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  14543. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  14544. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  14545. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  14546. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  14547. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  14548. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  14549. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  14550. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  14551. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  14552. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  14553. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  14554. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  14555. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  14556. ```py
  14557. data_transfer = await page.evaluate_handle(\"new DataTransfer()\")
  14558. await locator.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
  14559. ```
  14560. Parameters
  14561. ----------
  14562. type : str
  14563. DOM event type: `"click"`, `"dragstart"`, etc.
  14564. event_init : Union[Dict, None]
  14565. Optional event-specific initialization properties.
  14566. timeout : Union[float, None]
  14567. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14568. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14569. """
  14570. return mapping.from_maybe_impl(
  14571. await self._impl_obj.dispatch_event(
  14572. type=type,
  14573. eventInit=mapping.to_impl(event_init),
  14574. timeout=to_milliseconds(timeout),
  14575. )
  14576. )
  14577. async def evaluate(
  14578. self,
  14579. expression: str,
  14580. arg: typing.Optional[typing.Any] = None,
  14581. *,
  14582. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14583. ) -> typing.Any:
  14584. """Locator.evaluate
  14585. Execute JavaScript code in the page, taking the matching element as an argument.
  14586. **Details**
  14587. Returns the return value of `expression`, called with the matching element as a first argument, and `arg` as a
  14588. second argument.
  14589. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  14590. If `expression` throws or rejects, this method throws.
  14591. **Usage**
  14592. Passing argument to `expression`:
  14593. ```py
  14594. result = await page.get_by_testid(\"myId\").evaluate(\"(element, [x, y]) => element.textContent + ' ' + x * y\", [7, 8])
  14595. print(result) # prints \"myId text 56\"
  14596. ```
  14597. Parameters
  14598. ----------
  14599. expression : str
  14600. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  14601. function is automatically invoked.
  14602. arg : Union[Any, None]
  14603. Optional argument to pass to `expression`.
  14604. timeout : Union[float, None]
  14605. Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
  14606. evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  14607. Returns
  14608. -------
  14609. Any
  14610. """
  14611. return mapping.from_maybe_impl(
  14612. await self._impl_obj.evaluate(
  14613. expression=expression,
  14614. arg=mapping.to_impl(arg),
  14615. timeout=to_milliseconds(timeout),
  14616. )
  14617. )
  14618. async def evaluate_all(
  14619. self, expression: str, arg: typing.Optional[typing.Any] = None
  14620. ) -> typing.Any:
  14621. """Locator.evaluate_all
  14622. Execute JavaScript code in the page, taking all matching elements as an argument.
  14623. **Details**
  14624. Returns the return value of `expression`, called with an array of all matching elements as a first argument, and
  14625. `arg` as a second argument.
  14626. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  14627. If `expression` throws or rejects, this method throws.
  14628. **Usage**
  14629. ```py
  14630. locator = page.locator(\"div\")
  14631. more_than_ten = await locator.evaluate_all(\"(divs, min) => divs.length > min\", 10)
  14632. ```
  14633. Parameters
  14634. ----------
  14635. expression : str
  14636. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  14637. function is automatically invoked.
  14638. arg : Union[Any, None]
  14639. Optional argument to pass to `expression`.
  14640. Returns
  14641. -------
  14642. Any
  14643. """
  14644. return mapping.from_maybe_impl(
  14645. await self._impl_obj.evaluate_all(
  14646. expression=expression, arg=mapping.to_impl(arg)
  14647. )
  14648. )
  14649. async def evaluate_handle(
  14650. self,
  14651. expression: str,
  14652. arg: typing.Optional[typing.Any] = None,
  14653. *,
  14654. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14655. ) -> "JSHandle":
  14656. """Locator.evaluate_handle
  14657. Execute JavaScript code in the page, taking the matching element as an argument, and return a `JSHandle` with the
  14658. result.
  14659. **Details**
  14660. Returns the return value of `expression` as a`JSHandle`, called with the matching element as a first argument, and
  14661. `arg` as a second argument.
  14662. The only difference between `locator.evaluate()` and `locator.evaluate_handle()` is that
  14663. `locator.evaluate_handle()` returns `JSHandle`.
  14664. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  14665. If `expression` throws or rejects, this method throws.
  14666. See `page.evaluate_handle()` for more details.
  14667. Parameters
  14668. ----------
  14669. expression : str
  14670. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  14671. function is automatically invoked.
  14672. arg : Union[Any, None]
  14673. Optional argument to pass to `expression`.
  14674. timeout : Union[float, None]
  14675. Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
  14676. evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  14677. Returns
  14678. -------
  14679. JSHandle
  14680. """
  14681. return mapping.from_impl(
  14682. await self._impl_obj.evaluate_handle(
  14683. expression=expression,
  14684. arg=mapping.to_impl(arg),
  14685. timeout=to_milliseconds(timeout),
  14686. )
  14687. )
  14688. async def fill(
  14689. self,
  14690. value: str,
  14691. *,
  14692. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14693. no_wait_after: typing.Optional[bool] = None,
  14694. force: typing.Optional[bool] = None,
  14695. ) -> None:
  14696. """Locator.fill
  14697. Set a value to the input field.
  14698. **Usage**
  14699. ```py
  14700. await page.get_by_role(\"textbox\").fill(\"example value\")
  14701. ```
  14702. **Details**
  14703. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
  14704. `input` event after filling. Note that you can pass an empty string to clear the input field.
  14705. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  14706. error. However, if the element is inside the `<label>` element that has an associated
  14707. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  14708. instead.
  14709. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  14710. Parameters
  14711. ----------
  14712. value : str
  14713. Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
  14714. timeout : Union[float, None]
  14715. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14716. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14717. no_wait_after : Union[bool, None]
  14718. This option has no effect.
  14719. Deprecated: This option has no effect.
  14720. force : Union[bool, None]
  14721. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14722. """
  14723. return mapping.from_maybe_impl(
  14724. await self._impl_obj.fill(
  14725. value=value,
  14726. timeout=to_milliseconds(timeout),
  14727. noWaitAfter=no_wait_after,
  14728. force=force,
  14729. )
  14730. )
  14731. async def clear(
  14732. self,
  14733. *,
  14734. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  14735. no_wait_after: typing.Optional[bool] = None,
  14736. force: typing.Optional[bool] = None,
  14737. ) -> None:
  14738. """Locator.clear
  14739. Clear the input field.
  14740. **Details**
  14741. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, clears it and triggers an
  14742. `input` event after clearing.
  14743. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  14744. error. However, if the element is inside the `<label>` element that has an associated
  14745. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
  14746. instead.
  14747. **Usage**
  14748. ```py
  14749. await page.get_by_role(\"textbox\").clear()
  14750. ```
  14751. Parameters
  14752. ----------
  14753. timeout : Union[float, None]
  14754. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14755. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14756. no_wait_after : Union[bool, None]
  14757. This option has no effect.
  14758. Deprecated: This option has no effect.
  14759. force : Union[bool, None]
  14760. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14761. """
  14762. return mapping.from_maybe_impl(
  14763. await self._impl_obj.clear(
  14764. timeout=to_milliseconds(timeout), noWaitAfter=no_wait_after, force=force
  14765. )
  14766. )
  14767. def locator(
  14768. self,
  14769. selector_or_locator: typing.Union[str, "Locator"],
  14770. *,
  14771. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  14772. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  14773. has: typing.Optional["Locator"] = None,
  14774. has_not: typing.Optional["Locator"] = None,
  14775. ) -> "Locator":
  14776. """Locator.locator
  14777. The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
  14778. options, similar to `locator.filter()` method.
  14779. [Learn more about locators](https://playwright.dev/python/docs/locators).
  14780. Parameters
  14781. ----------
  14782. selector_or_locator : Union[Locator, str]
  14783. A selector or locator to use when resolving DOM element.
  14784. has_text : Union[Pattern[str], str, None]
  14785. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  14786. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  14787. `<article><div>Playwright</div></article>`.
  14788. has_not_text : Union[Pattern[str], str, None]
  14789. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  14790. When passed a [string], matching is case-insensitive and searches for a substring.
  14791. has : Union[Locator, None]
  14792. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  14793. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  14794. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  14795. the document root. For example, you can find `content` that has `div` in
  14796. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  14797. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  14798. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  14799. has_not : Union[Locator, None]
  14800. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  14801. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  14802. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  14803. Returns
  14804. -------
  14805. Locator
  14806. """
  14807. return mapping.from_impl(
  14808. self._impl_obj.locator(
  14809. selectorOrLocator=selector_or_locator,
  14810. hasText=has_text,
  14811. hasNotText=has_not_text,
  14812. has=has._impl_obj if has else None,
  14813. hasNot=has_not._impl_obj if has_not else None,
  14814. )
  14815. )
  14816. def get_by_alt_text(
  14817. self,
  14818. text: typing.Union[str, typing.Pattern[str]],
  14819. *,
  14820. exact: typing.Optional[bool] = None,
  14821. ) -> "Locator":
  14822. """Locator.get_by_alt_text
  14823. Allows locating elements by their alt text.
  14824. **Usage**
  14825. For example, this method will find the image by alt text \"Playwright logo\":
  14826. ```html
  14827. <img alt='Playwright logo'>
  14828. ```
  14829. ```py
  14830. await page.get_by_alt_text(\"Playwright logo\").click()
  14831. ```
  14832. Parameters
  14833. ----------
  14834. text : Union[Pattern[str], str]
  14835. Text to locate the element for.
  14836. exact : Union[bool, None]
  14837. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  14838. regular expression. Note that exact match still trims whitespace.
  14839. Returns
  14840. -------
  14841. Locator
  14842. """
  14843. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  14844. def get_by_label(
  14845. self,
  14846. text: typing.Union[str, typing.Pattern[str]],
  14847. *,
  14848. exact: typing.Optional[bool] = None,
  14849. ) -> "Locator":
  14850. """Locator.get_by_label
  14851. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  14852. `aria-label` attribute.
  14853. **Usage**
  14854. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  14855. ```html
  14856. <input aria-label=\"Username\">
  14857. <label for=\"password-input\">Password:</label>
  14858. <input id=\"password-input\">
  14859. ```
  14860. ```py
  14861. await page.get_by_label(\"Username\").fill(\"john\")
  14862. await page.get_by_label(\"Password\").fill(\"secret\")
  14863. ```
  14864. Parameters
  14865. ----------
  14866. text : Union[Pattern[str], str]
  14867. Text to locate the element for.
  14868. exact : Union[bool, None]
  14869. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  14870. regular expression. Note that exact match still trims whitespace.
  14871. Returns
  14872. -------
  14873. Locator
  14874. """
  14875. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  14876. def get_by_placeholder(
  14877. self,
  14878. text: typing.Union[str, typing.Pattern[str]],
  14879. *,
  14880. exact: typing.Optional[bool] = None,
  14881. ) -> "Locator":
  14882. """Locator.get_by_placeholder
  14883. Allows locating input elements by the placeholder text.
  14884. **Usage**
  14885. For example, consider the following DOM structure.
  14886. ```html
  14887. <input type=\"email\" placeholder=\"name@example.com\" />
  14888. ```
  14889. You can fill the input after locating it by the placeholder text:
  14890. ```py
  14891. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  14892. ```
  14893. Parameters
  14894. ----------
  14895. text : Union[Pattern[str], str]
  14896. Text to locate the element for.
  14897. exact : Union[bool, None]
  14898. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  14899. regular expression. Note that exact match still trims whitespace.
  14900. Returns
  14901. -------
  14902. Locator
  14903. """
  14904. return mapping.from_impl(
  14905. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  14906. )
  14907. def get_by_role(
  14908. self,
  14909. role: Literal[
  14910. "alert",
  14911. "alertdialog",
  14912. "application",
  14913. "article",
  14914. "banner",
  14915. "blockquote",
  14916. "button",
  14917. "caption",
  14918. "cell",
  14919. "checkbox",
  14920. "code",
  14921. "columnheader",
  14922. "combobox",
  14923. "complementary",
  14924. "contentinfo",
  14925. "definition",
  14926. "deletion",
  14927. "dialog",
  14928. "directory",
  14929. "document",
  14930. "emphasis",
  14931. "feed",
  14932. "figure",
  14933. "form",
  14934. "generic",
  14935. "grid",
  14936. "gridcell",
  14937. "group",
  14938. "heading",
  14939. "img",
  14940. "insertion",
  14941. "link",
  14942. "list",
  14943. "listbox",
  14944. "listitem",
  14945. "log",
  14946. "main",
  14947. "marquee",
  14948. "math",
  14949. "menu",
  14950. "menubar",
  14951. "menuitem",
  14952. "menuitemcheckbox",
  14953. "menuitemradio",
  14954. "meter",
  14955. "navigation",
  14956. "none",
  14957. "note",
  14958. "option",
  14959. "paragraph",
  14960. "presentation",
  14961. "progressbar",
  14962. "radio",
  14963. "radiogroup",
  14964. "region",
  14965. "row",
  14966. "rowgroup",
  14967. "rowheader",
  14968. "scrollbar",
  14969. "search",
  14970. "searchbox",
  14971. "separator",
  14972. "slider",
  14973. "spinbutton",
  14974. "status",
  14975. "strong",
  14976. "subscript",
  14977. "superscript",
  14978. "switch",
  14979. "tab",
  14980. "table",
  14981. "tablist",
  14982. "tabpanel",
  14983. "term",
  14984. "textbox",
  14985. "time",
  14986. "timer",
  14987. "toolbar",
  14988. "tooltip",
  14989. "tree",
  14990. "treegrid",
  14991. "treeitem",
  14992. ],
  14993. *,
  14994. checked: typing.Optional[bool] = None,
  14995. disabled: typing.Optional[bool] = None,
  14996. expanded: typing.Optional[bool] = None,
  14997. include_hidden: typing.Optional[bool] = None,
  14998. level: typing.Optional[int] = None,
  14999. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  15000. pressed: typing.Optional[bool] = None,
  15001. selected: typing.Optional[bool] = None,
  15002. exact: typing.Optional[bool] = None,
  15003. description: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  15004. ) -> "Locator":
  15005. """Locator.get_by_role
  15006. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  15007. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  15008. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  15009. **Usage**
  15010. Consider the following DOM structure.
  15011. ```html
  15012. <h3>Sign up</h3>
  15013. <label>
  15014. <input type=\"checkbox\" /> Subscribe
  15015. </label>
  15016. <br/>
  15017. <button>Submit</button>
  15018. ```
  15019. You can locate each element by its implicit role:
  15020. ```py
  15021. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  15022. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  15023. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  15024. ```
  15025. **Details**
  15026. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  15027. about the ARIA guidelines.
  15028. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  15029. that is recognized by the role selector. You can find all the
  15030. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  15031. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  15032. Parameters
  15033. ----------
  15034. 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"]
  15035. Required aria role.
  15036. checked : Union[bool, None]
  15037. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  15038. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  15039. disabled : Union[bool, None]
  15040. An attribute that is usually set by `aria-disabled` or `disabled`.
  15041. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  15042. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  15043. expanded : Union[bool, None]
  15044. An attribute that is usually set by `aria-expanded`.
  15045. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  15046. include_hidden : Union[bool, None]
  15047. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  15048. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  15049. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  15050. level : Union[int, None]
  15051. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  15052. for `<h1>-<h6>` elements.
  15053. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  15054. name : Union[Pattern[str], str, None]
  15055. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  15056. case-insensitive and searches for a substring, use `exact` to control this behavior.
  15057. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  15058. pressed : Union[bool, None]
  15059. An attribute that is usually set by `aria-pressed`.
  15060. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  15061. selected : Union[bool, None]
  15062. An attribute that is usually set by `aria-selected`.
  15063. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  15064. exact : Union[bool, None]
  15065. Whether `name` and `description` are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored
  15066. when the value is a regular expression. Note that exact match still trims whitespace.
  15067. description : Union[Pattern[str], str, None]
  15068. Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By
  15069. default, matching is case-insensitive and searches for a substring, use `exact` to control this behavior.
  15070. Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  15071. Returns
  15072. -------
  15073. Locator
  15074. """
  15075. return mapping.from_impl(
  15076. self._impl_obj.get_by_role(
  15077. role=role,
  15078. checked=checked,
  15079. disabled=disabled,
  15080. expanded=expanded,
  15081. includeHidden=include_hidden,
  15082. level=level,
  15083. name=name,
  15084. pressed=pressed,
  15085. selected=selected,
  15086. exact=exact,
  15087. description=description,
  15088. )
  15089. )
  15090. def get_by_test_id(
  15091. self, test_id: typing.Union[str, typing.Pattern[str]]
  15092. ) -> "Locator":
  15093. """Locator.get_by_test_id
  15094. Locate element by the test id.
  15095. **Usage**
  15096. Consider the following DOM structure.
  15097. ```html
  15098. <button data-testid=\"directions\">Itinéraire</button>
  15099. ```
  15100. You can locate the element by its test id:
  15101. ```py
  15102. await page.get_by_test_id(\"directions\").click()
  15103. ```
  15104. **Details**
  15105. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  15106. configure a different test id attribute if necessary.
  15107. Parameters
  15108. ----------
  15109. test_id : Union[Pattern[str], str]
  15110. Id to locate the element by.
  15111. Returns
  15112. -------
  15113. Locator
  15114. """
  15115. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  15116. def get_by_text(
  15117. self,
  15118. text: typing.Union[str, typing.Pattern[str]],
  15119. *,
  15120. exact: typing.Optional[bool] = None,
  15121. ) -> "Locator":
  15122. """Locator.get_by_text
  15123. Allows locating elements that contain given text.
  15124. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  15125. filter by the text content.
  15126. **Usage**
  15127. Consider the following DOM structure:
  15128. ```html
  15129. <div>Hello <span>world</span></div>
  15130. <div>Hello</div>
  15131. ```
  15132. You can locate by text substring, exact string, or a regular expression:
  15133. ```py
  15134. # Matches <span>
  15135. page.get_by_text(\"world\")
  15136. # Matches first <div>
  15137. page.get_by_text(\"Hello world\")
  15138. # Matches second <div>
  15139. page.get_by_text(\"Hello\", exact=True)
  15140. # Matches both <div>s
  15141. page.get_by_text(re.compile(\"Hello\"))
  15142. # Matches second <div>
  15143. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  15144. ```
  15145. **Details**
  15146. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  15147. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  15148. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  15149. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  15150. Parameters
  15151. ----------
  15152. text : Union[Pattern[str], str]
  15153. Text to locate the element for.
  15154. exact : Union[bool, None]
  15155. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  15156. regular expression. Note that exact match still trims whitespace.
  15157. Returns
  15158. -------
  15159. Locator
  15160. """
  15161. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  15162. def get_by_title(
  15163. self,
  15164. text: typing.Union[str, typing.Pattern[str]],
  15165. *,
  15166. exact: typing.Optional[bool] = None,
  15167. ) -> "Locator":
  15168. """Locator.get_by_title
  15169. Allows locating elements by their title attribute.
  15170. **Usage**
  15171. Consider the following DOM structure.
  15172. ```html
  15173. <span title='Issues count'>25 issues</span>
  15174. ```
  15175. You can check the issues count after locating it by the title text:
  15176. ```py
  15177. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  15178. ```
  15179. Parameters
  15180. ----------
  15181. text : Union[Pattern[str], str]
  15182. Text to locate the element for.
  15183. exact : Union[bool, None]
  15184. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  15185. regular expression. Note that exact match still trims whitespace.
  15186. Returns
  15187. -------
  15188. Locator
  15189. """
  15190. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  15191. def frame_locator(self, selector: str) -> "FrameLocator":
  15192. """Locator.frame_locator
  15193. When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
  15194. that iframe:
  15195. **Usage**
  15196. ```py
  15197. locator = page.frame_locator(\"iframe\").get_by_text(\"Submit\")
  15198. await locator.click()
  15199. ```
  15200. Parameters
  15201. ----------
  15202. selector : str
  15203. A selector to use when resolving DOM element.
  15204. Returns
  15205. -------
  15206. FrameLocator
  15207. """
  15208. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  15209. async def element_handle(
  15210. self,
  15211. *,
  15212. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15213. ) -> "ElementHandle":
  15214. """Locator.element_handle
  15215. Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
  15216. multiple elements match the locator, throws.
  15217. Parameters
  15218. ----------
  15219. timeout : Union[float, None]
  15220. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15221. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15222. Returns
  15223. -------
  15224. ElementHandle
  15225. """
  15226. return mapping.from_impl(
  15227. await self._impl_obj.element_handle(timeout=to_milliseconds(timeout))
  15228. )
  15229. async def element_handles(self) -> typing.List["ElementHandle"]:
  15230. """Locator.element_handles
  15231. Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
  15232. Returns
  15233. -------
  15234. List[ElementHandle]
  15235. """
  15236. return mapping.from_impl_list(await self._impl_obj.element_handles())
  15237. def nth(self, index: int) -> "Locator":
  15238. """Locator.nth
  15239. Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
  15240. **Usage**
  15241. ```py
  15242. banana = await page.get_by_role(\"listitem\").nth(2)
  15243. ```
  15244. Parameters
  15245. ----------
  15246. index : int
  15247. Returns
  15248. -------
  15249. Locator
  15250. """
  15251. return mapping.from_impl(self._impl_obj.nth(index=index))
  15252. def describe(self, description: str) -> "Locator":
  15253. """Locator.describe
  15254. Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the
  15255. same element.
  15256. **Usage**
  15257. ```py
  15258. button = page.get_by_test_id(\"btn-sub\").describe(\"Subscribe button\")
  15259. await button.click()
  15260. ```
  15261. Parameters
  15262. ----------
  15263. description : str
  15264. Locator description.
  15265. Returns
  15266. -------
  15267. Locator
  15268. """
  15269. return mapping.from_impl(self._impl_obj.describe(description=description))
  15270. def filter(
  15271. self,
  15272. *,
  15273. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  15274. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  15275. has: typing.Optional["Locator"] = None,
  15276. has_not: typing.Optional["Locator"] = None,
  15277. visible: typing.Optional[bool] = None,
  15278. ) -> "Locator":
  15279. """Locator.filter
  15280. This method narrows existing locator according to the options, for example filters by text. It can be chained to
  15281. filter multiple times.
  15282. **Usage**
  15283. ```py
  15284. row_locator = page.locator(\"tr\")
  15285. # ...
  15286. await row_locator.filter(has_text=\"text in column 1\").filter(
  15287. has=page.get_by_role(\"button\", name=\"column 2 button\")
  15288. ).screenshot()
  15289. ```
  15290. Parameters
  15291. ----------
  15292. has_text : Union[Pattern[str], str, None]
  15293. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  15294. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  15295. `<article><div>Playwright</div></article>`.
  15296. has_not_text : Union[Pattern[str], str, None]
  15297. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  15298. When passed a [string], matching is case-insensitive and searches for a substring.
  15299. has : Union[Locator, None]
  15300. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  15301. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  15302. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  15303. the document root. For example, you can find `content` that has `div` in
  15304. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  15305. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  15306. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  15307. has_not : Union[Locator, None]
  15308. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  15309. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  15310. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  15311. visible : Union[bool, None]
  15312. Only matches visible or invisible elements.
  15313. Returns
  15314. -------
  15315. Locator
  15316. """
  15317. return mapping.from_impl(
  15318. self._impl_obj.filter(
  15319. hasText=has_text,
  15320. hasNotText=has_not_text,
  15321. has=has._impl_obj if has else None,
  15322. hasNot=has_not._impl_obj if has_not else None,
  15323. visible=visible,
  15324. )
  15325. )
  15326. def or_(self, locator: "Locator") -> "Locator":
  15327. """Locator.or_
  15328. Creates a locator matching all elements that match one or both of the two locators.
  15329. Note that when both locators match something, the resulting locator will have multiple matches, potentially causing
  15330. a [locator strictness](https://playwright.dev/python/docs/locators#strictness) violation.
  15331. **Usage**
  15332. Consider a scenario where you'd like to click on a \"New email\" button, but sometimes a security settings dialog
  15333. shows up instead. In this case, you can wait for either a \"New email\" button, or a dialog and act accordingly.
  15334. **NOTE** If both \"New email\" button and security dialog appear on screen, the \"or\" locator will match both of them,
  15335. possibly throwing the [\"strict mode violation\" error](https://playwright.dev/python/docs/locators#strictness). In this case, you can use
  15336. `locator.first()` to only match one of them.
  15337. ```py
  15338. new_email = page.get_by_role(\"button\", name=\"New\")
  15339. dialog = page.get_by_text(\"Confirm security settings\")
  15340. await expect(new_email.or_(dialog).first).to_be_visible()
  15341. if (await dialog.is_visible()):
  15342. await page.get_by_role(\"button\", name=\"Dismiss\").click()
  15343. await new_email.click()
  15344. ```
  15345. Parameters
  15346. ----------
  15347. locator : Locator
  15348. Alternative locator to match.
  15349. Returns
  15350. -------
  15351. Locator
  15352. """
  15353. return mapping.from_impl(self._impl_obj.or_(locator=locator._impl_obj))
  15354. def and_(self, locator: "Locator") -> "Locator":
  15355. """Locator.and_
  15356. Creates a locator that matches both this locator and the argument locator.
  15357. **Usage**
  15358. The following example finds a button with a specific title.
  15359. ```py
  15360. button = page.get_by_role(\"button\").and_(page.get_by_title(\"Subscribe\"))
  15361. ```
  15362. Parameters
  15363. ----------
  15364. locator : Locator
  15365. Additional locator to match.
  15366. Returns
  15367. -------
  15368. Locator
  15369. """
  15370. return mapping.from_impl(self._impl_obj.and_(locator=locator._impl_obj))
  15371. async def focus(
  15372. self,
  15373. *,
  15374. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15375. ) -> None:
  15376. """Locator.focus
  15377. Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
  15378. Parameters
  15379. ----------
  15380. timeout : Union[float, None]
  15381. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15382. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15383. """
  15384. return mapping.from_maybe_impl(
  15385. await self._impl_obj.focus(timeout=to_milliseconds(timeout))
  15386. )
  15387. async def blur(
  15388. self,
  15389. *,
  15390. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15391. ) -> None:
  15392. """Locator.blur
  15393. Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur) on the element.
  15394. Parameters
  15395. ----------
  15396. timeout : Union[float, None]
  15397. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15398. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15399. """
  15400. return mapping.from_maybe_impl(
  15401. await self._impl_obj.blur(timeout=to_milliseconds(timeout))
  15402. )
  15403. async def all(self) -> typing.List["Locator"]:
  15404. """Locator.all
  15405. When the locator points to a list of elements, this returns an array of locators, pointing to their respective
  15406. elements.
  15407. **NOTE** `locator.all()` does not wait for elements to match the locator, and instead immediately returns
  15408. whatever is present in the page.
  15409. When the list of elements changes dynamically, `locator.all()` will produce unpredictable and flaky
  15410. results.
  15411. When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before
  15412. calling `locator.all()`.
  15413. **Usage**
  15414. ```py
  15415. for li in await page.get_by_role('listitem').all():
  15416. await li.click();
  15417. ```
  15418. Returns
  15419. -------
  15420. List[Locator]
  15421. """
  15422. return mapping.from_impl_list(await self._impl_obj.all())
  15423. async def count(self) -> int:
  15424. """Locator.count
  15425. Returns the number of elements matching the locator.
  15426. **NOTE** If you need to assert the number of elements on the page, prefer `locator_assertions.to_have_count()`
  15427. to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15428. **Usage**
  15429. ```py
  15430. count = await page.get_by_role(\"listitem\").count()
  15431. ```
  15432. Returns
  15433. -------
  15434. int
  15435. """
  15436. return mapping.from_maybe_impl(await self._impl_obj.count())
  15437. async def drag_to(
  15438. self,
  15439. target: "Locator",
  15440. *,
  15441. force: typing.Optional[bool] = None,
  15442. no_wait_after: typing.Optional[bool] = None,
  15443. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15444. trial: typing.Optional[bool] = None,
  15445. source_position: typing.Optional[Position] = None,
  15446. target_position: typing.Optional[Position] = None,
  15447. steps: typing.Optional[int] = None,
  15448. ) -> None:
  15449. """Locator.drag_to
  15450. Drag the source element towards the target element and drop it.
  15451. **Details**
  15452. This method drags the locator to another target locator or target position. It will first move to the source
  15453. element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
  15454. **Usage**
  15455. ```py
  15456. source = page.locator(\"#source\")
  15457. target = page.locator(\"#target\")
  15458. await source.drag_to(target)
  15459. # or specify exact positions relative to the top-left corners of the elements:
  15460. await source.drag_to(
  15461. target,
  15462. source_position={\"x\": 34, \"y\": 7},
  15463. target_position={\"x\": 10, \"y\": 20}
  15464. )
  15465. ```
  15466. Parameters
  15467. ----------
  15468. target : Locator
  15469. Locator of the element to drag to.
  15470. force : Union[bool, None]
  15471. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  15472. no_wait_after : Union[bool, None]
  15473. This option has no effect.
  15474. Deprecated: This option has no effect.
  15475. timeout : Union[float, None]
  15476. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15477. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15478. trial : Union[bool, None]
  15479. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  15480. to `false`. Useful to wait until the element is ready for the action without performing it.
  15481. source_position : Union[{x: float, y: float}, None]
  15482. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  15483. specified, some visible point of the element is used.
  15484. target_position : Union[{x: float, y: float}, None]
  15485. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  15486. specified, some visible point of the element is used.
  15487. steps : Union[int, None]
  15488. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  15489. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  15490. """
  15491. return mapping.from_maybe_impl(
  15492. await self._impl_obj.drag_to(
  15493. target=target._impl_obj,
  15494. force=force,
  15495. noWaitAfter=no_wait_after,
  15496. timeout=to_milliseconds(timeout),
  15497. trial=trial,
  15498. sourcePosition=source_position,
  15499. targetPosition=target_position,
  15500. steps=steps,
  15501. )
  15502. )
  15503. async def drop(
  15504. self,
  15505. payload: DropPayload,
  15506. *,
  15507. position: typing.Optional[Position] = None,
  15508. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15509. ) -> None:
  15510. """Locator.drop
  15511. Simulate an external drag-and-drop of files or clipboard-like data onto this locator.
  15512. **Details**
  15513. Dispatches the native `dragenter`, `dragover`, and `drop` events at the center of the target element with a
  15514. synthetic [DataTransfer] carrying the provided files and/or data entries. Works cross-browser by constructing the
  15515. [DataTransfer] in the page context.
  15516. If the target element's `dragover` listener does not call `preventDefault()`, the target is considered to have
  15517. rejected the drop: Playwright dispatches `dragleave` and this method throws.
  15518. **Usage**
  15519. Drop a file buffer onto an upload area:
  15520. Drop plain text and a URL together:
  15521. Parameters
  15522. ----------
  15523. payload : {files: Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}, None], data: Union[Dict[str, str], None]}
  15524. Data to drop onto the target. Provide `files` (file paths or in-memory buffers), `data` (a mime-type → string map
  15525. for clipboard-like content such as `text/plain`, `text/html`, `text/uri-list`), or both.
  15526. position : Union[{x: float, y: float}, None]
  15527. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  15528. the element.
  15529. timeout : Union[float, None]
  15530. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15531. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15532. """
  15533. return mapping.from_maybe_impl(
  15534. await self._impl_obj.drop(
  15535. payload=payload, position=position, timeout=to_milliseconds(timeout)
  15536. )
  15537. )
  15538. async def get_attribute(
  15539. self,
  15540. name: str,
  15541. *,
  15542. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15543. ) -> typing.Optional[str]:
  15544. """Locator.get_attribute
  15545. Returns the matching element's attribute value.
  15546. **NOTE** If you need to assert an element's attribute, prefer `locator_assertions.to_have_attribute()` to
  15547. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15548. Parameters
  15549. ----------
  15550. name : str
  15551. Attribute name to get the value for.
  15552. timeout : Union[float, None]
  15553. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15554. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15555. Returns
  15556. -------
  15557. Union[str, None]
  15558. """
  15559. return mapping.from_maybe_impl(
  15560. await self._impl_obj.get_attribute(
  15561. name=name, timeout=to_milliseconds(timeout)
  15562. )
  15563. )
  15564. async def hover(
  15565. self,
  15566. *,
  15567. modifiers: typing.Optional[
  15568. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  15569. ] = None,
  15570. position: typing.Optional[Position] = None,
  15571. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15572. no_wait_after: typing.Optional[bool] = None,
  15573. force: typing.Optional[bool] = None,
  15574. trial: typing.Optional[bool] = None,
  15575. ) -> None:
  15576. """Locator.hover
  15577. Hover over the matching element.
  15578. **Usage**
  15579. ```py
  15580. await page.get_by_role(\"link\").hover()
  15581. ```
  15582. **Details**
  15583. This method hovers over the element by performing the following steps:
  15584. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  15585. 1. Scroll the element into view if needed.
  15586. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  15587. If the element is detached from the DOM at any moment during the action, this method throws.
  15588. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  15589. Passing zero timeout disables this.
  15590. Parameters
  15591. ----------
  15592. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  15593. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  15594. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  15595. "Control" on Windows and Linux and to "Meta" on macOS.
  15596. position : Union[{x: float, y: float}, None]
  15597. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  15598. the element.
  15599. timeout : Union[float, None]
  15600. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15601. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15602. no_wait_after : Union[bool, None]
  15603. This option has no effect.
  15604. Deprecated: This option has no effect.
  15605. force : Union[bool, None]
  15606. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  15607. trial : Union[bool, None]
  15608. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  15609. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  15610. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  15611. are pressed.
  15612. """
  15613. return mapping.from_maybe_impl(
  15614. await self._impl_obj.hover(
  15615. modifiers=mapping.to_impl(modifiers),
  15616. position=position,
  15617. timeout=to_milliseconds(timeout),
  15618. noWaitAfter=no_wait_after,
  15619. force=force,
  15620. trial=trial,
  15621. )
  15622. )
  15623. async def inner_html(
  15624. self,
  15625. *,
  15626. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15627. ) -> str:
  15628. """Locator.inner_html
  15629. Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
  15630. Parameters
  15631. ----------
  15632. timeout : Union[float, None]
  15633. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15634. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15635. Returns
  15636. -------
  15637. str
  15638. """
  15639. return mapping.from_maybe_impl(
  15640. await self._impl_obj.inner_html(timeout=to_milliseconds(timeout))
  15641. )
  15642. async def inner_text(
  15643. self,
  15644. *,
  15645. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15646. ) -> str:
  15647. """Locator.inner_text
  15648. Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
  15649. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
  15650. `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15651. Parameters
  15652. ----------
  15653. timeout : Union[float, None]
  15654. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15655. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15656. Returns
  15657. -------
  15658. str
  15659. """
  15660. return mapping.from_maybe_impl(
  15661. await self._impl_obj.inner_text(timeout=to_milliseconds(timeout))
  15662. )
  15663. async def input_value(
  15664. self,
  15665. *,
  15666. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15667. ) -> str:
  15668. """Locator.input_value
  15669. Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
  15670. **NOTE** If you need to assert input value, prefer `locator_assertions.to_have_value()` to avoid flakiness.
  15671. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15672. **Usage**
  15673. ```py
  15674. value = await page.get_by_role(\"textbox\").input_value()
  15675. ```
  15676. **Details**
  15677. Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
  15678. element that has an associated
  15679. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  15680. control.
  15681. Parameters
  15682. ----------
  15683. timeout : Union[float, None]
  15684. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15685. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15686. Returns
  15687. -------
  15688. str
  15689. """
  15690. return mapping.from_maybe_impl(
  15691. await self._impl_obj.input_value(timeout=to_milliseconds(timeout))
  15692. )
  15693. async def is_checked(
  15694. self,
  15695. *,
  15696. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15697. ) -> bool:
  15698. """Locator.is_checked
  15699. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  15700. **NOTE** If you need to assert that checkbox is checked, prefer `locator_assertions.to_be_checked()` to avoid
  15701. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15702. **Usage**
  15703. ```py
  15704. checked = await page.get_by_role(\"checkbox\").is_checked()
  15705. ```
  15706. Parameters
  15707. ----------
  15708. timeout : Union[float, None]
  15709. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15710. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15711. Returns
  15712. -------
  15713. bool
  15714. """
  15715. return mapping.from_maybe_impl(
  15716. await self._impl_obj.is_checked(timeout=to_milliseconds(timeout))
  15717. )
  15718. async def is_disabled(
  15719. self,
  15720. *,
  15721. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15722. ) -> bool:
  15723. """Locator.is_disabled
  15724. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  15725. **NOTE** If you need to assert that an element is disabled, prefer `locator_assertions.to_be_disabled()` to
  15726. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15727. **Usage**
  15728. ```py
  15729. disabled = await page.get_by_role(\"button\").is_disabled()
  15730. ```
  15731. Parameters
  15732. ----------
  15733. timeout : Union[float, None]
  15734. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15735. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15736. Returns
  15737. -------
  15738. bool
  15739. """
  15740. return mapping.from_maybe_impl(
  15741. await self._impl_obj.is_disabled(timeout=to_milliseconds(timeout))
  15742. )
  15743. async def is_editable(
  15744. self,
  15745. *,
  15746. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15747. ) -> bool:
  15748. """Locator.is_editable
  15749. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable). If the target element is not an `<input>`,
  15750. `<textarea>`, `<select>`, `[contenteditable]` and does not have a role allowing `[aria-readonly]`, this method
  15751. throws an error.
  15752. **NOTE** If you need to assert that an element is editable, prefer `locator_assertions.to_be_editable()` to
  15753. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15754. **Usage**
  15755. ```py
  15756. editable = await page.get_by_role(\"textbox\").is_editable()
  15757. ```
  15758. Parameters
  15759. ----------
  15760. timeout : Union[float, None]
  15761. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15762. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15763. Returns
  15764. -------
  15765. bool
  15766. """
  15767. return mapping.from_maybe_impl(
  15768. await self._impl_obj.is_editable(timeout=to_milliseconds(timeout))
  15769. )
  15770. async def is_enabled(
  15771. self,
  15772. *,
  15773. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15774. ) -> bool:
  15775. """Locator.is_enabled
  15776. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  15777. **NOTE** If you need to assert that an element is enabled, prefer `locator_assertions.to_be_enabled()` to
  15778. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15779. **Usage**
  15780. ```py
  15781. enabled = await page.get_by_role(\"button\").is_enabled()
  15782. ```
  15783. Parameters
  15784. ----------
  15785. timeout : Union[float, None]
  15786. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15787. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15788. Returns
  15789. -------
  15790. bool
  15791. """
  15792. return mapping.from_maybe_impl(
  15793. await self._impl_obj.is_enabled(timeout=to_milliseconds(timeout))
  15794. )
  15795. async def is_hidden(
  15796. self,
  15797. *,
  15798. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15799. ) -> bool:
  15800. """Locator.is_hidden
  15801. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
  15802. **NOTE** If you need to assert that element is hidden, prefer `locator_assertions.to_be_hidden()` to avoid
  15803. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15804. **Usage**
  15805. ```py
  15806. hidden = await page.get_by_role(\"button\").is_hidden()
  15807. ```
  15808. Parameters
  15809. ----------
  15810. timeout : Union[float, None]
  15811. Deprecated: This option is ignored. `locator.is_hidden()` does not wait for the element to become hidden and returns immediately.
  15812. Returns
  15813. -------
  15814. bool
  15815. """
  15816. return mapping.from_maybe_impl(
  15817. await self._impl_obj.is_hidden(timeout=to_milliseconds(timeout))
  15818. )
  15819. async def is_visible(
  15820. self,
  15821. *,
  15822. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15823. ) -> bool:
  15824. """Locator.is_visible
  15825. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  15826. **NOTE** If you need to assert that element is visible, prefer `locator_assertions.to_be_visible()` to avoid
  15827. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  15828. **Usage**
  15829. ```py
  15830. visible = await page.get_by_role(\"button\").is_visible()
  15831. ```
  15832. Parameters
  15833. ----------
  15834. timeout : Union[float, None]
  15835. Deprecated: This option is ignored. `locator.is_visible()` does not wait for the element to become visible and returns immediately.
  15836. Returns
  15837. -------
  15838. bool
  15839. """
  15840. return mapping.from_maybe_impl(
  15841. await self._impl_obj.is_visible(timeout=to_milliseconds(timeout))
  15842. )
  15843. async def press(
  15844. self,
  15845. key: str,
  15846. *,
  15847. delay: typing.Optional[float] = None,
  15848. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15849. no_wait_after: typing.Optional[bool] = None,
  15850. ) -> None:
  15851. """Locator.press
  15852. Focuses the matching element and presses a combination of the keys.
  15853. **Usage**
  15854. ```py
  15855. await page.get_by_role(\"textbox\").press(\"Backspace\")
  15856. ```
  15857. **Details**
  15858. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  15859. `key` can specify the intended
  15860. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  15861. to generate the text for. A superset of the `key` values can be found
  15862. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  15863. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  15864. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  15865. etc.
  15866. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  15867. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  15868. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  15869. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  15870. texts.
  15871. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  15872. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  15873. Parameters
  15874. ----------
  15875. key : str
  15876. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  15877. delay : Union[float, None]
  15878. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  15879. timeout : Union[float, None]
  15880. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15881. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15882. no_wait_after : Union[bool, None]
  15883. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  15884. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  15885. navigating to inaccessible pages. Defaults to `false`.
  15886. Deprecated: This option will default to `true` in the future.
  15887. """
  15888. return mapping.from_maybe_impl(
  15889. await self._impl_obj.press(
  15890. key=key,
  15891. delay=delay,
  15892. timeout=to_milliseconds(timeout),
  15893. noWaitAfter=no_wait_after,
  15894. )
  15895. )
  15896. async def screenshot(
  15897. self,
  15898. *,
  15899. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15900. type: typing.Optional[Literal["jpeg", "png"]] = None,
  15901. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  15902. quality: typing.Optional[int] = None,
  15903. omit_background: typing.Optional[bool] = None,
  15904. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  15905. caret: typing.Optional[Literal["hide", "initial"]] = None,
  15906. scale: typing.Optional[Literal["css", "device"]] = None,
  15907. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  15908. mask_color: typing.Optional[str] = None,
  15909. style: typing.Optional[str] = None,
  15910. ) -> bytes:
  15911. """Locator.screenshot
  15912. Take a screenshot of the element matching the locator.
  15913. **Usage**
  15914. ```py
  15915. await page.get_by_role(\"link\").screenshot()
  15916. ```
  15917. Disable animations and save screenshot to a file:
  15918. ```py
  15919. await page.get_by_role(\"link\").screenshot(animations=\"disabled\", path=\"link.png\")
  15920. ```
  15921. **Details**
  15922. This method captures a screenshot of the page, clipped to the size and position of a particular element matching
  15923. the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
  15924. element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
  15925. This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
  15926. a screenshot. If the element is detached from DOM, the method throws an error.
  15927. Returns the buffer with the captured screenshot.
  15928. Parameters
  15929. ----------
  15930. timeout : Union[float, None]
  15931. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  15932. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  15933. type : Union["jpeg", "png", None]
  15934. Specify screenshot type, defaults to `png`.
  15935. path : Union[pathlib.Path, str, None]
  15936. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  15937. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  15938. won't be saved to the disk.
  15939. quality : Union[int, None]
  15940. The quality of the image, between 0-100. Not applicable to `png` images.
  15941. omit_background : Union[bool, None]
  15942. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  15943. Defaults to `false`.
  15944. animations : Union["allow", "disabled", None]
  15945. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  15946. treatment depending on their duration:
  15947. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  15948. - infinite animations are canceled to initial state, and then played over after the screenshot.
  15949. Defaults to `"allow"` that leaves animations untouched.
  15950. caret : Union["hide", "initial", None]
  15951. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  15952. changed. Defaults to `"hide"`.
  15953. scale : Union["css", "device", None]
  15954. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  15955. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  15956. screenshots of high-dpi devices will be twice as large or even larger.
  15957. Defaults to `"device"`.
  15958. mask : Union[Sequence[Locator], None]
  15959. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  15960. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  15961. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  15962. that.
  15963. mask_color : Union[str, None]
  15964. Specify the color of the overlay box for masked elements, in
  15965. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  15966. style : Union[str, None]
  15967. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  15968. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  15969. the Shadow DOM and applies to the inner frames.
  15970. Returns
  15971. -------
  15972. bytes
  15973. """
  15974. return mapping.from_maybe_impl(
  15975. await self._impl_obj.screenshot(
  15976. timeout=to_milliseconds(timeout),
  15977. type=type,
  15978. path=path,
  15979. quality=quality,
  15980. omitBackground=omit_background,
  15981. animations=animations,
  15982. caret=caret,
  15983. scale=scale,
  15984. mask=mapping.to_impl(mask),
  15985. maskColor=mask_color,
  15986. style=style,
  15987. )
  15988. )
  15989. async def aria_snapshot(
  15990. self,
  15991. *,
  15992. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  15993. depth: typing.Optional[int] = None,
  15994. mode: typing.Optional[Literal["ai", "default"]] = None,
  15995. boxes: typing.Optional[bool] = None,
  15996. ) -> str:
  15997. """Locator.aria_snapshot
  15998. Captures the aria snapshot of the given element. Read more about [aria snapshots](https://playwright.dev/python/docs/aria-snapshots) and
  15999. `locator_assertions.to_match_aria_snapshot()` for the corresponding assertion.
  16000. **Usage**
  16001. ```py
  16002. await page.get_by_role(\"link\").aria_snapshot()
  16003. ```
  16004. **Details**
  16005. This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of
  16006. the element and its children. The snapshot can be used to assert the state of the element in the test, or to
  16007. compare it to state in the future.
  16008. The ARIA snapshot is represented using [YAML](https://yaml.org/spec/1.2.2/) markup language:
  16009. - The keys of the objects are the roles and optional accessible names of the elements.
  16010. - The values are either text content or an array of child elements.
  16011. - Generic static text can be represented with the `text` key.
  16012. Below is the HTML markup and the respective ARIA snapshot:
  16013. ```html
  16014. <ul aria-label=\"Links\">
  16015. <li><a href=\"/\">Home</a></li>
  16016. <li><a href=\"/about\">About</a></li>
  16017. <ul>
  16018. ```
  16019. ```yml
  16020. - list \"Links\":
  16021. - listitem:
  16022. - link \"Home\"
  16023. - listitem:
  16024. - link \"About\"
  16025. ```
  16026. An AI-optimized snapshot, controlled by `mode`, is different from a default snapshot:
  16027. 1. Includes element references `[ref=e2]`. 2. Does not wait for an element matching the locator, and throws when
  16028. no elements match. 3. Includes snapshots of `<iframe>`s inside the target.
  16029. Parameters
  16030. ----------
  16031. timeout : Union[float, None]
  16032. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16033. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16034. depth : Union[int, None]
  16035. When specified, limits the depth of the snapshot.
  16036. mode : Union["ai", "default", None]
  16037. When set to `"ai"`, returns a snapshot optimized for AI consumption. Defaults to `"default"`. See details for more
  16038. information.
  16039. boxes : Union[bool, None]
  16040. When `true`, appends each element's bounding box as `[box=x,y,width,height]` to the snapshot. Coordinates are
  16041. relative to the viewport, in CSS pixels, as returned by
  16042. [`Element.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  16043. Defaults to `false`.
  16044. Returns
  16045. -------
  16046. str
  16047. """
  16048. return mapping.from_maybe_impl(
  16049. await self._impl_obj.aria_snapshot(
  16050. timeout=to_milliseconds(timeout), depth=depth, mode=mode, boxes=boxes
  16051. )
  16052. )
  16053. async def normalize(self) -> "Locator":
  16054. """Locator.normalize
  16055. Returns a new locator that uses best practices for referencing the matched element, prioritizing test ids, aria
  16056. roles, and other user-facing attributes over CSS selectors. This is useful for converting implementation-detail
  16057. selectors into more resilient, human-readable locators.
  16058. Returns
  16059. -------
  16060. Locator
  16061. """
  16062. return mapping.from_impl(await self._impl_obj.normalize())
  16063. async def scroll_into_view_if_needed(
  16064. self,
  16065. *,
  16066. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16067. ) -> None:
  16068. """Locator.scroll_into_view_if_needed
  16069. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
  16070. it is completely visible as defined by
  16071. [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
  16072. See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  16073. Parameters
  16074. ----------
  16075. timeout : Union[float, None]
  16076. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16077. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16078. """
  16079. return mapping.from_maybe_impl(
  16080. await self._impl_obj.scroll_into_view_if_needed(
  16081. timeout=to_milliseconds(timeout)
  16082. )
  16083. )
  16084. async def select_option(
  16085. self,
  16086. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  16087. *,
  16088. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  16089. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  16090. element: typing.Optional[
  16091. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  16092. ] = None,
  16093. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16094. no_wait_after: typing.Optional[bool] = None,
  16095. force: typing.Optional[bool] = None,
  16096. ) -> typing.List[str]:
  16097. """Locator.select_option
  16098. Selects option or options in `<select>`.
  16099. **Details**
  16100. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
  16101. the `<select>` element and selects these options.
  16102. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  16103. the `<label>` element that has an associated
  16104. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  16105. instead.
  16106. Returns the array of option values that have been successfully selected.
  16107. Triggers a `change` and `input` event once all the provided options have been selected.
  16108. **Usage**
  16109. ```html
  16110. <select multiple>
  16111. <option value=\"red\">Red</option>
  16112. <option value=\"green\">Green</option>
  16113. <option value=\"blue\">Blue</option>
  16114. </select>
  16115. ```
  16116. ```py
  16117. # single selection matching the value or label
  16118. await element.select_option(\"blue\")
  16119. # single selection matching the label
  16120. await element.select_option(label=\"blue\")
  16121. # multiple selection for blue, red and second option
  16122. await element.select_option(value=[\"red\", \"green\", \"blue\"])
  16123. ```
  16124. Parameters
  16125. ----------
  16126. value : Union[Sequence[str], str, None]
  16127. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  16128. otherwise only the first option matching one of the passed options is selected. Optional.
  16129. index : Union[Sequence[int], int, None]
  16130. Options to select by index. Optional.
  16131. label : Union[Sequence[str], str, None]
  16132. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  16133. otherwise only the first option matching one of the passed options is selected. Optional.
  16134. element : Union[ElementHandle, Sequence[ElementHandle], None]
  16135. Option elements to select. Optional.
  16136. timeout : Union[float, None]
  16137. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16138. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16139. no_wait_after : Union[bool, None]
  16140. This option has no effect.
  16141. Deprecated: This option has no effect.
  16142. force : Union[bool, None]
  16143. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  16144. Returns
  16145. -------
  16146. List[str]
  16147. """
  16148. return mapping.from_maybe_impl(
  16149. await self._impl_obj.select_option(
  16150. value=mapping.to_impl(value),
  16151. index=mapping.to_impl(index),
  16152. label=mapping.to_impl(label),
  16153. element=mapping.to_impl(element),
  16154. timeout=to_milliseconds(timeout),
  16155. noWaitAfter=no_wait_after,
  16156. force=force,
  16157. )
  16158. )
  16159. async def select_text(
  16160. self,
  16161. *,
  16162. force: typing.Optional[bool] = None,
  16163. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16164. ) -> None:
  16165. """Locator.select_text
  16166. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
  16167. text content.
  16168. If the element is inside the `<label>` element that has an associated
  16169. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
  16170. the control instead.
  16171. Parameters
  16172. ----------
  16173. force : Union[bool, None]
  16174. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  16175. timeout : Union[float, None]
  16176. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16177. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16178. """
  16179. return mapping.from_maybe_impl(
  16180. await self._impl_obj.select_text(
  16181. force=force, timeout=to_milliseconds(timeout)
  16182. )
  16183. )
  16184. async def set_input_files(
  16185. self,
  16186. files: typing.Union[
  16187. str,
  16188. pathlib.Path,
  16189. FilePayload,
  16190. typing.Sequence[typing.Union[str, pathlib.Path]],
  16191. typing.Sequence[FilePayload],
  16192. ],
  16193. *,
  16194. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16195. no_wait_after: typing.Optional[bool] = None,
  16196. ) -> None:
  16197. """Locator.set_input_files
  16198. Upload file or multiple files into `<input type=file>`. For inputs with a `[webkitdirectory]` attribute, only a
  16199. single directory path is supported.
  16200. **Usage**
  16201. ```py
  16202. # Select one file
  16203. await page.get_by_label(\"Upload file\").set_input_files('myfile.pdf')
  16204. # Select multiple files
  16205. await page.get_by_label(\"Upload files\").set_input_files(['file1.txt', 'file2.txt'])
  16206. # Select a directory
  16207. await page.get_by_label(\"Upload directory\").set_input_files('mydir')
  16208. # Remove all the selected files
  16209. await page.get_by_label(\"Upload file\").set_input_files([])
  16210. # Upload buffer from memory
  16211. await page.get_by_label(\"Upload file\").set_input_files(
  16212. files=[
  16213. {\"name\": \"test.txt\", \"mimeType\": \"text/plain\", \"buffer\": b\"this is a test\"}
  16214. ],
  16215. )
  16216. ```
  16217. **Details**
  16218. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  16219. they are resolved relative to the current working directory. For empty array, clears the selected files.
  16220. This method expects `Locator` to point to an
  16221. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  16222. the `<label>` element that has an associated
  16223. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  16224. Parameters
  16225. ----------
  16226. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  16227. timeout : Union[float, None]
  16228. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16229. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16230. no_wait_after : Union[bool, None]
  16231. This option has no effect.
  16232. Deprecated: This option has no effect.
  16233. """
  16234. return mapping.from_maybe_impl(
  16235. await self._impl_obj.set_input_files(
  16236. files=mapping.to_impl(files),
  16237. timeout=to_milliseconds(timeout),
  16238. noWaitAfter=no_wait_after,
  16239. )
  16240. )
  16241. async def tap(
  16242. self,
  16243. *,
  16244. modifiers: typing.Optional[
  16245. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  16246. ] = None,
  16247. position: typing.Optional[Position] = None,
  16248. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16249. force: typing.Optional[bool] = None,
  16250. no_wait_after: typing.Optional[bool] = None,
  16251. trial: typing.Optional[bool] = None,
  16252. ) -> None:
  16253. """Locator.tap
  16254. Perform a tap gesture on the element matching the locator. For examples of emulating other gestures by manually
  16255. dispatching touch events, see the [emulating legacy touch events](https://playwright.dev/python/docs/touch-events) page.
  16256. **Details**
  16257. This method taps the element by performing the following steps:
  16258. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  16259. 1. Scroll the element into view if needed.
  16260. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  16261. If the element is detached from the DOM at any moment during the action, this method throws.
  16262. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  16263. Passing zero timeout disables this.
  16264. **NOTE** `element.tap()` requires that the `hasTouch` option of the browser context be set to true.
  16265. Parameters
  16266. ----------
  16267. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  16268. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  16269. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  16270. "Control" on Windows and Linux and to "Meta" on macOS.
  16271. position : Union[{x: float, y: float}, None]
  16272. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  16273. the element.
  16274. timeout : Union[float, None]
  16275. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16276. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16277. force : Union[bool, None]
  16278. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  16279. no_wait_after : Union[bool, None]
  16280. This option has no effect.
  16281. Deprecated: This option has no effect.
  16282. trial : Union[bool, None]
  16283. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  16284. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  16285. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  16286. are pressed.
  16287. """
  16288. return mapping.from_maybe_impl(
  16289. await self._impl_obj.tap(
  16290. modifiers=mapping.to_impl(modifiers),
  16291. position=position,
  16292. timeout=to_milliseconds(timeout),
  16293. force=force,
  16294. noWaitAfter=no_wait_after,
  16295. trial=trial,
  16296. )
  16297. )
  16298. async def text_content(
  16299. self,
  16300. *,
  16301. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16302. ) -> typing.Optional[str]:
  16303. """Locator.text_content
  16304. Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
  16305. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
  16306. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  16307. Parameters
  16308. ----------
  16309. timeout : Union[float, None]
  16310. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16311. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16312. Returns
  16313. -------
  16314. Union[str, None]
  16315. """
  16316. return mapping.from_maybe_impl(
  16317. await self._impl_obj.text_content(timeout=to_milliseconds(timeout))
  16318. )
  16319. async def type(
  16320. self,
  16321. text: str,
  16322. *,
  16323. delay: typing.Optional[float] = None,
  16324. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16325. no_wait_after: typing.Optional[bool] = None,
  16326. ) -> None:
  16327. """Locator.type
  16328. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  16329. text.
  16330. To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
  16331. **Usage**
  16332. Parameters
  16333. ----------
  16334. text : str
  16335. A text to type into a focused element.
  16336. delay : Union[float, None]
  16337. Time to wait between key presses in milliseconds. Defaults to 0.
  16338. timeout : Union[float, None]
  16339. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16340. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16341. no_wait_after : Union[bool, None]
  16342. This option has no effect.
  16343. Deprecated: This option has no effect.
  16344. """
  16345. return mapping.from_maybe_impl(
  16346. await self._impl_obj.type(
  16347. text=text,
  16348. delay=delay,
  16349. timeout=to_milliseconds(timeout),
  16350. noWaitAfter=no_wait_after,
  16351. )
  16352. )
  16353. async def press_sequentially(
  16354. self,
  16355. text: str,
  16356. *,
  16357. delay: typing.Optional[float] = None,
  16358. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16359. no_wait_after: typing.Optional[bool] = None,
  16360. ) -> None:
  16361. """Locator.press_sequentially
  16362. **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
  16363. there is special keyboard handling on the page.
  16364. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  16365. text.
  16366. To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
  16367. **Usage**
  16368. ```py
  16369. await locator.press_sequentially(\"hello\") # types instantly
  16370. await locator.press_sequentially(\"world\", delay=100) # types slower, like a user
  16371. ```
  16372. An example of typing into a text field and then submitting the form:
  16373. ```py
  16374. locator = page.get_by_label(\"Password\")
  16375. await locator.press_sequentially(\"my password\")
  16376. await locator.press(\"Enter\")
  16377. ```
  16378. Parameters
  16379. ----------
  16380. text : str
  16381. String of characters to sequentially press into a focused element.
  16382. delay : Union[float, None]
  16383. Time to wait between key presses in milliseconds. Defaults to 0.
  16384. timeout : Union[float, None]
  16385. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16386. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16387. no_wait_after : Union[bool, None]
  16388. This option has no effect.
  16389. Deprecated: This option has no effect.
  16390. """
  16391. return mapping.from_maybe_impl(
  16392. await self._impl_obj.press_sequentially(
  16393. text=text,
  16394. delay=delay,
  16395. timeout=to_milliseconds(timeout),
  16396. noWaitAfter=no_wait_after,
  16397. )
  16398. )
  16399. async def uncheck(
  16400. self,
  16401. *,
  16402. position: typing.Optional[Position] = None,
  16403. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16404. force: typing.Optional[bool] = None,
  16405. no_wait_after: typing.Optional[bool] = None,
  16406. trial: typing.Optional[bool] = None,
  16407. ) -> None:
  16408. """Locator.uncheck
  16409. Ensure that checkbox or radio element is unchecked.
  16410. **Usage**
  16411. ```py
  16412. await page.get_by_role(\"checkbox\").uncheck()
  16413. ```
  16414. **Details**
  16415. This method unchecks the element by performing the following steps:
  16416. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  16417. unchecked, this method returns immediately.
  16418. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  16419. 1. Scroll the element into view if needed.
  16420. 1. Use `page.mouse` to click in the center of the element.
  16421. 1. Ensure that the element is now unchecked. If not, this method throws.
  16422. If the element is detached from the DOM at any moment during the action, this method throws.
  16423. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  16424. Passing zero timeout disables this.
  16425. Parameters
  16426. ----------
  16427. position : Union[{x: float, y: float}, None]
  16428. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  16429. the element.
  16430. timeout : Union[float, None]
  16431. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16432. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16433. force : Union[bool, None]
  16434. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  16435. no_wait_after : Union[bool, None]
  16436. This option has no effect.
  16437. Deprecated: This option has no effect.
  16438. trial : Union[bool, None]
  16439. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  16440. to `false`. Useful to wait until the element is ready for the action without performing it.
  16441. """
  16442. return mapping.from_maybe_impl(
  16443. await self._impl_obj.uncheck(
  16444. position=position,
  16445. timeout=to_milliseconds(timeout),
  16446. force=force,
  16447. noWaitAfter=no_wait_after,
  16448. trial=trial,
  16449. )
  16450. )
  16451. async def all_inner_texts(self) -> typing.List[str]:
  16452. """Locator.all_inner_texts
  16453. Returns an array of `node.innerText` values for all matching nodes.
  16454. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
  16455. `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  16456. **Usage**
  16457. ```py
  16458. texts = await page.get_by_role(\"link\").all_inner_texts()
  16459. ```
  16460. Returns
  16461. -------
  16462. List[str]
  16463. """
  16464. return mapping.from_maybe_impl(await self._impl_obj.all_inner_texts())
  16465. async def all_text_contents(self) -> typing.List[str]:
  16466. """Locator.all_text_contents
  16467. Returns an array of `node.textContent` values for all matching nodes.
  16468. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
  16469. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  16470. **Usage**
  16471. ```py
  16472. texts = await page.get_by_role(\"link\").all_text_contents()
  16473. ```
  16474. Returns
  16475. -------
  16476. List[str]
  16477. """
  16478. return mapping.from_maybe_impl(await self._impl_obj.all_text_contents())
  16479. async def wait_for(
  16480. self,
  16481. *,
  16482. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16483. state: typing.Optional[
  16484. Literal["attached", "detached", "hidden", "visible"]
  16485. ] = None,
  16486. ) -> None:
  16487. """Locator.wait_for
  16488. Returns when element specified by locator satisfies the `state` option.
  16489. If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
  16490. `timeout` milliseconds until the condition is met.
  16491. **Usage**
  16492. ```py
  16493. order_sent = page.locator(\"#order-sent\")
  16494. await order_sent.wait_for()
  16495. ```
  16496. Parameters
  16497. ----------
  16498. timeout : Union[float, None]
  16499. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16500. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16501. state : Union["attached", "detached", "hidden", "visible", None]
  16502. Defaults to `'visible'`. Can be either:
  16503. - `'attached'` - wait for element to be present in DOM.
  16504. - `'detached'` - wait for element to not be present in DOM.
  16505. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  16506. without any content or with `display:none` has an empty bounding box and is not considered visible.
  16507. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  16508. `visibility:hidden`. This is opposite to the `'visible'` option.
  16509. """
  16510. return mapping.from_maybe_impl(
  16511. await self._impl_obj.wait_for(timeout=to_milliseconds(timeout), state=state)
  16512. )
  16513. async def set_checked(
  16514. self,
  16515. checked: bool,
  16516. *,
  16517. position: typing.Optional[Position] = None,
  16518. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16519. force: typing.Optional[bool] = None,
  16520. no_wait_after: typing.Optional[bool] = None,
  16521. trial: typing.Optional[bool] = None,
  16522. ) -> None:
  16523. """Locator.set_checked
  16524. Set the state of a checkbox or a radio element.
  16525. **Usage**
  16526. ```py
  16527. await page.get_by_role(\"checkbox\").set_checked(True)
  16528. ```
  16529. **Details**
  16530. This method checks or unchecks an element by performing the following steps:
  16531. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  16532. 1. If the element already has the right checked state, this method returns immediately.
  16533. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  16534. the element is detached during the checks, the whole action is retried.
  16535. 1. Scroll the element into view if needed.
  16536. 1. Use `page.mouse` to click in the center of the element.
  16537. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  16538. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  16539. Passing zero timeout disables this.
  16540. Parameters
  16541. ----------
  16542. checked : bool
  16543. Whether to check or uncheck the checkbox.
  16544. position : Union[{x: float, y: float}, None]
  16545. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  16546. the element.
  16547. timeout : Union[float, None]
  16548. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  16549. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  16550. force : Union[bool, None]
  16551. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  16552. no_wait_after : Union[bool, None]
  16553. This option has no effect.
  16554. Deprecated: This option has no effect.
  16555. trial : Union[bool, None]
  16556. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  16557. to `false`. Useful to wait until the element is ready for the action without performing it.
  16558. """
  16559. return mapping.from_maybe_impl(
  16560. await self._impl_obj.set_checked(
  16561. checked=checked,
  16562. position=position,
  16563. timeout=to_milliseconds(timeout),
  16564. force=force,
  16565. noWaitAfter=no_wait_after,
  16566. trial=trial,
  16567. )
  16568. )
  16569. async def highlight(self, *, style: typing.Optional[str] = None) -> None:
  16570. """Locator.highlight
  16571. Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
  16572. `locator.highlight()`.
  16573. Parameters
  16574. ----------
  16575. style : Union[str, None]
  16576. Additional inline CSS applied to the highlight overlay, e.g. `"outline: 2px dashed red"`.
  16577. """
  16578. return mapping.from_maybe_impl(await self._impl_obj.highlight(style=style))
  16579. async def hide_highlight(self) -> None:
  16580. """Locator.hide_highlight
  16581. Hides the element highlight previously added by `locator.highlight()`.
  16582. """
  16583. return mapping.from_maybe_impl(await self._impl_obj.hide_highlight())
  16584. mapping.register(LocatorImpl, Locator)
  16585. class APIResponse(AsyncBase):
  16586. @property
  16587. def ok(self) -> bool:
  16588. """APIResponse.ok
  16589. Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
  16590. Returns
  16591. -------
  16592. bool
  16593. """
  16594. return mapping.from_maybe_impl(self._impl_obj.ok)
  16595. @property
  16596. def url(self) -> str:
  16597. """APIResponse.url
  16598. Contains the URL of the response.
  16599. Returns
  16600. -------
  16601. str
  16602. """
  16603. return mapping.from_maybe_impl(self._impl_obj.url)
  16604. @property
  16605. def status(self) -> int:
  16606. """APIResponse.status
  16607. Contains the status code of the response (e.g., 200 for a success).
  16608. Returns
  16609. -------
  16610. int
  16611. """
  16612. return mapping.from_maybe_impl(self._impl_obj.status)
  16613. @property
  16614. def status_text(self) -> str:
  16615. """APIResponse.status_text
  16616. Contains the status text of the response (e.g. usually an \"OK\" for a success).
  16617. Returns
  16618. -------
  16619. str
  16620. """
  16621. return mapping.from_maybe_impl(self._impl_obj.status_text)
  16622. @property
  16623. def headers(self) -> typing.Dict[str, str]:
  16624. """APIResponse.headers
  16625. An object with all the response HTTP headers associated with this response.
  16626. Returns
  16627. -------
  16628. Dict[str, str]
  16629. """
  16630. return mapping.from_maybe_impl(self._impl_obj.headers)
  16631. @property
  16632. def headers_array(self) -> typing.List[NameValue]:
  16633. """APIResponse.headers_array
  16634. An array with all the response HTTP headers associated with this response. Header names are not lower-cased.
  16635. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.
  16636. Returns
  16637. -------
  16638. List[{name: str, value: str}]
  16639. """
  16640. return mapping.from_impl_list(self._impl_obj.headers_array)
  16641. async def body(self) -> bytes:
  16642. """APIResponse.body
  16643. Returns the buffer with response body.
  16644. Returns
  16645. -------
  16646. bytes
  16647. """
  16648. return mapping.from_maybe_impl(await self._impl_obj.body())
  16649. async def text(self) -> str:
  16650. """APIResponse.text
  16651. Returns the text representation of response body.
  16652. Returns
  16653. -------
  16654. str
  16655. """
  16656. return mapping.from_maybe_impl(await self._impl_obj.text())
  16657. async def json(self) -> typing.Any:
  16658. """APIResponse.json
  16659. Returns the JSON representation of response body.
  16660. This method will throw if the response body is not parsable via `JSON.parse`.
  16661. Returns
  16662. -------
  16663. Any
  16664. """
  16665. return mapping.from_maybe_impl(await self._impl_obj.json())
  16666. async def dispose(self) -> None:
  16667. """APIResponse.dispose
  16668. Disposes the body of this response. If not called then the body will stay in memory until the context closes.
  16669. """
  16670. return mapping.from_maybe_impl(await self._impl_obj.dispose())
  16671. mapping.register(APIResponseImpl, APIResponse)
  16672. class APIRequestContext(AsyncBase):
  16673. @property
  16674. def tracing(self) -> "Tracing":
  16675. """APIRequestContext.tracing
  16676. Returns
  16677. -------
  16678. Tracing
  16679. """
  16680. return mapping.from_impl(self._impl_obj.tracing)
  16681. async def dispose(self, *, reason: typing.Optional[str] = None) -> None:
  16682. """APIRequestContext.dispose
  16683. All responses returned by `a_pi_request_context.get()` and similar methods are stored in the memory, so that
  16684. you can later call `a_pi_response.body()`.This method discards all its resources, calling any method on
  16685. disposed `APIRequestContext` will throw an exception.
  16686. Parameters
  16687. ----------
  16688. reason : Union[str, None]
  16689. The reason to be reported to the operations interrupted by the context disposal.
  16690. """
  16691. return mapping.from_maybe_impl(await self._impl_obj.dispose(reason=reason))
  16692. async def delete(
  16693. self,
  16694. url: str,
  16695. *,
  16696. params: typing.Optional[
  16697. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  16698. ] = None,
  16699. headers: typing.Optional[typing.Dict[str, str]] = None,
  16700. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  16701. form: typing.Optional[
  16702. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  16703. ] = None,
  16704. multipart: typing.Optional[
  16705. typing.Union[
  16706. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  16707. "FormData",
  16708. ]
  16709. ] = None,
  16710. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16711. fail_on_status_code: typing.Optional[bool] = None,
  16712. ignore_https_errors: typing.Optional[bool] = None,
  16713. max_redirects: typing.Optional[int] = None,
  16714. max_retries: typing.Optional[int] = None,
  16715. ) -> "APIResponse":
  16716. """APIRequestContext.delete
  16717. Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
  16718. response. The method will populate request cookies from the context and update context cookies from the response.
  16719. The method will automatically follow redirects.
  16720. Parameters
  16721. ----------
  16722. url : str
  16723. Target URL.
  16724. params : Union[Dict[str, Union[bool, float, str]], str, None]
  16725. Query parameters to be sent with the URL.
  16726. headers : Union[Dict[str, str], None]
  16727. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  16728. it.
  16729. data : Union[Any, bytes, str, None]
  16730. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  16731. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  16732. header will be set to `application/octet-stream` if not explicitly set.
  16733. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  16734. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  16735. as this request body. If this parameter is specified `content-type` header will be set to
  16736. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  16737. field.
  16738. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  16739. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  16740. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  16741. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  16742. Use `FormData` to send multiple files in the same field.
  16743. timeout : Union[float, None]
  16744. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  16745. fail_on_status_code : Union[bool, None]
  16746. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  16747. codes.
  16748. ignore_https_errors : Union[bool, None]
  16749. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  16750. max_redirects : Union[int, None]
  16751. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  16752. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  16753. max_retries : Union[int, None]
  16754. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  16755. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  16756. Returns
  16757. -------
  16758. APIResponse
  16759. """
  16760. return mapping.from_impl(
  16761. await self._impl_obj.delete(
  16762. url=url,
  16763. params=mapping.to_impl(params),
  16764. headers=mapping.to_impl(headers),
  16765. data=mapping.to_impl(data),
  16766. form=mapping.to_impl(form),
  16767. multipart=mapping.to_impl(multipart),
  16768. timeout=to_milliseconds(timeout),
  16769. failOnStatusCode=fail_on_status_code,
  16770. ignoreHTTPSErrors=ignore_https_errors,
  16771. maxRedirects=max_redirects,
  16772. maxRetries=max_retries,
  16773. )
  16774. )
  16775. async def head(
  16776. self,
  16777. url: str,
  16778. *,
  16779. params: typing.Optional[
  16780. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  16781. ] = None,
  16782. headers: typing.Optional[typing.Dict[str, str]] = None,
  16783. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  16784. form: typing.Optional[
  16785. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  16786. ] = None,
  16787. multipart: typing.Optional[
  16788. typing.Union[
  16789. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  16790. "FormData",
  16791. ]
  16792. ] = None,
  16793. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16794. fail_on_status_code: typing.Optional[bool] = None,
  16795. ignore_https_errors: typing.Optional[bool] = None,
  16796. max_redirects: typing.Optional[int] = None,
  16797. max_retries: typing.Optional[int] = None,
  16798. ) -> "APIResponse":
  16799. """APIRequestContext.head
  16800. Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its
  16801. response. The method will populate request cookies from the context and update context cookies from the response.
  16802. The method will automatically follow redirects.
  16803. Parameters
  16804. ----------
  16805. url : str
  16806. Target URL.
  16807. params : Union[Dict[str, Union[bool, float, str]], str, None]
  16808. Query parameters to be sent with the URL.
  16809. headers : Union[Dict[str, str], None]
  16810. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  16811. it.
  16812. data : Union[Any, bytes, str, None]
  16813. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  16814. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  16815. header will be set to `application/octet-stream` if not explicitly set.
  16816. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  16817. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  16818. as this request body. If this parameter is specified `content-type` header will be set to
  16819. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  16820. field.
  16821. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  16822. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  16823. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  16824. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  16825. Use `FormData` to send multiple files in the same field.
  16826. timeout : Union[float, None]
  16827. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  16828. fail_on_status_code : Union[bool, None]
  16829. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  16830. codes.
  16831. ignore_https_errors : Union[bool, None]
  16832. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  16833. max_redirects : Union[int, None]
  16834. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  16835. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  16836. max_retries : Union[int, None]
  16837. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  16838. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  16839. Returns
  16840. -------
  16841. APIResponse
  16842. """
  16843. return mapping.from_impl(
  16844. await self._impl_obj.head(
  16845. url=url,
  16846. params=mapping.to_impl(params),
  16847. headers=mapping.to_impl(headers),
  16848. data=mapping.to_impl(data),
  16849. form=mapping.to_impl(form),
  16850. multipart=mapping.to_impl(multipart),
  16851. timeout=to_milliseconds(timeout),
  16852. failOnStatusCode=fail_on_status_code,
  16853. ignoreHTTPSErrors=ignore_https_errors,
  16854. maxRedirects=max_redirects,
  16855. maxRetries=max_retries,
  16856. )
  16857. )
  16858. async def get(
  16859. self,
  16860. url: str,
  16861. *,
  16862. params: typing.Optional[
  16863. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  16864. ] = None,
  16865. headers: typing.Optional[typing.Dict[str, str]] = None,
  16866. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  16867. form: typing.Optional[
  16868. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  16869. ] = None,
  16870. multipart: typing.Optional[
  16871. typing.Union[
  16872. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  16873. "FormData",
  16874. ]
  16875. ] = None,
  16876. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16877. fail_on_status_code: typing.Optional[bool] = None,
  16878. ignore_https_errors: typing.Optional[bool] = None,
  16879. max_redirects: typing.Optional[int] = None,
  16880. max_retries: typing.Optional[int] = None,
  16881. ) -> "APIResponse":
  16882. """APIRequestContext.get
  16883. Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its
  16884. response. The method will populate request cookies from the context and update context cookies from the response.
  16885. The method will automatically follow redirects.
  16886. **Usage**
  16887. Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
  16888. ```python
  16889. query_params = {
  16890. \"isbn\": \"1234\",
  16891. \"page\": \"23\"
  16892. }
  16893. api_request_context.get(\"https://example.com/api/getText\", params=query_params)
  16894. ```
  16895. Parameters
  16896. ----------
  16897. url : str
  16898. Target URL.
  16899. params : Union[Dict[str, Union[bool, float, str]], str, None]
  16900. Query parameters to be sent with the URL.
  16901. headers : Union[Dict[str, str], None]
  16902. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  16903. it.
  16904. data : Union[Any, bytes, str, None]
  16905. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  16906. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  16907. header will be set to `application/octet-stream` if not explicitly set.
  16908. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  16909. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  16910. as this request body. If this parameter is specified `content-type` header will be set to
  16911. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  16912. field.
  16913. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  16914. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  16915. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  16916. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  16917. Use `FormData` to send multiple files in the same field.
  16918. timeout : Union[float, None]
  16919. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  16920. fail_on_status_code : Union[bool, None]
  16921. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  16922. codes.
  16923. ignore_https_errors : Union[bool, None]
  16924. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  16925. max_redirects : Union[int, None]
  16926. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  16927. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  16928. max_retries : Union[int, None]
  16929. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  16930. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  16931. Returns
  16932. -------
  16933. APIResponse
  16934. """
  16935. return mapping.from_impl(
  16936. await self._impl_obj.get(
  16937. url=url,
  16938. params=mapping.to_impl(params),
  16939. headers=mapping.to_impl(headers),
  16940. data=mapping.to_impl(data),
  16941. form=mapping.to_impl(form),
  16942. multipart=mapping.to_impl(multipart),
  16943. timeout=to_milliseconds(timeout),
  16944. failOnStatusCode=fail_on_status_code,
  16945. ignoreHTTPSErrors=ignore_https_errors,
  16946. maxRedirects=max_redirects,
  16947. maxRetries=max_retries,
  16948. )
  16949. )
  16950. async def patch(
  16951. self,
  16952. url: str,
  16953. *,
  16954. params: typing.Optional[
  16955. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  16956. ] = None,
  16957. headers: typing.Optional[typing.Dict[str, str]] = None,
  16958. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  16959. form: typing.Optional[
  16960. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  16961. ] = None,
  16962. multipart: typing.Optional[
  16963. typing.Union[
  16964. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  16965. "FormData",
  16966. ]
  16967. ] = None,
  16968. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  16969. fail_on_status_code: typing.Optional[bool] = None,
  16970. ignore_https_errors: typing.Optional[bool] = None,
  16971. max_redirects: typing.Optional[int] = None,
  16972. max_retries: typing.Optional[int] = None,
  16973. ) -> "APIResponse":
  16974. """APIRequestContext.patch
  16975. Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its
  16976. response. The method will populate request cookies from the context and update context cookies from the response.
  16977. The method will automatically follow redirects.
  16978. Parameters
  16979. ----------
  16980. url : str
  16981. Target URL.
  16982. params : Union[Dict[str, Union[bool, float, str]], str, None]
  16983. Query parameters to be sent with the URL.
  16984. headers : Union[Dict[str, str], None]
  16985. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  16986. it.
  16987. data : Union[Any, bytes, str, None]
  16988. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  16989. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  16990. header will be set to `application/octet-stream` if not explicitly set.
  16991. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  16992. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  16993. as this request body. If this parameter is specified `content-type` header will be set to
  16994. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  16995. field.
  16996. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  16997. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  16998. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  16999. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  17000. Use `FormData` to send multiple files in the same field.
  17001. timeout : Union[float, None]
  17002. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  17003. fail_on_status_code : Union[bool, None]
  17004. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  17005. codes.
  17006. ignore_https_errors : Union[bool, None]
  17007. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  17008. max_redirects : Union[int, None]
  17009. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  17010. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  17011. max_retries : Union[int, None]
  17012. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  17013. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  17014. Returns
  17015. -------
  17016. APIResponse
  17017. """
  17018. return mapping.from_impl(
  17019. await self._impl_obj.patch(
  17020. url=url,
  17021. params=mapping.to_impl(params),
  17022. headers=mapping.to_impl(headers),
  17023. data=mapping.to_impl(data),
  17024. form=mapping.to_impl(form),
  17025. multipart=mapping.to_impl(multipart),
  17026. timeout=to_milliseconds(timeout),
  17027. failOnStatusCode=fail_on_status_code,
  17028. ignoreHTTPSErrors=ignore_https_errors,
  17029. maxRedirects=max_redirects,
  17030. maxRetries=max_retries,
  17031. )
  17032. )
  17033. async def put(
  17034. self,
  17035. url: str,
  17036. *,
  17037. params: typing.Optional[
  17038. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  17039. ] = None,
  17040. headers: typing.Optional[typing.Dict[str, str]] = None,
  17041. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  17042. form: typing.Optional[
  17043. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  17044. ] = None,
  17045. multipart: typing.Optional[
  17046. typing.Union[
  17047. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  17048. "FormData",
  17049. ]
  17050. ] = None,
  17051. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17052. fail_on_status_code: typing.Optional[bool] = None,
  17053. ignore_https_errors: typing.Optional[bool] = None,
  17054. max_redirects: typing.Optional[int] = None,
  17055. max_retries: typing.Optional[int] = None,
  17056. ) -> "APIResponse":
  17057. """APIRequestContext.put
  17058. Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its
  17059. response. The method will populate request cookies from the context and update context cookies from the response.
  17060. The method will automatically follow redirects.
  17061. Parameters
  17062. ----------
  17063. url : str
  17064. Target URL.
  17065. params : Union[Dict[str, Union[bool, float, str]], str, None]
  17066. Query parameters to be sent with the URL.
  17067. headers : Union[Dict[str, str], None]
  17068. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  17069. it.
  17070. data : Union[Any, bytes, str, None]
  17071. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  17072. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  17073. header will be set to `application/octet-stream` if not explicitly set.
  17074. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  17075. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  17076. as this request body. If this parameter is specified `content-type` header will be set to
  17077. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  17078. field.
  17079. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  17080. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  17081. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  17082. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  17083. Use `FormData` to send multiple files in the same field.
  17084. timeout : Union[float, None]
  17085. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  17086. fail_on_status_code : Union[bool, None]
  17087. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  17088. codes.
  17089. ignore_https_errors : Union[bool, None]
  17090. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  17091. max_redirects : Union[int, None]
  17092. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  17093. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  17094. max_retries : Union[int, None]
  17095. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  17096. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  17097. Returns
  17098. -------
  17099. APIResponse
  17100. """
  17101. return mapping.from_impl(
  17102. await self._impl_obj.put(
  17103. url=url,
  17104. params=mapping.to_impl(params),
  17105. headers=mapping.to_impl(headers),
  17106. data=mapping.to_impl(data),
  17107. form=mapping.to_impl(form),
  17108. multipart=mapping.to_impl(multipart),
  17109. timeout=to_milliseconds(timeout),
  17110. failOnStatusCode=fail_on_status_code,
  17111. ignoreHTTPSErrors=ignore_https_errors,
  17112. maxRedirects=max_redirects,
  17113. maxRetries=max_retries,
  17114. )
  17115. )
  17116. async def post(
  17117. self,
  17118. url: str,
  17119. *,
  17120. params: typing.Optional[
  17121. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  17122. ] = None,
  17123. headers: typing.Optional[typing.Dict[str, str]] = None,
  17124. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  17125. form: typing.Optional[
  17126. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  17127. ] = None,
  17128. multipart: typing.Optional[
  17129. typing.Union[
  17130. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  17131. "FormData",
  17132. ]
  17133. ] = None,
  17134. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17135. fail_on_status_code: typing.Optional[bool] = None,
  17136. ignore_https_errors: typing.Optional[bool] = None,
  17137. max_redirects: typing.Optional[int] = None,
  17138. max_retries: typing.Optional[int] = None,
  17139. ) -> "APIResponse":
  17140. """APIRequestContext.post
  17141. Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its
  17142. response. The method will populate request cookies from the context and update context cookies from the response.
  17143. The method will automatically follow redirects.
  17144. **Usage**
  17145. JSON objects can be passed directly to the request:
  17146. ```python
  17147. data = {
  17148. \"title\": \"Book Title\",
  17149. \"body\": \"John Doe\",
  17150. }
  17151. api_request_context.post(\"https://example.com/api/createBook\", data=data)
  17152. ```
  17153. To send form data to the server use `form` option. Its value will be encoded into the request body with
  17154. `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send
  17155. files):
  17156. The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
  17157. encoding. Use `FormData` to construct request body and pass it to the request as `multipart` parameter:
  17158. ```python
  17159. api_request_context.post(
  17160. \"https://example.com/api/uploadScript'\",
  17161. multipart={
  17162. \"fileField\": {
  17163. \"name\": \"f.js\",
  17164. \"mimeType\": \"text/javascript\",
  17165. \"buffer\": b\"console.log(2022);\",
  17166. },
  17167. })
  17168. ```
  17169. Parameters
  17170. ----------
  17171. url : str
  17172. Target URL.
  17173. params : Union[Dict[str, Union[bool, float, str]], str, None]
  17174. Query parameters to be sent with the URL.
  17175. headers : Union[Dict[str, str], None]
  17176. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  17177. it.
  17178. data : Union[Any, bytes, str, None]
  17179. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  17180. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  17181. header will be set to `application/octet-stream` if not explicitly set.
  17182. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  17183. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  17184. as this request body. If this parameter is specified `content-type` header will be set to
  17185. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  17186. field.
  17187. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  17188. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  17189. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  17190. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  17191. Use `FormData` to send multiple files in the same field.
  17192. timeout : Union[float, None]
  17193. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  17194. fail_on_status_code : Union[bool, None]
  17195. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  17196. codes.
  17197. ignore_https_errors : Union[bool, None]
  17198. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  17199. max_redirects : Union[int, None]
  17200. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  17201. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  17202. max_retries : Union[int, None]
  17203. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  17204. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  17205. Returns
  17206. -------
  17207. APIResponse
  17208. """
  17209. return mapping.from_impl(
  17210. await self._impl_obj.post(
  17211. url=url,
  17212. params=mapping.to_impl(params),
  17213. headers=mapping.to_impl(headers),
  17214. data=mapping.to_impl(data),
  17215. form=mapping.to_impl(form),
  17216. multipart=mapping.to_impl(multipart),
  17217. timeout=to_milliseconds(timeout),
  17218. failOnStatusCode=fail_on_status_code,
  17219. ignoreHTTPSErrors=ignore_https_errors,
  17220. maxRedirects=max_redirects,
  17221. maxRetries=max_retries,
  17222. )
  17223. )
  17224. async def fetch(
  17225. self,
  17226. url_or_request: typing.Union[str, "Request"],
  17227. *,
  17228. params: typing.Optional[
  17229. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  17230. ] = None,
  17231. method: typing.Optional[str] = None,
  17232. headers: typing.Optional[typing.Dict[str, str]] = None,
  17233. data: typing.Optional[typing.Union[typing.Any, bytes, str]] = None,
  17234. form: typing.Optional[
  17235. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"]
  17236. ] = None,
  17237. multipart: typing.Optional[
  17238. typing.Union[
  17239. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]],
  17240. "FormData",
  17241. ]
  17242. ] = None,
  17243. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17244. fail_on_status_code: typing.Optional[bool] = None,
  17245. ignore_https_errors: typing.Optional[bool] = None,
  17246. max_redirects: typing.Optional[int] = None,
  17247. max_retries: typing.Optional[int] = None,
  17248. ) -> "APIResponse":
  17249. """APIRequestContext.fetch
  17250. Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
  17251. update context cookies from the response. The method will automatically follow redirects.
  17252. **Usage**
  17253. JSON objects can be passed directly to the request:
  17254. ```python
  17255. data = {
  17256. \"title\": \"Book Title\",
  17257. \"body\": \"John Doe\",
  17258. }
  17259. api_request_context.fetch(\"https://example.com/api/createBook\", method=\"post\", data=data)
  17260. ```
  17261. The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
  17262. encoding, by specifiying the `multipart` parameter:
  17263. Parameters
  17264. ----------
  17265. url_or_request : Union[Request, str]
  17266. Target URL or Request to get all parameters from.
  17267. params : Union[Dict[str, Union[bool, float, str]], str, None]
  17268. Query parameters to be sent with the URL.
  17269. method : Union[str, None]
  17270. If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or
  17271. [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.
  17272. headers : Union[Dict[str, str], None]
  17273. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  17274. it.
  17275. data : Union[Any, bytes, str, None]
  17276. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  17277. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  17278. header will be set to `application/octet-stream` if not explicitly set.
  17279. form : Union[Dict[str, Union[bool, float, str]], FormData, None]
  17280. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  17281. as this request body. If this parameter is specified `content-type` header will be set to
  17282. `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same
  17283. field.
  17284. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None]
  17285. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  17286. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  17287. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  17288. Use `FormData` to send multiple files in the same field.
  17289. timeout : Union[float, None]
  17290. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  17291. fail_on_status_code : Union[bool, None]
  17292. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  17293. codes.
  17294. ignore_https_errors : Union[bool, None]
  17295. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  17296. max_redirects : Union[int, None]
  17297. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  17298. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  17299. max_retries : Union[int, None]
  17300. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  17301. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  17302. Returns
  17303. -------
  17304. APIResponse
  17305. """
  17306. return mapping.from_impl(
  17307. await self._impl_obj.fetch(
  17308. urlOrRequest=url_or_request,
  17309. params=mapping.to_impl(params),
  17310. method=method,
  17311. headers=mapping.to_impl(headers),
  17312. data=mapping.to_impl(data),
  17313. form=mapping.to_impl(form),
  17314. multipart=mapping.to_impl(multipart),
  17315. timeout=to_milliseconds(timeout),
  17316. failOnStatusCode=fail_on_status_code,
  17317. ignoreHTTPSErrors=ignore_https_errors,
  17318. maxRedirects=max_redirects,
  17319. maxRetries=max_retries,
  17320. )
  17321. )
  17322. async def storage_state(
  17323. self,
  17324. *,
  17325. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  17326. indexed_db: typing.Optional[bool] = None,
  17327. ) -> StorageState:
  17328. """APIRequestContext.storage_state
  17329. Returns storage state for this request context, contains current cookies and local storage snapshot if it was
  17330. passed to the constructor.
  17331. Parameters
  17332. ----------
  17333. path : Union[pathlib.Path, str, None]
  17334. The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
  17335. working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
  17336. indexed_db : Union[bool, None]
  17337. Set to `true` to include IndexedDB in the storage state snapshot.
  17338. Returns
  17339. -------
  17340. {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}]}]}
  17341. """
  17342. return mapping.from_impl(
  17343. await self._impl_obj.storage_state(path=path, indexedDB=indexed_db)
  17344. )
  17345. mapping.register(APIRequestContextImpl, APIRequestContext)
  17346. class APIRequest(AsyncBase):
  17347. async def new_context(
  17348. self,
  17349. *,
  17350. base_url: typing.Optional[str] = None,
  17351. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  17352. http_credentials: typing.Optional[HttpCredentials] = None,
  17353. ignore_https_errors: typing.Optional[bool] = None,
  17354. proxy: typing.Optional[ProxySettings] = None,
  17355. user_agent: typing.Optional[str] = None,
  17356. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17357. storage_state: typing.Optional[
  17358. typing.Union[StorageState, str, pathlib.Path]
  17359. ] = None,
  17360. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  17361. fail_on_status_code: typing.Optional[bool] = None,
  17362. max_redirects: typing.Optional[int] = None,
  17363. ) -> "APIRequestContext":
  17364. """APIRequest.new_context
  17365. Creates new instances of `APIRequestContext`.
  17366. Parameters
  17367. ----------
  17368. base_url : Union[str, None]
  17369. Methods like `a_pi_request_context.get()` take the base URL into consideration by using the
  17370. [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
  17371. Examples:
  17372. - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`
  17373. - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in
  17374. `http://localhost:3000/foo/bar.html`
  17375. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  17376. `http://localhost:3000/bar.html`
  17377. extra_http_headers : Union[Dict[str, str], None]
  17378. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  17379. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  17380. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  17381. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  17382. ignore_https_errors : Union[bool, None]
  17383. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  17384. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  17385. Network proxy settings.
  17386. user_agent : Union[str, None]
  17387. Specific user agent to use in this context.
  17388. timeout : Union[float, None]
  17389. Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable
  17390. timeout.
  17391. 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]
  17392. Populates context with given storage state. This option can be used to initialize context with logged-in
  17393. information obtained via `browser_context.storage_state()` or `a_pi_request_context.storage_state()`.
  17394. Either a path to the file with saved storage, or the value returned by one of
  17395. `browser_context.storage_state()` or `a_pi_request_context.storage_state()` methods.
  17396. 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]
  17397. TLS Client Authentication allows the server to request a client certificate and verify it.
  17398. **Details**
  17399. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  17400. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  17401. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  17402. with an exact match to the request origin that the certificate is valid for.
  17403. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  17404. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  17405. does not match any of the domains you plan to visit.
  17406. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  17407. work by replacing `localhost` with `local.playwright`.
  17408. fail_on_status_code : Union[bool, None]
  17409. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  17410. codes.
  17411. max_redirects : Union[int, None]
  17412. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  17413. exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request
  17414. individually.
  17415. Returns
  17416. -------
  17417. APIRequestContext
  17418. """
  17419. return mapping.from_impl(
  17420. await self._impl_obj.new_context(
  17421. baseURL=base_url,
  17422. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  17423. httpCredentials=http_credentials,
  17424. ignoreHTTPSErrors=ignore_https_errors,
  17425. proxy=proxy,
  17426. userAgent=user_agent,
  17427. timeout=to_milliseconds(timeout),
  17428. storageState=storage_state,
  17429. clientCertificates=client_certificates,
  17430. failOnStatusCode=fail_on_status_code,
  17431. maxRedirects=max_redirects,
  17432. )
  17433. )
  17434. mapping.register(APIRequestImpl, APIRequest)
  17435. class PageAssertions(AsyncBase):
  17436. async def to_have_title(
  17437. self,
  17438. title_or_reg_exp: typing.Union[typing.Pattern[str], str],
  17439. *,
  17440. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17441. ) -> None:
  17442. """PageAssertions.to_have_title
  17443. Ensures the page has the given title.
  17444. **Usage**
  17445. ```py
  17446. import re
  17447. from playwright.async_api import expect
  17448. # ...
  17449. await expect(page).to_have_title(re.compile(r\".*checkout\"))
  17450. ```
  17451. Parameters
  17452. ----------
  17453. title_or_reg_exp : Union[Pattern[str], str]
  17454. Expected title or RegExp.
  17455. timeout : Union[float, None]
  17456. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17457. """
  17458. __tracebackhide__ = True
  17459. return mapping.from_maybe_impl(
  17460. await self._impl_obj.to_have_title(
  17461. titleOrRegExp=title_or_reg_exp, timeout=to_milliseconds(timeout)
  17462. )
  17463. )
  17464. async def not_to_have_title(
  17465. self,
  17466. title_or_reg_exp: typing.Union[typing.Pattern[str], str],
  17467. *,
  17468. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17469. ) -> None:
  17470. """PageAssertions.not_to_have_title
  17471. The opposite of `page_assertions.to_have_title()`.
  17472. Parameters
  17473. ----------
  17474. title_or_reg_exp : Union[Pattern[str], str]
  17475. Expected title or RegExp.
  17476. timeout : Union[float, None]
  17477. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17478. """
  17479. __tracebackhide__ = True
  17480. return mapping.from_maybe_impl(
  17481. await self._impl_obj.not_to_have_title(
  17482. titleOrRegExp=title_or_reg_exp, timeout=to_milliseconds(timeout)
  17483. )
  17484. )
  17485. async def to_have_url(
  17486. self,
  17487. url_or_reg_exp: typing.Union[str, typing.Pattern[str]],
  17488. *,
  17489. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17490. ignore_case: typing.Optional[bool] = None,
  17491. ) -> None:
  17492. """PageAssertions.to_have_url
  17493. Ensures the page is navigated to the given URL.
  17494. **Usage**
  17495. ```py
  17496. import re
  17497. from playwright.async_api import expect
  17498. # ...
  17499. await expect(page).to_have_url(re.compile(\".*checkout\"))
  17500. ```
  17501. Parameters
  17502. ----------
  17503. url_or_reg_exp : Union[Pattern[str], str]
  17504. Expected URL string or RegExp.
  17505. timeout : Union[float, None]
  17506. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17507. ignore_case : Union[bool, None]
  17508. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17509. expression parameter if specified. A provided predicate ignores this flag.
  17510. """
  17511. __tracebackhide__ = True
  17512. return mapping.from_maybe_impl(
  17513. await self._impl_obj.to_have_url(
  17514. urlOrRegExp=url_or_reg_exp,
  17515. timeout=to_milliseconds(timeout),
  17516. ignoreCase=ignore_case,
  17517. )
  17518. )
  17519. async def not_to_have_url(
  17520. self,
  17521. url_or_reg_exp: typing.Union[typing.Pattern[str], str],
  17522. *,
  17523. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17524. ignore_case: typing.Optional[bool] = None,
  17525. ) -> None:
  17526. """PageAssertions.not_to_have_url
  17527. The opposite of `page_assertions.to_have_url()`.
  17528. Parameters
  17529. ----------
  17530. url_or_reg_exp : Union[Pattern[str], str]
  17531. Expected URL string or RegExp.
  17532. timeout : Union[float, None]
  17533. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17534. ignore_case : Union[bool, None]
  17535. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17536. expression flag if specified.
  17537. """
  17538. __tracebackhide__ = True
  17539. return mapping.from_maybe_impl(
  17540. await self._impl_obj.not_to_have_url(
  17541. urlOrRegExp=url_or_reg_exp,
  17542. timeout=to_milliseconds(timeout),
  17543. ignoreCase=ignore_case,
  17544. )
  17545. )
  17546. async def to_match_aria_snapshot(
  17547. self,
  17548. expected: str,
  17549. *,
  17550. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17551. ) -> None:
  17552. """PageAssertions.to_match_aria_snapshot
  17553. Asserts that the page body matches the given [accessibility snapshot](https://playwright.dev/python/docs/aria-snapshots).
  17554. **Usage**
  17555. ```py
  17556. await page.goto(\"https://demo.playwright.dev/todomvc/\")
  17557. await expect(page).to_match_aria_snapshot('''
  17558. - heading \"todos\"
  17559. - textbox \"What needs to be done?\"
  17560. ''')
  17561. ```
  17562. Parameters
  17563. ----------
  17564. expected : str
  17565. timeout : Union[float, None]
  17566. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17567. """
  17568. __tracebackhide__ = True
  17569. return mapping.from_maybe_impl(
  17570. await self._impl_obj.to_match_aria_snapshot(
  17571. expected=expected, timeout=to_milliseconds(timeout)
  17572. )
  17573. )
  17574. async def not_to_match_aria_snapshot(
  17575. self,
  17576. expected: str,
  17577. *,
  17578. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17579. ) -> None:
  17580. """PageAssertions.not_to_match_aria_snapshot
  17581. The opposite of `page_assertions.to_match_aria_snapshot()`.
  17582. Parameters
  17583. ----------
  17584. expected : str
  17585. timeout : Union[float, None]
  17586. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17587. """
  17588. __tracebackhide__ = True
  17589. return mapping.from_maybe_impl(
  17590. await self._impl_obj.not_to_match_aria_snapshot(
  17591. expected=expected, timeout=to_milliseconds(timeout)
  17592. )
  17593. )
  17594. mapping.register(PageAssertionsImpl, PageAssertions)
  17595. class LocatorAssertions(AsyncBase):
  17596. async def to_contain_text(
  17597. self,
  17598. expected: typing.Union[
  17599. typing.Sequence[str],
  17600. typing.Sequence[typing.Pattern[str]],
  17601. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  17602. typing.Pattern[str],
  17603. str,
  17604. ],
  17605. *,
  17606. use_inner_text: typing.Optional[bool] = None,
  17607. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17608. ignore_case: typing.Optional[bool] = None,
  17609. ) -> None:
  17610. """LocatorAssertions.to_contain_text
  17611. Ensures the `Locator` points to an element that contains the given text. All nested elements will be considered
  17612. when computing the text content of the element. You can use regular expressions for the value as well.
  17613. **Details**
  17614. When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
  17615. text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
  17616. **Usage**
  17617. ```py
  17618. import re
  17619. from playwright.async_api import expect
  17620. locator = page.locator('.title')
  17621. await expect(locator).to_contain_text(\"substring\")
  17622. await expect(locator).to_contain_text(re.compile(r\"\\d messages\"))
  17623. ```
  17624. If you pass an array as an expected value, the expectations are:
  17625. 1. Locator resolves to a list of elements.
  17626. 1. Elements from a **subset** of this list contain text from the expected array, respectively.
  17627. 1. The matching subset of elements has the same order as the expected array.
  17628. 1. Each text value from the expected array is matched by some element from the list.
  17629. For example, consider the following list:
  17630. ```html
  17631. <ul>
  17632. <li>Item Text 1</li>
  17633. <li>Item Text 2</li>
  17634. <li>Item Text 3</li>
  17635. </ul>
  17636. ```
  17637. Let's see how we can use the assertion:
  17638. ```py
  17639. from playwright.async_api import expect
  17640. # ✓ Contains the right items in the right order
  17641. await expect(page.locator(\"ul > li\")).to_contain_text([\"Text 1\", \"Text 3\"])
  17642. # ✖ Wrong order
  17643. await expect(page.locator(\"ul > li\")).to_contain_text([\"Text 3\", \"Text 2\"])
  17644. # ✖ No item contains this text
  17645. await expect(page.locator(\"ul > li\")).to_contain_text([\"Some 33\"])
  17646. # ✖ Locator points to the outer list element, not to the list items
  17647. await expect(page.locator(\"ul\")).to_contain_text([\"Text 3\"])
  17648. ```
  17649. Parameters
  17650. ----------
  17651. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  17652. Expected substring or RegExp or a list of those.
  17653. use_inner_text : Union[bool, None]
  17654. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  17655. timeout : Union[float, None]
  17656. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17657. ignore_case : Union[bool, None]
  17658. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17659. expression flag if specified.
  17660. """
  17661. __tracebackhide__ = True
  17662. return mapping.from_maybe_impl(
  17663. await self._impl_obj.to_contain_text(
  17664. expected=mapping.to_impl(expected),
  17665. useInnerText=use_inner_text,
  17666. timeout=to_milliseconds(timeout),
  17667. ignoreCase=ignore_case,
  17668. )
  17669. )
  17670. async def not_to_contain_text(
  17671. self,
  17672. expected: typing.Union[
  17673. typing.Sequence[str],
  17674. typing.Sequence[typing.Pattern[str]],
  17675. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  17676. typing.Pattern[str],
  17677. str,
  17678. ],
  17679. *,
  17680. use_inner_text: typing.Optional[bool] = None,
  17681. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17682. ignore_case: typing.Optional[bool] = None,
  17683. ) -> None:
  17684. """LocatorAssertions.not_to_contain_text
  17685. The opposite of `locator_assertions.to_contain_text()`.
  17686. Parameters
  17687. ----------
  17688. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  17689. Expected substring or RegExp or a list of those.
  17690. use_inner_text : Union[bool, None]
  17691. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  17692. timeout : Union[float, None]
  17693. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17694. ignore_case : Union[bool, None]
  17695. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17696. expression flag if specified.
  17697. """
  17698. __tracebackhide__ = True
  17699. return mapping.from_maybe_impl(
  17700. await self._impl_obj.not_to_contain_text(
  17701. expected=mapping.to_impl(expected),
  17702. useInnerText=use_inner_text,
  17703. timeout=to_milliseconds(timeout),
  17704. ignoreCase=ignore_case,
  17705. )
  17706. )
  17707. async def to_have_attribute(
  17708. self,
  17709. name: str,
  17710. value: typing.Union[str, typing.Pattern[str]],
  17711. *,
  17712. ignore_case: typing.Optional[bool] = None,
  17713. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17714. ) -> None:
  17715. """LocatorAssertions.to_have_attribute
  17716. Ensures the `Locator` points to an element with given attribute.
  17717. **Usage**
  17718. ```py
  17719. from playwright.async_api import expect
  17720. locator = page.locator(\"input\")
  17721. await expect(locator).to_have_attribute(\"type\", \"text\")
  17722. ```
  17723. Parameters
  17724. ----------
  17725. name : str
  17726. Attribute name.
  17727. value : Union[Pattern[str], str]
  17728. Expected attribute value.
  17729. ignore_case : Union[bool, None]
  17730. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17731. expression flag if specified.
  17732. timeout : Union[float, None]
  17733. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17734. """
  17735. __tracebackhide__ = True
  17736. return mapping.from_maybe_impl(
  17737. await self._impl_obj.to_have_attribute(
  17738. name=name,
  17739. value=value,
  17740. ignoreCase=ignore_case,
  17741. timeout=to_milliseconds(timeout),
  17742. )
  17743. )
  17744. async def not_to_have_attribute(
  17745. self,
  17746. name: str,
  17747. value: typing.Union[str, typing.Pattern[str]],
  17748. *,
  17749. ignore_case: typing.Optional[bool] = None,
  17750. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17751. ) -> None:
  17752. """LocatorAssertions.not_to_have_attribute
  17753. The opposite of `locator_assertions.to_have_attribute()`.
  17754. Parameters
  17755. ----------
  17756. name : str
  17757. Attribute name.
  17758. value : Union[Pattern[str], str]
  17759. Expected attribute value.
  17760. ignore_case : Union[bool, None]
  17761. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17762. expression flag if specified.
  17763. timeout : Union[float, None]
  17764. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17765. """
  17766. __tracebackhide__ = True
  17767. return mapping.from_maybe_impl(
  17768. await self._impl_obj.not_to_have_attribute(
  17769. name=name,
  17770. value=value,
  17771. ignoreCase=ignore_case,
  17772. timeout=to_milliseconds(timeout),
  17773. )
  17774. )
  17775. async def to_have_class(
  17776. self,
  17777. expected: typing.Union[
  17778. typing.Sequence[str],
  17779. typing.Sequence[typing.Pattern[str]],
  17780. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  17781. typing.Pattern[str],
  17782. str,
  17783. ],
  17784. *,
  17785. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17786. ) -> None:
  17787. """LocatorAssertions.to_have_class
  17788. Ensures the `Locator` points to an element with given CSS classes. When a string is provided, it must fully match
  17789. the element's `class` attribute. To match individual classes use `locator_assertions.to_contain_class()`.
  17790. **Usage**
  17791. ```html
  17792. <div class='middle selected row' id='component'></div>
  17793. ```
  17794. ```py
  17795. from playwright.async_api import expect
  17796. locator = page.locator(\"#component\")
  17797. await expect(locator).to_have_class(\"middle selected row\")
  17798. await expect(locator).to_have_class(re.compile(r\"(^|\\\\s)selected(\\\\s|$)\"))
  17799. ```
  17800. When an array is passed, the method asserts that the list of elements located matches the corresponding list of
  17801. expected class values. Each element's class attribute is matched against the corresponding string or regular
  17802. expression in the array:
  17803. ```py
  17804. from playwright.async_api import expect
  17805. locator = page.locator(\".list > .component\")
  17806. await expect(locator).to_have_class([\"component\", \"component selected\", \"component\"])
  17807. ```
  17808. Parameters
  17809. ----------
  17810. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  17811. Expected class or RegExp or a list of those.
  17812. timeout : Union[float, None]
  17813. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17814. """
  17815. __tracebackhide__ = True
  17816. return mapping.from_maybe_impl(
  17817. await self._impl_obj.to_have_class(
  17818. expected=mapping.to_impl(expected), timeout=to_milliseconds(timeout)
  17819. )
  17820. )
  17821. async def not_to_have_class(
  17822. self,
  17823. expected: typing.Union[
  17824. typing.Sequence[str],
  17825. typing.Sequence[typing.Pattern[str]],
  17826. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  17827. typing.Pattern[str],
  17828. str,
  17829. ],
  17830. *,
  17831. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17832. ) -> None:
  17833. """LocatorAssertions.not_to_have_class
  17834. The opposite of `locator_assertions.to_have_class()`.
  17835. Parameters
  17836. ----------
  17837. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  17838. Expected class or RegExp or a list of those.
  17839. timeout : Union[float, None]
  17840. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17841. """
  17842. __tracebackhide__ = True
  17843. return mapping.from_maybe_impl(
  17844. await self._impl_obj.not_to_have_class(
  17845. expected=mapping.to_impl(expected), timeout=to_milliseconds(timeout)
  17846. )
  17847. )
  17848. async def to_contain_class(
  17849. self,
  17850. expected: typing.Union[typing.Sequence[str], str],
  17851. *,
  17852. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17853. ) -> None:
  17854. """LocatorAssertions.to_contain_class
  17855. Ensures the `Locator` points to an element with given CSS classes. All classes from the asserted value, separated
  17856. by spaces, must be present in the
  17857. [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) in any order.
  17858. **Usage**
  17859. ```html
  17860. <div class='middle selected row' id='component'></div>
  17861. ```
  17862. ```py
  17863. from playwright.async_api import expect
  17864. locator = page.locator(\"#component\")
  17865. await expect(locator).to_contain_class(\"middle selected row\")
  17866. await expect(locator).to_contain_class(\"selected\")
  17867. await expect(locator).to_contain_class(\"row middle\")
  17868. ```
  17869. When an array is passed, the method asserts that the list of elements located matches the corresponding list of
  17870. expected class lists. Each element's class attribute is matched against the corresponding class in the array:
  17871. ```html
  17872. <div class='list'>
  17873. <div class='component inactive'></div>
  17874. <div class='component active'></div>
  17875. <div class='component inactive'></div>
  17876. </div>
  17877. ```
  17878. ```py
  17879. from playwright.async_api import expect
  17880. locator = page.locator(\".list > .component\")
  17881. await expect(locator).to_contain_class([\"inactive\", \"active\", \"inactive\"])
  17882. ```
  17883. Parameters
  17884. ----------
  17885. expected : Union[Sequence[str], str]
  17886. A string containing expected class names, separated by spaces, or a list of such strings to assert multiple
  17887. elements.
  17888. timeout : Union[float, None]
  17889. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17890. """
  17891. __tracebackhide__ = True
  17892. return mapping.from_maybe_impl(
  17893. await self._impl_obj.to_contain_class(
  17894. expected=mapping.to_impl(expected), timeout=to_milliseconds(timeout)
  17895. )
  17896. )
  17897. async def not_to_contain_class(
  17898. self,
  17899. expected: typing.Union[typing.Sequence[str], str],
  17900. *,
  17901. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17902. ) -> None:
  17903. """LocatorAssertions.not_to_contain_class
  17904. The opposite of `locator_assertions.to_contain_class()`.
  17905. Parameters
  17906. ----------
  17907. expected : Union[Sequence[str], str]
  17908. Expected class or RegExp or a list of those.
  17909. timeout : Union[float, None]
  17910. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17911. """
  17912. __tracebackhide__ = True
  17913. return mapping.from_maybe_impl(
  17914. await self._impl_obj.not_to_contain_class(
  17915. expected=mapping.to_impl(expected), timeout=to_milliseconds(timeout)
  17916. )
  17917. )
  17918. async def to_have_count(
  17919. self,
  17920. count: int,
  17921. *,
  17922. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17923. ) -> None:
  17924. """LocatorAssertions.to_have_count
  17925. Ensures the `Locator` resolves to an exact number of DOM nodes.
  17926. **Usage**
  17927. ```py
  17928. from playwright.async_api import expect
  17929. locator = page.locator(\"list > .component\")
  17930. await expect(locator).to_have_count(3)
  17931. ```
  17932. Parameters
  17933. ----------
  17934. count : int
  17935. Expected count.
  17936. timeout : Union[float, None]
  17937. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17938. """
  17939. __tracebackhide__ = True
  17940. return mapping.from_maybe_impl(
  17941. await self._impl_obj.to_have_count(
  17942. count=count, timeout=to_milliseconds(timeout)
  17943. )
  17944. )
  17945. async def not_to_have_count(
  17946. self,
  17947. count: int,
  17948. *,
  17949. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17950. ) -> None:
  17951. """LocatorAssertions.not_to_have_count
  17952. The opposite of `locator_assertions.to_have_count()`.
  17953. Parameters
  17954. ----------
  17955. count : int
  17956. Expected count.
  17957. timeout : Union[float, None]
  17958. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17959. """
  17960. __tracebackhide__ = True
  17961. return mapping.from_maybe_impl(
  17962. await self._impl_obj.not_to_have_count(
  17963. count=count, timeout=to_milliseconds(timeout)
  17964. )
  17965. )
  17966. async def to_have_css(
  17967. self,
  17968. name: str,
  17969. value: typing.Union[str, typing.Pattern[str]],
  17970. *,
  17971. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  17972. pseudo: typing.Optional[Literal["after", "before"]] = None,
  17973. ) -> None:
  17974. """LocatorAssertions.to_have_css
  17975. Ensures the `Locator` resolves to an element with the given computed CSS style.
  17976. **Usage**
  17977. ```py
  17978. from playwright.async_api import expect
  17979. locator = page.get_by_role(\"button\")
  17980. await expect(locator).to_have_css(\"display\", \"flex\")
  17981. ```
  17982. Parameters
  17983. ----------
  17984. name : str
  17985. CSS property name.
  17986. value : Union[Pattern[str], str]
  17987. CSS property value.
  17988. timeout : Union[float, None]
  17989. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17990. pseudo : Union["after", "before", None]
  17991. Pseudo-element to read computed styles from.
  17992. """
  17993. __tracebackhide__ = True
  17994. return mapping.from_maybe_impl(
  17995. await self._impl_obj.to_have_css(
  17996. name=name, value=value, timeout=to_milliseconds(timeout), pseudo=pseudo
  17997. )
  17998. )
  17999. async def not_to_have_css(
  18000. self,
  18001. name: str,
  18002. value: typing.Union[str, typing.Pattern[str]],
  18003. *,
  18004. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18005. ) -> None:
  18006. """LocatorAssertions.not_to_have_css
  18007. The opposite of `locator_assertions.to_have_css()`.
  18008. Parameters
  18009. ----------
  18010. name : str
  18011. CSS property name.
  18012. value : Union[Pattern[str], str]
  18013. CSS property value.
  18014. timeout : Union[float, None]
  18015. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18016. """
  18017. __tracebackhide__ = True
  18018. return mapping.from_maybe_impl(
  18019. await self._impl_obj.not_to_have_css(
  18020. name=name, value=value, timeout=to_milliseconds(timeout)
  18021. )
  18022. )
  18023. async def to_have_id(
  18024. self,
  18025. id: typing.Union[str, typing.Pattern[str]],
  18026. *,
  18027. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18028. ) -> None:
  18029. """LocatorAssertions.to_have_id
  18030. Ensures the `Locator` points to an element with the given DOM Node ID.
  18031. **Usage**
  18032. ```py
  18033. from playwright.async_api import expect
  18034. locator = page.get_by_role(\"textbox\")
  18035. await expect(locator).to_have_id(\"lastname\")
  18036. ```
  18037. Parameters
  18038. ----------
  18039. id : Union[Pattern[str], str]
  18040. Element id.
  18041. timeout : Union[float, None]
  18042. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18043. """
  18044. __tracebackhide__ = True
  18045. return mapping.from_maybe_impl(
  18046. await self._impl_obj.to_have_id(id=id, timeout=to_milliseconds(timeout))
  18047. )
  18048. async def not_to_have_id(
  18049. self,
  18050. id: typing.Union[str, typing.Pattern[str]],
  18051. *,
  18052. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18053. ) -> None:
  18054. """LocatorAssertions.not_to_have_id
  18055. The opposite of `locator_assertions.to_have_id()`.
  18056. Parameters
  18057. ----------
  18058. id : Union[Pattern[str], str]
  18059. Element id.
  18060. timeout : Union[float, None]
  18061. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18062. """
  18063. __tracebackhide__ = True
  18064. return mapping.from_maybe_impl(
  18065. await self._impl_obj.not_to_have_id(id=id, timeout=to_milliseconds(timeout))
  18066. )
  18067. async def to_have_js_property(
  18068. self,
  18069. name: str,
  18070. value: typing.Any,
  18071. *,
  18072. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18073. ) -> None:
  18074. """LocatorAssertions.to_have_js_property
  18075. Ensures the `Locator` points to an element with given JavaScript property. Note that this property can be of a
  18076. primitive type as well as a plain serializable JavaScript object.
  18077. **Usage**
  18078. ```py
  18079. from playwright.async_api import expect
  18080. locator = page.locator(\".component\")
  18081. await expect(locator).to_have_js_property(\"loaded\", True)
  18082. ```
  18083. Parameters
  18084. ----------
  18085. name : str
  18086. Property name.
  18087. value : Any
  18088. Property value.
  18089. timeout : Union[float, None]
  18090. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18091. """
  18092. __tracebackhide__ = True
  18093. return mapping.from_maybe_impl(
  18094. await self._impl_obj.to_have_js_property(
  18095. name=name,
  18096. value=mapping.to_impl(value),
  18097. timeout=to_milliseconds(timeout),
  18098. )
  18099. )
  18100. async def not_to_have_js_property(
  18101. self,
  18102. name: str,
  18103. value: typing.Any,
  18104. *,
  18105. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18106. ) -> None:
  18107. """LocatorAssertions.not_to_have_js_property
  18108. The opposite of `locator_assertions.to_have_js_property()`.
  18109. Parameters
  18110. ----------
  18111. name : str
  18112. Property name.
  18113. value : Any
  18114. Property value.
  18115. timeout : Union[float, None]
  18116. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18117. """
  18118. __tracebackhide__ = True
  18119. return mapping.from_maybe_impl(
  18120. await self._impl_obj.not_to_have_js_property(
  18121. name=name,
  18122. value=mapping.to_impl(value),
  18123. timeout=to_milliseconds(timeout),
  18124. )
  18125. )
  18126. async def to_have_value(
  18127. self,
  18128. value: typing.Union[str, typing.Pattern[str]],
  18129. *,
  18130. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18131. ) -> None:
  18132. """LocatorAssertions.to_have_value
  18133. Ensures the `Locator` points to an element with the given input value. You can use regular expressions for the
  18134. value as well.
  18135. **Usage**
  18136. ```py
  18137. import re
  18138. from playwright.async_api import expect
  18139. locator = page.locator(\"input[type=number]\")
  18140. await expect(locator).to_have_value(re.compile(r\"[0-9]\"))
  18141. ```
  18142. Parameters
  18143. ----------
  18144. value : Union[Pattern[str], str]
  18145. Expected value.
  18146. timeout : Union[float, None]
  18147. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18148. """
  18149. __tracebackhide__ = True
  18150. return mapping.from_maybe_impl(
  18151. await self._impl_obj.to_have_value(
  18152. value=value, timeout=to_milliseconds(timeout)
  18153. )
  18154. )
  18155. async def not_to_have_value(
  18156. self,
  18157. value: typing.Union[str, typing.Pattern[str]],
  18158. *,
  18159. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18160. ) -> None:
  18161. """LocatorAssertions.not_to_have_value
  18162. The opposite of `locator_assertions.to_have_value()`.
  18163. Parameters
  18164. ----------
  18165. value : Union[Pattern[str], str]
  18166. Expected value.
  18167. timeout : Union[float, None]
  18168. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18169. """
  18170. __tracebackhide__ = True
  18171. return mapping.from_maybe_impl(
  18172. await self._impl_obj.not_to_have_value(
  18173. value=value, timeout=to_milliseconds(timeout)
  18174. )
  18175. )
  18176. async def to_have_values(
  18177. self,
  18178. values: typing.Union[
  18179. typing.Sequence[str],
  18180. typing.Sequence[typing.Pattern[str]],
  18181. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  18182. ],
  18183. *,
  18184. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18185. ) -> None:
  18186. """LocatorAssertions.to_have_values
  18187. Ensures the `Locator` points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the
  18188. specified values are selected.
  18189. **Usage**
  18190. For example, given the following element:
  18191. ```html
  18192. <select id=\"favorite-colors\" multiple>
  18193. <option value=\"R\">Red</option>
  18194. <option value=\"G\">Green</option>
  18195. <option value=\"B\">Blue</option>
  18196. </select>
  18197. ```
  18198. ```py
  18199. import re
  18200. from playwright.async_api import expect
  18201. locator = page.locator(\"id=favorite-colors\")
  18202. await locator.select_option([\"R\", \"G\"])
  18203. await expect(locator).to_have_values([re.compile(r\"R\"), re.compile(r\"G\")])
  18204. ```
  18205. Parameters
  18206. ----------
  18207. values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
  18208. Expected options currently selected.
  18209. timeout : Union[float, None]
  18210. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18211. """
  18212. __tracebackhide__ = True
  18213. return mapping.from_maybe_impl(
  18214. await self._impl_obj.to_have_values(
  18215. values=mapping.to_impl(values), timeout=to_milliseconds(timeout)
  18216. )
  18217. )
  18218. async def not_to_have_values(
  18219. self,
  18220. values: typing.Union[
  18221. typing.Sequence[str],
  18222. typing.Sequence[typing.Pattern[str]],
  18223. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  18224. ],
  18225. *,
  18226. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18227. ) -> None:
  18228. """LocatorAssertions.not_to_have_values
  18229. The opposite of `locator_assertions.to_have_values()`.
  18230. Parameters
  18231. ----------
  18232. values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
  18233. Expected options currently selected.
  18234. timeout : Union[float, None]
  18235. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18236. """
  18237. __tracebackhide__ = True
  18238. return mapping.from_maybe_impl(
  18239. await self._impl_obj.not_to_have_values(
  18240. values=mapping.to_impl(values), timeout=to_milliseconds(timeout)
  18241. )
  18242. )
  18243. async def to_have_text(
  18244. self,
  18245. expected: typing.Union[
  18246. typing.Sequence[str],
  18247. typing.Sequence[typing.Pattern[str]],
  18248. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  18249. typing.Pattern[str],
  18250. str,
  18251. ],
  18252. *,
  18253. use_inner_text: typing.Optional[bool] = None,
  18254. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18255. ignore_case: typing.Optional[bool] = None,
  18256. ) -> None:
  18257. """LocatorAssertions.to_have_text
  18258. Ensures the `Locator` points to an element with the given text. All nested elements will be considered when
  18259. computing the text content of the element. You can use regular expressions for the value as well.
  18260. **Details**
  18261. When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
  18262. text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
  18263. **Usage**
  18264. ```py
  18265. import re
  18266. from playwright.async_api import expect
  18267. locator = page.locator(\".title\")
  18268. await expect(locator).to_have_text(re.compile(r\"Welcome, Test User\"))
  18269. await expect(locator).to_have_text(re.compile(r\"Welcome, .*\"))
  18270. ```
  18271. If you pass an array as an expected value, the expectations are:
  18272. 1. Locator resolves to a list of elements.
  18273. 1. The number of elements equals the number of expected values in the array.
  18274. 1. Elements from the list have text matching expected array values, one by one, in order.
  18275. For example, consider the following list:
  18276. ```html
  18277. <ul>
  18278. <li>Text 1</li>
  18279. <li>Text 2</li>
  18280. <li>Text 3</li>
  18281. </ul>
  18282. ```
  18283. Let's see how we can use the assertion:
  18284. ```py
  18285. from playwright.async_api import expect
  18286. # ✓ Has the right items in the right order
  18287. await expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
  18288. # ✖ Wrong order
  18289. await expect(page.locator(\"ul > li\")).to_have_text([\"Text 3\", \"Text 2\", \"Text 1\"])
  18290. # ✖ Last item does not match
  18291. await expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text\"])
  18292. # ✖ Locator points to the outer list element, not to the list items
  18293. await expect(page.locator(\"ul\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
  18294. ```
  18295. Parameters
  18296. ----------
  18297. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  18298. Expected string or RegExp or a list of those.
  18299. use_inner_text : Union[bool, None]
  18300. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  18301. timeout : Union[float, None]
  18302. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18303. ignore_case : Union[bool, None]
  18304. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  18305. expression flag if specified.
  18306. """
  18307. __tracebackhide__ = True
  18308. return mapping.from_maybe_impl(
  18309. await self._impl_obj.to_have_text(
  18310. expected=mapping.to_impl(expected),
  18311. useInnerText=use_inner_text,
  18312. timeout=to_milliseconds(timeout),
  18313. ignoreCase=ignore_case,
  18314. )
  18315. )
  18316. async def not_to_have_text(
  18317. self,
  18318. expected: typing.Union[
  18319. typing.Sequence[str],
  18320. typing.Sequence[typing.Pattern[str]],
  18321. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  18322. typing.Pattern[str],
  18323. str,
  18324. ],
  18325. *,
  18326. use_inner_text: typing.Optional[bool] = None,
  18327. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18328. ignore_case: typing.Optional[bool] = None,
  18329. ) -> None:
  18330. """LocatorAssertions.not_to_have_text
  18331. The opposite of `locator_assertions.to_have_text()`.
  18332. Parameters
  18333. ----------
  18334. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  18335. Expected string or RegExp or a list of those.
  18336. use_inner_text : Union[bool, None]
  18337. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  18338. timeout : Union[float, None]
  18339. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18340. ignore_case : Union[bool, None]
  18341. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  18342. expression flag if specified.
  18343. """
  18344. __tracebackhide__ = True
  18345. return mapping.from_maybe_impl(
  18346. await self._impl_obj.not_to_have_text(
  18347. expected=mapping.to_impl(expected),
  18348. useInnerText=use_inner_text,
  18349. timeout=to_milliseconds(timeout),
  18350. ignoreCase=ignore_case,
  18351. )
  18352. )
  18353. async def to_be_attached(
  18354. self,
  18355. *,
  18356. attached: typing.Optional[bool] = None,
  18357. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18358. ) -> None:
  18359. """LocatorAssertions.to_be_attached
  18360. Ensures that `Locator` points to an element that is
  18361. [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
  18362. **Usage**
  18363. ```py
  18364. await expect(page.get_by_text(\"Hidden text\")).to_be_attached()
  18365. ```
  18366. Parameters
  18367. ----------
  18368. attached : Union[bool, None]
  18369. timeout : Union[float, None]
  18370. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18371. """
  18372. __tracebackhide__ = True
  18373. return mapping.from_maybe_impl(
  18374. await self._impl_obj.to_be_attached(
  18375. attached=attached, timeout=to_milliseconds(timeout)
  18376. )
  18377. )
  18378. async def to_be_checked(
  18379. self,
  18380. *,
  18381. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18382. checked: typing.Optional[bool] = None,
  18383. indeterminate: typing.Optional[bool] = None,
  18384. ) -> None:
  18385. """LocatorAssertions.to_be_checked
  18386. Ensures the `Locator` points to a checked input.
  18387. **Usage**
  18388. ```py
  18389. from playwright.async_api import expect
  18390. locator = page.get_by_label(\"Subscribe to newsletter\")
  18391. await expect(locator).to_be_checked()
  18392. ```
  18393. Parameters
  18394. ----------
  18395. timeout : Union[float, None]
  18396. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18397. checked : Union[bool, None]
  18398. Provides state to assert for. Asserts for input to be checked by default. This option can't be used when
  18399. `indeterminate` is set to true.
  18400. indeterminate : Union[bool, None]
  18401. Asserts that the element is in the indeterminate (mixed) state. Only supported for checkboxes and radio buttons.
  18402. This option can't be true when `checked` is provided.
  18403. """
  18404. __tracebackhide__ = True
  18405. return mapping.from_maybe_impl(
  18406. await self._impl_obj.to_be_checked(
  18407. timeout=to_milliseconds(timeout),
  18408. checked=checked,
  18409. indeterminate=indeterminate,
  18410. )
  18411. )
  18412. async def not_to_be_attached(
  18413. self,
  18414. *,
  18415. attached: typing.Optional[bool] = None,
  18416. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18417. ) -> None:
  18418. """LocatorAssertions.not_to_be_attached
  18419. The opposite of `locator_assertions.to_be_attached()`.
  18420. Parameters
  18421. ----------
  18422. attached : Union[bool, None]
  18423. timeout : Union[float, None]
  18424. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18425. """
  18426. __tracebackhide__ = True
  18427. return mapping.from_maybe_impl(
  18428. await self._impl_obj.not_to_be_attached(
  18429. attached=attached, timeout=to_milliseconds(timeout)
  18430. )
  18431. )
  18432. async def not_to_be_checked(
  18433. self,
  18434. *,
  18435. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18436. ) -> None:
  18437. """LocatorAssertions.not_to_be_checked
  18438. The opposite of `locator_assertions.to_be_checked()`.
  18439. Parameters
  18440. ----------
  18441. timeout : Union[float, None]
  18442. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18443. """
  18444. __tracebackhide__ = True
  18445. return mapping.from_maybe_impl(
  18446. await self._impl_obj.not_to_be_checked(timeout=to_milliseconds(timeout))
  18447. )
  18448. async def to_be_disabled(
  18449. self,
  18450. *,
  18451. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18452. ) -> None:
  18453. """LocatorAssertions.to_be_disabled
  18454. Ensures the `Locator` points to a disabled element. Element is disabled if it has \"disabled\" attribute or is
  18455. disabled via
  18456. ['aria-disabled'](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled). Note
  18457. that only native control elements such as HTML `button`, `input`, `select`, `textarea`, `option`, `optgroup` can be
  18458. disabled by setting \"disabled\" attribute. \"disabled\" attribute on other elements is ignored by the browser.
  18459. **Usage**
  18460. ```py
  18461. from playwright.async_api import expect
  18462. locator = page.locator(\"button.submit\")
  18463. await expect(locator).to_be_disabled()
  18464. ```
  18465. Parameters
  18466. ----------
  18467. timeout : Union[float, None]
  18468. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18469. """
  18470. __tracebackhide__ = True
  18471. return mapping.from_maybe_impl(
  18472. await self._impl_obj.to_be_disabled(timeout=to_milliseconds(timeout))
  18473. )
  18474. async def not_to_be_disabled(
  18475. self,
  18476. *,
  18477. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18478. ) -> None:
  18479. """LocatorAssertions.not_to_be_disabled
  18480. The opposite of `locator_assertions.to_be_disabled()`.
  18481. Parameters
  18482. ----------
  18483. timeout : Union[float, None]
  18484. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18485. """
  18486. __tracebackhide__ = True
  18487. return mapping.from_maybe_impl(
  18488. await self._impl_obj.not_to_be_disabled(timeout=to_milliseconds(timeout))
  18489. )
  18490. async def to_be_editable(
  18491. self,
  18492. *,
  18493. editable: typing.Optional[bool] = None,
  18494. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18495. ) -> None:
  18496. """LocatorAssertions.to_be_editable
  18497. Ensures the `Locator` points to an editable element.
  18498. **Usage**
  18499. ```py
  18500. from playwright.async_api import expect
  18501. locator = page.get_by_role(\"textbox\")
  18502. await expect(locator).to_be_editable()
  18503. ```
  18504. Parameters
  18505. ----------
  18506. editable : Union[bool, None]
  18507. timeout : Union[float, None]
  18508. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18509. """
  18510. __tracebackhide__ = True
  18511. return mapping.from_maybe_impl(
  18512. await self._impl_obj.to_be_editable(
  18513. editable=editable, timeout=to_milliseconds(timeout)
  18514. )
  18515. )
  18516. async def not_to_be_editable(
  18517. self,
  18518. *,
  18519. editable: typing.Optional[bool] = None,
  18520. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18521. ) -> None:
  18522. """LocatorAssertions.not_to_be_editable
  18523. The opposite of `locator_assertions.to_be_editable()`.
  18524. Parameters
  18525. ----------
  18526. editable : Union[bool, None]
  18527. timeout : Union[float, None]
  18528. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18529. """
  18530. __tracebackhide__ = True
  18531. return mapping.from_maybe_impl(
  18532. await self._impl_obj.not_to_be_editable(
  18533. editable=editable, timeout=to_milliseconds(timeout)
  18534. )
  18535. )
  18536. async def to_be_empty(
  18537. self,
  18538. *,
  18539. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18540. ) -> None:
  18541. """LocatorAssertions.to_be_empty
  18542. Ensures the `Locator` points to an empty editable element or to a DOM node that has no text.
  18543. **Usage**
  18544. ```py
  18545. from playwright.async_api import expect
  18546. locator = page.locator(\"div.warning\")
  18547. await expect(locator).to_be_empty()
  18548. ```
  18549. Parameters
  18550. ----------
  18551. timeout : Union[float, None]
  18552. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18553. """
  18554. __tracebackhide__ = True
  18555. return mapping.from_maybe_impl(
  18556. await self._impl_obj.to_be_empty(timeout=to_milliseconds(timeout))
  18557. )
  18558. async def not_to_be_empty(
  18559. self,
  18560. *,
  18561. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18562. ) -> None:
  18563. """LocatorAssertions.not_to_be_empty
  18564. The opposite of `locator_assertions.to_be_empty()`.
  18565. Parameters
  18566. ----------
  18567. timeout : Union[float, None]
  18568. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18569. """
  18570. __tracebackhide__ = True
  18571. return mapping.from_maybe_impl(
  18572. await self._impl_obj.not_to_be_empty(timeout=to_milliseconds(timeout))
  18573. )
  18574. async def to_be_enabled(
  18575. self,
  18576. *,
  18577. enabled: typing.Optional[bool] = None,
  18578. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18579. ) -> None:
  18580. """LocatorAssertions.to_be_enabled
  18581. Ensures the `Locator` points to an enabled element.
  18582. **Usage**
  18583. ```py
  18584. from playwright.async_api import expect
  18585. locator = page.locator(\"button.submit\")
  18586. await expect(locator).to_be_enabled()
  18587. ```
  18588. Parameters
  18589. ----------
  18590. enabled : Union[bool, None]
  18591. timeout : Union[float, None]
  18592. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18593. """
  18594. __tracebackhide__ = True
  18595. return mapping.from_maybe_impl(
  18596. await self._impl_obj.to_be_enabled(
  18597. enabled=enabled, timeout=to_milliseconds(timeout)
  18598. )
  18599. )
  18600. async def not_to_be_enabled(
  18601. self,
  18602. *,
  18603. enabled: typing.Optional[bool] = None,
  18604. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18605. ) -> None:
  18606. """LocatorAssertions.not_to_be_enabled
  18607. The opposite of `locator_assertions.to_be_enabled()`.
  18608. Parameters
  18609. ----------
  18610. enabled : Union[bool, None]
  18611. timeout : Union[float, None]
  18612. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18613. """
  18614. __tracebackhide__ = True
  18615. return mapping.from_maybe_impl(
  18616. await self._impl_obj.not_to_be_enabled(
  18617. enabled=enabled, timeout=to_milliseconds(timeout)
  18618. )
  18619. )
  18620. async def to_be_hidden(
  18621. self,
  18622. *,
  18623. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18624. ) -> None:
  18625. """LocatorAssertions.to_be_hidden
  18626. Ensures that `Locator` either does not resolve to any DOM node, or resolves to a
  18627. [non-visible](https://playwright.dev/python/docs/actionability#visible) one.
  18628. **Usage**
  18629. ```py
  18630. from playwright.async_api import expect
  18631. locator = page.locator('.my-element')
  18632. await expect(locator).to_be_hidden()
  18633. ```
  18634. Parameters
  18635. ----------
  18636. timeout : Union[float, None]
  18637. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18638. """
  18639. __tracebackhide__ = True
  18640. return mapping.from_maybe_impl(
  18641. await self._impl_obj.to_be_hidden(timeout=to_milliseconds(timeout))
  18642. )
  18643. async def not_to_be_hidden(
  18644. self,
  18645. *,
  18646. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18647. ) -> None:
  18648. """LocatorAssertions.not_to_be_hidden
  18649. The opposite of `locator_assertions.to_be_hidden()`.
  18650. Parameters
  18651. ----------
  18652. timeout : Union[float, None]
  18653. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18654. """
  18655. __tracebackhide__ = True
  18656. return mapping.from_maybe_impl(
  18657. await self._impl_obj.not_to_be_hidden(timeout=to_milliseconds(timeout))
  18658. )
  18659. async def to_be_visible(
  18660. self,
  18661. *,
  18662. visible: typing.Optional[bool] = None,
  18663. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18664. ) -> None:
  18665. """LocatorAssertions.to_be_visible
  18666. Ensures that `Locator` points to an attached and [visible](https://playwright.dev/python/docs/actionability#visible) DOM node.
  18667. To check that at least one element from the list is visible, use `locator.first()`.
  18668. **Usage**
  18669. ```py
  18670. # A specific element is visible.
  18671. await expect(page.get_by_text(\"Welcome\")).to_be_visible()
  18672. # At least one item in the list is visible.
  18673. await expect(page.get_by_test_id(\"todo-item\").first).to_be_visible()
  18674. # At least one of the two elements is visible, possibly both.
  18675. await expect(
  18676. page.get_by_role(\"button\", name=\"Sign in\")
  18677. .or_(page.get_by_role(\"button\", name=\"Sign up\"))
  18678. .first
  18679. ).to_be_visible()
  18680. ```
  18681. Parameters
  18682. ----------
  18683. visible : Union[bool, None]
  18684. timeout : Union[float, None]
  18685. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18686. """
  18687. __tracebackhide__ = True
  18688. return mapping.from_maybe_impl(
  18689. await self._impl_obj.to_be_visible(
  18690. visible=visible, timeout=to_milliseconds(timeout)
  18691. )
  18692. )
  18693. async def not_to_be_visible(
  18694. self,
  18695. *,
  18696. visible: typing.Optional[bool] = None,
  18697. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18698. ) -> None:
  18699. """LocatorAssertions.not_to_be_visible
  18700. The opposite of `locator_assertions.to_be_visible()`.
  18701. Parameters
  18702. ----------
  18703. visible : Union[bool, None]
  18704. timeout : Union[float, None]
  18705. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18706. """
  18707. __tracebackhide__ = True
  18708. return mapping.from_maybe_impl(
  18709. await self._impl_obj.not_to_be_visible(
  18710. visible=visible, timeout=to_milliseconds(timeout)
  18711. )
  18712. )
  18713. async def to_be_focused(
  18714. self,
  18715. *,
  18716. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18717. ) -> None:
  18718. """LocatorAssertions.to_be_focused
  18719. Ensures the `Locator` points to a focused DOM node.
  18720. **Usage**
  18721. ```py
  18722. from playwright.async_api import expect
  18723. locator = page.get_by_role(\"textbox\")
  18724. await expect(locator).to_be_focused()
  18725. ```
  18726. Parameters
  18727. ----------
  18728. timeout : Union[float, None]
  18729. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18730. """
  18731. __tracebackhide__ = True
  18732. return mapping.from_maybe_impl(
  18733. await self._impl_obj.to_be_focused(timeout=to_milliseconds(timeout))
  18734. )
  18735. async def not_to_be_focused(
  18736. self,
  18737. *,
  18738. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18739. ) -> None:
  18740. """LocatorAssertions.not_to_be_focused
  18741. The opposite of `locator_assertions.to_be_focused()`.
  18742. Parameters
  18743. ----------
  18744. timeout : Union[float, None]
  18745. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18746. """
  18747. __tracebackhide__ = True
  18748. return mapping.from_maybe_impl(
  18749. await self._impl_obj.not_to_be_focused(timeout=to_milliseconds(timeout))
  18750. )
  18751. async def to_be_in_viewport(
  18752. self,
  18753. *,
  18754. ratio: typing.Optional[float] = None,
  18755. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18756. ) -> None:
  18757. """LocatorAssertions.to_be_in_viewport
  18758. Ensures the `Locator` points to an element that intersects viewport, according to the
  18759. [intersection observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
  18760. **Usage**
  18761. ```py
  18762. from playwright.async_api import expect
  18763. locator = page.get_by_role(\"button\")
  18764. # Make sure at least some part of element intersects viewport.
  18765. await expect(locator).to_be_in_viewport()
  18766. # Make sure element is fully outside of viewport.
  18767. await expect(locator).not_to_be_in_viewport()
  18768. # Make sure that at least half of the element intersects viewport.
  18769. await expect(locator).to_be_in_viewport(ratio=0.5)
  18770. ```
  18771. Parameters
  18772. ----------
  18773. ratio : Union[float, None]
  18774. The minimal ratio of the element to intersect viewport. If equals to `0`, then element should intersect viewport at
  18775. any positive ratio. Defaults to `0`.
  18776. timeout : Union[float, None]
  18777. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18778. """
  18779. __tracebackhide__ = True
  18780. return mapping.from_maybe_impl(
  18781. await self._impl_obj.to_be_in_viewport(
  18782. ratio=ratio, timeout=to_milliseconds(timeout)
  18783. )
  18784. )
  18785. async def not_to_be_in_viewport(
  18786. self,
  18787. *,
  18788. ratio: typing.Optional[float] = None,
  18789. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18790. ) -> None:
  18791. """LocatorAssertions.not_to_be_in_viewport
  18792. The opposite of `locator_assertions.to_be_in_viewport()`.
  18793. Parameters
  18794. ----------
  18795. ratio : Union[float, None]
  18796. timeout : Union[float, None]
  18797. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18798. """
  18799. __tracebackhide__ = True
  18800. return mapping.from_maybe_impl(
  18801. await self._impl_obj.not_to_be_in_viewport(
  18802. ratio=ratio, timeout=to_milliseconds(timeout)
  18803. )
  18804. )
  18805. async def to_have_accessible_description(
  18806. self,
  18807. description: typing.Union[str, typing.Pattern[str]],
  18808. *,
  18809. ignore_case: typing.Optional[bool] = None,
  18810. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18811. ) -> None:
  18812. """LocatorAssertions.to_have_accessible_description
  18813. Ensures the `Locator` points to an element with a given
  18814. [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  18815. **Usage**
  18816. ```py
  18817. locator = page.get_by_test_id(\"save-button\")
  18818. await expect(locator).to_have_accessible_description(\"Save results to disk\")
  18819. ```
  18820. Parameters
  18821. ----------
  18822. description : Union[Pattern[str], str]
  18823. Expected accessible description.
  18824. ignore_case : Union[bool, None]
  18825. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  18826. expression flag if specified.
  18827. timeout : Union[float, None]
  18828. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18829. """
  18830. __tracebackhide__ = True
  18831. return mapping.from_maybe_impl(
  18832. await self._impl_obj.to_have_accessible_description(
  18833. description=description,
  18834. ignoreCase=ignore_case,
  18835. timeout=to_milliseconds(timeout),
  18836. )
  18837. )
  18838. async def not_to_have_accessible_description(
  18839. self,
  18840. name: typing.Union[str, typing.Pattern[str]],
  18841. *,
  18842. ignore_case: typing.Optional[bool] = None,
  18843. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18844. ) -> None:
  18845. """LocatorAssertions.not_to_have_accessible_description
  18846. The opposite of `locator_assertions.to_have_accessible_description()`.
  18847. Parameters
  18848. ----------
  18849. name : Union[Pattern[str], str]
  18850. Expected accessible description.
  18851. ignore_case : Union[bool, None]
  18852. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  18853. expression flag if specified.
  18854. timeout : Union[float, None]
  18855. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18856. """
  18857. __tracebackhide__ = True
  18858. return mapping.from_maybe_impl(
  18859. await self._impl_obj.not_to_have_accessible_description(
  18860. name=name, ignoreCase=ignore_case, timeout=to_milliseconds(timeout)
  18861. )
  18862. )
  18863. async def to_have_accessible_name(
  18864. self,
  18865. name: typing.Union[str, typing.Pattern[str]],
  18866. *,
  18867. ignore_case: typing.Optional[bool] = None,
  18868. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18869. ) -> None:
  18870. """LocatorAssertions.to_have_accessible_name
  18871. Ensures the `Locator` points to an element with a given
  18872. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  18873. **Usage**
  18874. ```py
  18875. locator = page.get_by_test_id(\"save-button\")
  18876. await expect(locator).to_have_accessible_name(\"Save to disk\")
  18877. ```
  18878. Parameters
  18879. ----------
  18880. name : Union[Pattern[str], str]
  18881. Expected accessible name.
  18882. ignore_case : Union[bool, None]
  18883. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  18884. expression flag if specified.
  18885. timeout : Union[float, None]
  18886. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18887. """
  18888. __tracebackhide__ = True
  18889. return mapping.from_maybe_impl(
  18890. await self._impl_obj.to_have_accessible_name(
  18891. name=name, ignoreCase=ignore_case, timeout=to_milliseconds(timeout)
  18892. )
  18893. )
  18894. async def not_to_have_accessible_name(
  18895. self,
  18896. name: typing.Union[str, typing.Pattern[str]],
  18897. *,
  18898. ignore_case: typing.Optional[bool] = None,
  18899. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  18900. ) -> None:
  18901. """LocatorAssertions.not_to_have_accessible_name
  18902. The opposite of `locator_assertions.to_have_accessible_name()`.
  18903. Parameters
  18904. ----------
  18905. name : Union[Pattern[str], str]
  18906. Expected accessible name.
  18907. ignore_case : Union[bool, None]
  18908. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  18909. expression flag if specified.
  18910. timeout : Union[float, None]
  18911. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  18912. """
  18913. __tracebackhide__ = True
  18914. return mapping.from_maybe_impl(
  18915. await self._impl_obj.not_to_have_accessible_name(
  18916. name=name, ignoreCase=ignore_case, timeout=to_milliseconds(timeout)
  18917. )
  18918. )
  18919. async def to_have_role(
  18920. self,
  18921. role: Literal[
  18922. "alert",
  18923. "alertdialog",
  18924. "application",
  18925. "article",
  18926. "banner",
  18927. "blockquote",
  18928. "button",
  18929. "caption",
  18930. "cell",
  18931. "checkbox",
  18932. "code",
  18933. "columnheader",
  18934. "combobox",
  18935. "complementary",
  18936. "contentinfo",
  18937. "definition",
  18938. "deletion",
  18939. "dialog",
  18940. "directory",
  18941. "document",
  18942. "emphasis",
  18943. "feed",
  18944. "figure",
  18945. "form",
  18946. "generic",
  18947. "grid",
  18948. "gridcell",
  18949. "group",
  18950. "heading",
  18951. "img",
  18952. "insertion",
  18953. "link",
  18954. "list",
  18955. "listbox",
  18956. "listitem",
  18957. "log",
  18958. "main",
  18959. "marquee",
  18960. "math",
  18961. "menu",
  18962. "menubar",
  18963. "menuitem",
  18964. "menuitemcheckbox",
  18965. "menuitemradio",
  18966. "meter",
  18967. "navigation",
  18968. "none",
  18969. "note",
  18970. "option",
  18971. "paragraph",
  18972. "presentation",
  18973. "progressbar",
  18974. "radio",
  18975. "radiogroup",
  18976. "region",
  18977. "row",
  18978. "rowgroup",
  18979. "rowheader",
  18980. "scrollbar",
  18981. "search",
  18982. "searchbox",
  18983. "separator",
  18984. "slider",
  18985. "spinbutton",
  18986. "status",
  18987. "strong",
  18988. "subscript",
  18989. "superscript",
  18990. "switch",
  18991. "tab",
  18992. "table",
  18993. "tablist",
  18994. "tabpanel",
  18995. "term",
  18996. "textbox",
  18997. "time",
  18998. "timer",
  18999. "toolbar",
  19000. "tooltip",
  19001. "tree",
  19002. "treegrid",
  19003. "treeitem",
  19004. ],
  19005. *,
  19006. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  19007. ) -> None:
  19008. """LocatorAssertions.to_have_role
  19009. Ensures the `Locator` points to an element with a given [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles).
  19010. Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass
  19011. role `\"checkbox\"` on an element with a subclass role `\"switch\"` will fail.
  19012. **Usage**
  19013. ```py
  19014. locator = page.get_by_test_id(\"save-button\")
  19015. await expect(locator).to_have_role(\"button\")
  19016. ```
  19017. Parameters
  19018. ----------
  19019. 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"]
  19020. Required aria role.
  19021. timeout : Union[float, None]
  19022. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  19023. """
  19024. __tracebackhide__ = True
  19025. return mapping.from_maybe_impl(
  19026. await self._impl_obj.to_have_role(
  19027. role=role, timeout=to_milliseconds(timeout)
  19028. )
  19029. )
  19030. async def to_have_accessible_error_message(
  19031. self,
  19032. error_message: typing.Union[str, typing.Pattern[str]],
  19033. *,
  19034. ignore_case: typing.Optional[bool] = None,
  19035. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  19036. ) -> None:
  19037. """LocatorAssertions.to_have_accessible_error_message
  19038. Ensures the `Locator` points to an element with a given
  19039. [aria errormessage](https://w3c.github.io/aria/#aria-errormessage).
  19040. **Usage**
  19041. ```py
  19042. locator = page.get_by_test_id(\"username-input\")
  19043. await expect(locator).to_have_accessible_error_message(\"Username is required.\")
  19044. ```
  19045. Parameters
  19046. ----------
  19047. error_message : Union[Pattern[str], str]
  19048. Expected accessible error message.
  19049. ignore_case : Union[bool, None]
  19050. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  19051. expression flag if specified.
  19052. timeout : Union[float, None]
  19053. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  19054. """
  19055. __tracebackhide__ = True
  19056. return mapping.from_maybe_impl(
  19057. await self._impl_obj.to_have_accessible_error_message(
  19058. errorMessage=error_message,
  19059. ignoreCase=ignore_case,
  19060. timeout=to_milliseconds(timeout),
  19061. )
  19062. )
  19063. async def not_to_have_accessible_error_message(
  19064. self,
  19065. error_message: typing.Union[str, typing.Pattern[str]],
  19066. *,
  19067. ignore_case: typing.Optional[bool] = None,
  19068. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  19069. ) -> None:
  19070. """LocatorAssertions.not_to_have_accessible_error_message
  19071. The opposite of `locator_assertions.to_have_accessible_error_message()`.
  19072. Parameters
  19073. ----------
  19074. error_message : Union[Pattern[str], str]
  19075. Expected accessible error message.
  19076. ignore_case : Union[bool, None]
  19077. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  19078. expression flag if specified.
  19079. timeout : Union[float, None]
  19080. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  19081. """
  19082. __tracebackhide__ = True
  19083. return mapping.from_maybe_impl(
  19084. await self._impl_obj.not_to_have_accessible_error_message(
  19085. errorMessage=error_message,
  19086. ignoreCase=ignore_case,
  19087. timeout=to_milliseconds(timeout),
  19088. )
  19089. )
  19090. async def not_to_have_role(
  19091. self,
  19092. role: Literal[
  19093. "alert",
  19094. "alertdialog",
  19095. "application",
  19096. "article",
  19097. "banner",
  19098. "blockquote",
  19099. "button",
  19100. "caption",
  19101. "cell",
  19102. "checkbox",
  19103. "code",
  19104. "columnheader",
  19105. "combobox",
  19106. "complementary",
  19107. "contentinfo",
  19108. "definition",
  19109. "deletion",
  19110. "dialog",
  19111. "directory",
  19112. "document",
  19113. "emphasis",
  19114. "feed",
  19115. "figure",
  19116. "form",
  19117. "generic",
  19118. "grid",
  19119. "gridcell",
  19120. "group",
  19121. "heading",
  19122. "img",
  19123. "insertion",
  19124. "link",
  19125. "list",
  19126. "listbox",
  19127. "listitem",
  19128. "log",
  19129. "main",
  19130. "marquee",
  19131. "math",
  19132. "menu",
  19133. "menubar",
  19134. "menuitem",
  19135. "menuitemcheckbox",
  19136. "menuitemradio",
  19137. "meter",
  19138. "navigation",
  19139. "none",
  19140. "note",
  19141. "option",
  19142. "paragraph",
  19143. "presentation",
  19144. "progressbar",
  19145. "radio",
  19146. "radiogroup",
  19147. "region",
  19148. "row",
  19149. "rowgroup",
  19150. "rowheader",
  19151. "scrollbar",
  19152. "search",
  19153. "searchbox",
  19154. "separator",
  19155. "slider",
  19156. "spinbutton",
  19157. "status",
  19158. "strong",
  19159. "subscript",
  19160. "superscript",
  19161. "switch",
  19162. "tab",
  19163. "table",
  19164. "tablist",
  19165. "tabpanel",
  19166. "term",
  19167. "textbox",
  19168. "time",
  19169. "timer",
  19170. "toolbar",
  19171. "tooltip",
  19172. "tree",
  19173. "treegrid",
  19174. "treeitem",
  19175. ],
  19176. *,
  19177. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  19178. ) -> None:
  19179. """LocatorAssertions.not_to_have_role
  19180. The opposite of `locator_assertions.to_have_role()`.
  19181. Parameters
  19182. ----------
  19183. 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"]
  19184. Required aria role.
  19185. timeout : Union[float, None]
  19186. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  19187. """
  19188. __tracebackhide__ = True
  19189. return mapping.from_maybe_impl(
  19190. await self._impl_obj.not_to_have_role(
  19191. role=role, timeout=to_milliseconds(timeout)
  19192. )
  19193. )
  19194. async def to_match_aria_snapshot(
  19195. self,
  19196. expected: str,
  19197. *,
  19198. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  19199. ) -> None:
  19200. """LocatorAssertions.to_match_aria_snapshot
  19201. Asserts that the target element matches the given [accessibility snapshot](https://playwright.dev/python/docs/aria-snapshots).
  19202. **Usage**
  19203. ```py
  19204. await page.goto(\"https://demo.playwright.dev/todomvc/\")
  19205. await expect(page.locator('body')).to_match_aria_snapshot('''
  19206. - heading \"todos\"
  19207. - textbox \"What needs to be done?\"
  19208. ''')
  19209. ```
  19210. Parameters
  19211. ----------
  19212. expected : str
  19213. timeout : Union[float, None]
  19214. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  19215. """
  19216. __tracebackhide__ = True
  19217. return mapping.from_maybe_impl(
  19218. await self._impl_obj.to_match_aria_snapshot(
  19219. expected=expected, timeout=to_milliseconds(timeout)
  19220. )
  19221. )
  19222. async def not_to_match_aria_snapshot(
  19223. self,
  19224. expected: str,
  19225. *,
  19226. timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None,
  19227. ) -> None:
  19228. """LocatorAssertions.not_to_match_aria_snapshot
  19229. The opposite of `locator_assertions.to_match_aria_snapshot()`.
  19230. Parameters
  19231. ----------
  19232. expected : str
  19233. timeout : Union[float, None]
  19234. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  19235. """
  19236. __tracebackhide__ = True
  19237. return mapping.from_maybe_impl(
  19238. await self._impl_obj.not_to_match_aria_snapshot(
  19239. expected=expected, timeout=to_milliseconds(timeout)
  19240. )
  19241. )
  19242. mapping.register(LocatorAssertionsImpl, LocatorAssertions)
  19243. class APIResponseAssertions(AsyncBase):
  19244. async def to_be_ok(self) -> None:
  19245. """APIResponseAssertions.to_be_ok
  19246. Ensures the response status code is within `200..299` range.
  19247. **Usage**
  19248. ```py
  19249. from playwright.async_api import expect
  19250. # ...
  19251. await expect(response).to_be_ok()
  19252. ```
  19253. """
  19254. __tracebackhide__ = True
  19255. return mapping.from_maybe_impl(await self._impl_obj.to_be_ok())
  19256. async def not_to_be_ok(self) -> None:
  19257. """APIResponseAssertions.not_to_be_ok
  19258. The opposite of `a_pi_response_assertions.to_be_ok()`.
  19259. """
  19260. __tracebackhide__ = True
  19261. return mapping.from_maybe_impl(await self._impl_obj.not_to_be_ok())
  19262. mapping.register(APIResponseAssertionsImpl, APIResponseAssertions)
  19263. class Disposable(AsyncContextManager):
  19264. async def dispose(self) -> None:
  19265. """Disposable.dispose
  19266. Removes the associated resource. For example, removes the init script installed via `page.add_init_script()`
  19267. or `browser_context.add_init_script()`.
  19268. """
  19269. return mapping.from_maybe_impl(await self._impl_obj.dispose())
  19270. async def close(self) -> None:
  19271. return mapping.from_maybe_impl(await self._impl_obj.close())
  19272. mapping.register(DisposableImpl, Disposable)