_generated.py 827 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007
  1. # Copyright (c) Microsoft Corporation.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import datetime
  15. import pathlib
  16. import typing
  17. from typing import Literal
  18. from playwright._impl._api_structures import (
  19. ClientCertificate,
  20. Cookie,
  21. FilePayload,
  22. FloatRect,
  23. Geolocation,
  24. HttpCredentials,
  25. NameValue,
  26. PdfMargins,
  27. Position,
  28. ProxySettings,
  29. RemoteAddr,
  30. RequestSizes,
  31. ResourceTiming,
  32. SecurityDetails,
  33. SetCookieParam,
  34. SourceLocation,
  35. StorageState,
  36. TracingGroupLocation,
  37. ViewportSize,
  38. )
  39. from playwright._impl._assertions import (
  40. APIResponseAssertions as APIResponseAssertionsImpl,
  41. )
  42. from playwright._impl._assertions import LocatorAssertions as LocatorAssertionsImpl
  43. from playwright._impl._assertions import PageAssertions as PageAssertionsImpl
  44. from playwright._impl._async_base import (
  45. AsyncBase,
  46. AsyncContextManager,
  47. AsyncEventContextManager,
  48. mapping,
  49. )
  50. from playwright._impl._browser import Browser as BrowserImpl
  51. from playwright._impl._browser_context import BrowserContext as BrowserContextImpl
  52. from playwright._impl._browser_type import BrowserType as BrowserTypeImpl
  53. from playwright._impl._cdp_session import CDPSession as CDPSessionImpl
  54. from playwright._impl._clock import Clock as ClockImpl
  55. from playwright._impl._console_message import ConsoleMessage as ConsoleMessageImpl
  56. from playwright._impl._dialog import Dialog as DialogImpl
  57. from playwright._impl._download import Download as DownloadImpl
  58. from playwright._impl._element_handle import ElementHandle as ElementHandleImpl
  59. from playwright._impl._errors import Error
  60. from playwright._impl._fetch import APIRequest as APIRequestImpl
  61. from playwright._impl._fetch import APIRequestContext as APIRequestContextImpl
  62. from playwright._impl._fetch import APIResponse as APIResponseImpl
  63. from playwright._impl._file_chooser import FileChooser as FileChooserImpl
  64. from playwright._impl._frame import Frame as FrameImpl
  65. from playwright._impl._input import Keyboard as KeyboardImpl
  66. from playwright._impl._input import Mouse as MouseImpl
  67. from playwright._impl._input import Touchscreen as TouchscreenImpl
  68. from playwright._impl._js_handle import JSHandle as JSHandleImpl
  69. from playwright._impl._locator import FrameLocator as FrameLocatorImpl
  70. from playwright._impl._locator import Locator as LocatorImpl
  71. from playwright._impl._network import Request as RequestImpl
  72. from playwright._impl._network import Response as ResponseImpl
  73. from playwright._impl._network import Route as RouteImpl
  74. from playwright._impl._network import WebSocket as WebSocketImpl
  75. from playwright._impl._network import WebSocketRoute as WebSocketRouteImpl
  76. from playwright._impl._page import Page as PageImpl
  77. from playwright._impl._page import Worker as WorkerImpl
  78. from playwright._impl._playwright import Playwright as PlaywrightImpl
  79. from playwright._impl._selectors import Selectors as SelectorsImpl
  80. from playwright._impl._tracing import Tracing as TracingImpl
  81. from playwright._impl._video import Video as VideoImpl
  82. from playwright._impl._web_error import WebError as WebErrorImpl
  83. class Request(AsyncBase):
  84. @property
  85. def url(self) -> str:
  86. """Request.url
  87. URL of the request.
  88. Returns
  89. -------
  90. str
  91. """
  92. return mapping.from_maybe_impl(self._impl_obj.url)
  93. @property
  94. def resource_type(self) -> str:
  95. """Request.resource_type
  96. Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the
  97. following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,
  98. `eventsource`, `websocket`, `manifest`, `other`.
  99. Returns
  100. -------
  101. str
  102. """
  103. return mapping.from_maybe_impl(self._impl_obj.resource_type)
  104. @property
  105. def service_worker(self) -> typing.Optional["Worker"]:
  106. """Request.service_worker
  107. The Service `Worker` that is performing the request.
  108. **Details**
  109. This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.
  110. Requests originated in a Service Worker do not have a `request.frame()` available.
  111. Returns
  112. -------
  113. Union[Worker, None]
  114. """
  115. return mapping.from_impl_nullable(self._impl_obj.service_worker)
  116. @property
  117. def method(self) -> str:
  118. """Request.method
  119. Request's method (GET, POST, etc.)
  120. Returns
  121. -------
  122. str
  123. """
  124. return mapping.from_maybe_impl(self._impl_obj.method)
  125. @property
  126. def post_data(self) -> typing.Optional[str]:
  127. """Request.post_data
  128. Request's post body, if any.
  129. Returns
  130. -------
  131. Union[str, None]
  132. """
  133. return mapping.from_maybe_impl(self._impl_obj.post_data)
  134. @property
  135. def post_data_json(self) -> typing.Optional[typing.Any]:
  136. """Request.post_data_json
  137. Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.
  138. When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.
  139. Otherwise it will be parsed as JSON.
  140. Returns
  141. -------
  142. Union[Any, None]
  143. """
  144. return mapping.from_maybe_impl(self._impl_obj.post_data_json)
  145. @property
  146. def post_data_buffer(self) -> typing.Optional[bytes]:
  147. """Request.post_data_buffer
  148. Request's post body in a binary form, if any.
  149. Returns
  150. -------
  151. Union[bytes, None]
  152. """
  153. return mapping.from_maybe_impl(self._impl_obj.post_data_buffer)
  154. @property
  155. def frame(self) -> "Frame":
  156. """Request.frame
  157. Returns the `Frame` that initiated this request.
  158. **Usage**
  159. ```py
  160. frame_url = request.frame.url
  161. ```
  162. **Details**
  163. Note that in some cases the frame is not available, and this method will throw.
  164. - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.
  165. - When navigation request is issued before the corresponding frame is created. You can use
  166. `request.is_navigation_request()` to check that.
  167. Here is an example that handles all the cases:
  168. Returns
  169. -------
  170. Frame
  171. """
  172. return mapping.from_impl(self._impl_obj.frame)
  173. @property
  174. def redirected_from(self) -> typing.Optional["Request"]:
  175. """Request.redirected_from
  176. Request that was redirected by the server to this one, if any.
  177. When the server responds with a redirect, Playwright creates a new `Request` object. The two requests are connected
  178. by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
  179. construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
  180. **Usage**
  181. For example, if the website `http://example.com` redirects to `https://example.com`:
  182. ```py
  183. response = await page.goto(\"http://example.com\")
  184. print(response.request.redirected_from.url) # \"http://example.com\"
  185. ```
  186. If the website `https://google.com` has no redirects:
  187. ```py
  188. response = await page.goto(\"https://google.com\")
  189. print(response.request.redirected_from) # None
  190. ```
  191. Returns
  192. -------
  193. Union[Request, None]
  194. """
  195. return mapping.from_impl_nullable(self._impl_obj.redirected_from)
  196. @property
  197. def redirected_to(self) -> typing.Optional["Request"]:
  198. """Request.redirected_to
  199. New request issued by the browser if the server responded with redirect.
  200. **Usage**
  201. This method is the opposite of `request.redirected_from()`:
  202. ```py
  203. assert request.redirected_from.redirected_to == request
  204. ```
  205. Returns
  206. -------
  207. Union[Request, None]
  208. """
  209. return mapping.from_impl_nullable(self._impl_obj.redirected_to)
  210. @property
  211. def failure(self) -> typing.Optional[str]:
  212. """Request.failure
  213. The method returns `null` unless this request has failed, as reported by `requestfailed` event.
  214. **Usage**
  215. Example of logging of all the failed requests:
  216. ```py
  217. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure))
  218. ```
  219. Returns
  220. -------
  221. Union[str, None]
  222. """
  223. return mapping.from_maybe_impl(self._impl_obj.failure)
  224. @property
  225. def timing(self) -> ResourceTiming:
  226. """Request.timing
  227. Returns resource timing information for given request. Most of the timing values become available upon the
  228. response, `responseEnd` becomes available when request finishes. Find more information at
  229. [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
  230. **Usage**
  231. ```py
  232. async with page.expect_event(\"requestfinished\") as request_info:
  233. await page.goto(\"http://example.com\")
  234. request = await request_info.value
  235. print(request.timing)
  236. ```
  237. Returns
  238. -------
  239. {startTime: float, domainLookupStart: float, domainLookupEnd: float, connectStart: float, secureConnectionStart: float, connectEnd: float, requestStart: float, responseStart: float, responseEnd: float}
  240. """
  241. return mapping.from_impl(self._impl_obj.timing)
  242. @property
  243. def headers(self) -> typing.Dict[str, str]:
  244. """Request.headers
  245. An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return
  246. security-related headers, including cookie-related ones. You can use `request.all_headers()` for complete
  247. list of headers that include `cookie` information.
  248. Returns
  249. -------
  250. Dict[str, str]
  251. """
  252. return mapping.from_maybe_impl(self._impl_obj.headers)
  253. async def sizes(self) -> RequestSizes:
  254. """Request.sizes
  255. Returns resource size information for given request.
  256. Returns
  257. -------
  258. {requestBodySize: int, requestHeadersSize: int, responseBodySize: int, responseHeadersSize: int}
  259. """
  260. return mapping.from_impl(await self._impl_obj.sizes())
  261. async def response(self) -> typing.Optional["Response"]:
  262. """Request.response
  263. Returns the matching `Response` object, or `null` if the response was not received due to error.
  264. Returns
  265. -------
  266. Union[Response, None]
  267. """
  268. return mapping.from_impl_nullable(await self._impl_obj.response())
  269. def is_navigation_request(self) -> bool:
  270. """Request.is_navigation_request
  271. Whether this request is driving frame's navigation.
  272. Some navigation requests are issued before the corresponding frame is created, and therefore do not have
  273. `request.frame()` available.
  274. Returns
  275. -------
  276. bool
  277. """
  278. return mapping.from_maybe_impl(self._impl_obj.is_navigation_request())
  279. async def all_headers(self) -> typing.Dict[str, str]:
  280. """Request.all_headers
  281. An object with all the request HTTP headers associated with this request. The header names are lower-cased.
  282. Returns
  283. -------
  284. Dict[str, str]
  285. """
  286. return mapping.from_maybe_impl(await self._impl_obj.all_headers())
  287. async def headers_array(self) -> typing.List[NameValue]:
  288. """Request.headers_array
  289. An array with all the request HTTP headers associated with this request. Unlike `request.all_headers()`,
  290. header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
  291. times.
  292. Returns
  293. -------
  294. List[{name: str, value: str}]
  295. """
  296. return mapping.from_impl_list(await self._impl_obj.headers_array())
  297. async def header_value(self, name: str) -> typing.Optional[str]:
  298. """Request.header_value
  299. Returns the value of the header matching the name. The name is case-insensitive.
  300. Parameters
  301. ----------
  302. name : str
  303. Name of the header.
  304. Returns
  305. -------
  306. Union[str, None]
  307. """
  308. return mapping.from_maybe_impl(await self._impl_obj.header_value(name=name))
  309. mapping.register(RequestImpl, Request)
  310. class Response(AsyncBase):
  311. @property
  312. def url(self) -> str:
  313. """Response.url
  314. Contains the URL of the response.
  315. Returns
  316. -------
  317. str
  318. """
  319. return mapping.from_maybe_impl(self._impl_obj.url)
  320. @property
  321. def ok(self) -> bool:
  322. """Response.ok
  323. Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
  324. Returns
  325. -------
  326. bool
  327. """
  328. return mapping.from_maybe_impl(self._impl_obj.ok)
  329. @property
  330. def status(self) -> int:
  331. """Response.status
  332. Contains the status code of the response (e.g., 200 for a success).
  333. Returns
  334. -------
  335. int
  336. """
  337. return mapping.from_maybe_impl(self._impl_obj.status)
  338. @property
  339. def status_text(self) -> str:
  340. """Response.status_text
  341. Contains the status text of the response (e.g. usually an \"OK\" for a success).
  342. Returns
  343. -------
  344. str
  345. """
  346. return mapping.from_maybe_impl(self._impl_obj.status_text)
  347. @property
  348. def headers(self) -> typing.Dict[str, str]:
  349. """Response.headers
  350. An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return
  351. security-related headers, including cookie-related ones. You can use `response.all_headers()` for complete
  352. list of headers that include `cookie` information.
  353. Returns
  354. -------
  355. Dict[str, str]
  356. """
  357. return mapping.from_maybe_impl(self._impl_obj.headers)
  358. @property
  359. def from_service_worker(self) -> bool:
  360. """Response.from_service_worker
  361. Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via
  362. [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).
  363. Returns
  364. -------
  365. bool
  366. """
  367. return mapping.from_maybe_impl(self._impl_obj.from_service_worker)
  368. @property
  369. def request(self) -> "Request":
  370. """Response.request
  371. Returns the matching `Request` object.
  372. Returns
  373. -------
  374. Request
  375. """
  376. return mapping.from_impl(self._impl_obj.request)
  377. @property
  378. def frame(self) -> "Frame":
  379. """Response.frame
  380. Returns the `Frame` that initiated this response.
  381. Returns
  382. -------
  383. Frame
  384. """
  385. return mapping.from_impl(self._impl_obj.frame)
  386. async def all_headers(self) -> typing.Dict[str, str]:
  387. """Response.all_headers
  388. An object with all the response HTTP headers associated with this response.
  389. Returns
  390. -------
  391. Dict[str, str]
  392. """
  393. return mapping.from_maybe_impl(await self._impl_obj.all_headers())
  394. async def headers_array(self) -> typing.List[NameValue]:
  395. """Response.headers_array
  396. An array with all the request HTTP headers associated with this response. Unlike `response.all_headers()`,
  397. header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
  398. times.
  399. Returns
  400. -------
  401. List[{name: str, value: str}]
  402. """
  403. return mapping.from_impl_list(await self._impl_obj.headers_array())
  404. async def header_value(self, name: str) -> typing.Optional[str]:
  405. """Response.header_value
  406. Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same
  407. name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\\n` separator is
  408. used. If no headers are found, `null` is returned.
  409. Parameters
  410. ----------
  411. name : str
  412. Name of the header.
  413. Returns
  414. -------
  415. Union[str, None]
  416. """
  417. return mapping.from_maybe_impl(await self._impl_obj.header_value(name=name))
  418. async def header_values(self, name: str) -> typing.List[str]:
  419. """Response.header_values
  420. Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.
  421. Parameters
  422. ----------
  423. name : str
  424. Name of the header.
  425. Returns
  426. -------
  427. List[str]
  428. """
  429. return mapping.from_maybe_impl(await self._impl_obj.header_values(name=name))
  430. async def server_addr(self) -> typing.Optional[RemoteAddr]:
  431. """Response.server_addr
  432. Returns the IP address and port of the server.
  433. Returns
  434. -------
  435. Union[{ipAddress: str, port: int}, None]
  436. """
  437. return mapping.from_impl_nullable(await self._impl_obj.server_addr())
  438. async def security_details(self) -> typing.Optional[SecurityDetails]:
  439. """Response.security_details
  440. Returns SSL and other security information.
  441. Returns
  442. -------
  443. Union[{issuer: Union[str, None], protocol: Union[str, None], subjectName: Union[str, None], validFrom: Union[float, None], validTo: Union[float, None]}, None]
  444. """
  445. return mapping.from_impl_nullable(await self._impl_obj.security_details())
  446. async def finished(self) -> None:
  447. """Response.finished
  448. Waits for this response to finish, returns always `null`.
  449. """
  450. return mapping.from_maybe_impl(await self._impl_obj.finished())
  451. async def body(self) -> bytes:
  452. """Response.body
  453. Returns the buffer with response body.
  454. Returns
  455. -------
  456. bytes
  457. """
  458. return mapping.from_maybe_impl(await self._impl_obj.body())
  459. async def text(self) -> str:
  460. """Response.text
  461. Returns the text representation of response body.
  462. Returns
  463. -------
  464. str
  465. """
  466. return mapping.from_maybe_impl(await self._impl_obj.text())
  467. async def json(self) -> typing.Any:
  468. """Response.json
  469. Returns the JSON representation of response body.
  470. This method will throw if the response body is not parsable via `JSON.parse`.
  471. Returns
  472. -------
  473. Any
  474. """
  475. return mapping.from_maybe_impl(await self._impl_obj.json())
  476. mapping.register(ResponseImpl, Response)
  477. class Route(AsyncBase):
  478. @property
  479. def request(self) -> "Request":
  480. """Route.request
  481. A request to be routed.
  482. Returns
  483. -------
  484. Request
  485. """
  486. return mapping.from_impl(self._impl_obj.request)
  487. async def abort(self, error_code: typing.Optional[str] = None) -> None:
  488. """Route.abort
  489. Aborts the route's request.
  490. Parameters
  491. ----------
  492. error_code : Union[str, None]
  493. Optional error code. Defaults to `failed`, could be one of the following:
  494. - `'aborted'` - An operation was aborted (due to user action)
  495. - `'accessdenied'` - Permission to access a resource, other than the network, was denied
  496. - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the
  497. specified host or network.
  498. - `'blockedbyclient'` - The client chose to block the request.
  499. - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are
  500. not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
  501. - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
  502. - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
  503. - `'connectionfailed'` - A connection attempt failed.
  504. - `'connectionrefused'` - A connection attempt was refused.
  505. - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
  506. - `'internetdisconnected'` - The Internet connection has been lost.
  507. - `'namenotresolved'` - The host name could not be resolved.
  508. - `'timedout'` - An operation timed out.
  509. - `'failed'` - A generic failure occurred.
  510. """
  511. return mapping.from_maybe_impl(await self._impl_obj.abort(errorCode=error_code))
  512. async def fulfill(
  513. self,
  514. *,
  515. status: typing.Optional[int] = None,
  516. headers: typing.Optional[typing.Dict[str, str]] = None,
  517. body: typing.Optional[typing.Union[str, bytes]] = None,
  518. json: typing.Optional[typing.Any] = None,
  519. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  520. content_type: typing.Optional[str] = None,
  521. response: typing.Optional["APIResponse"] = None,
  522. ) -> None:
  523. """Route.fulfill
  524. Fulfills route's request with given response.
  525. **Usage**
  526. An example of fulfilling all requests with 404 responses:
  527. ```py
  528. await page.route(\"**/*\", lambda route: route.fulfill(
  529. status=404,
  530. content_type=\"text/plain\",
  531. body=\"not found!\"))
  532. ```
  533. An example of serving static file:
  534. ```py
  535. await page.route(\"**/xhr_endpoint\", lambda route: route.fulfill(path=\"mock_data.json\"))
  536. ```
  537. Parameters
  538. ----------
  539. status : Union[int, None]
  540. Response status code, defaults to `200`.
  541. headers : Union[Dict[str, str], None]
  542. Response headers. Header values will be converted to a string.
  543. body : Union[bytes, str, None]
  544. Response body.
  545. json : Union[Any, None]
  546. JSON response. This method will set the content type to `application/json` if not set.
  547. path : Union[pathlib.Path, str, None]
  548. File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,
  549. then it is resolved relative to the current working directory.
  550. content_type : Union[str, None]
  551. If set, equals to setting `Content-Type` response header.
  552. response : Union[APIResponse, None]
  553. `APIResponse` to fulfill route's request with. Individual fields of the response (such as headers) can be
  554. overridden using fulfill options.
  555. """
  556. return mapping.from_maybe_impl(
  557. await self._impl_obj.fulfill(
  558. status=status,
  559. headers=mapping.to_impl(headers),
  560. body=body,
  561. json=mapping.to_impl(json),
  562. path=path,
  563. contentType=content_type,
  564. response=response._impl_obj if response else None,
  565. )
  566. )
  567. async def fetch(
  568. self,
  569. *,
  570. url: typing.Optional[str] = None,
  571. method: typing.Optional[str] = None,
  572. headers: typing.Optional[typing.Dict[str, str]] = None,
  573. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  574. max_redirects: typing.Optional[int] = None,
  575. max_retries: typing.Optional[int] = None,
  576. timeout: typing.Optional[float] = None,
  577. ) -> "APIResponse":
  578. """Route.fetch
  579. Performs the request and fetches result without fulfilling it, so that the response could be modified and then
  580. fulfilled.
  581. **Usage**
  582. ```py
  583. async def handle(route):
  584. response = await route.fetch()
  585. json = await response.json()
  586. json[\"message\"][\"big_red_dog\"] = []
  587. await route.fulfill(response=response, json=json)
  588. await page.route(\"https://dog.ceo/api/breeds/list/all\", handle)
  589. ```
  590. **Details**
  591. Note that `headers` option will apply to the fetched request as well as any redirects initiated by it. If you want
  592. to only apply `headers` to the original request, but not to redirects, look into `route.continue_()`
  593. instead.
  594. Parameters
  595. ----------
  596. url : Union[str, None]
  597. If set changes the request URL. New URL must have same protocol as original one.
  598. method : Union[str, None]
  599. If set changes the request method (e.g. GET or POST).
  600. headers : Union[Dict[str, str], None]
  601. If set changes the request HTTP headers. Header values will be converted to a string.
  602. post_data : Union[Any, bytes, str, None]
  603. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  604. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  605. header will be set to `application/octet-stream` if not explicitly set.
  606. max_redirects : Union[int, None]
  607. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  608. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  609. max_retries : Union[int, None]
  610. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  611. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  612. timeout : Union[float, None]
  613. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  614. Returns
  615. -------
  616. APIResponse
  617. """
  618. return mapping.from_impl(
  619. await self._impl_obj.fetch(
  620. url=url,
  621. method=method,
  622. headers=mapping.to_impl(headers),
  623. postData=mapping.to_impl(post_data),
  624. maxRedirects=max_redirects,
  625. maxRetries=max_retries,
  626. timeout=timeout,
  627. )
  628. )
  629. async def fallback(
  630. self,
  631. *,
  632. url: typing.Optional[str] = None,
  633. method: typing.Optional[str] = None,
  634. headers: typing.Optional[typing.Dict[str, str]] = None,
  635. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  636. ) -> None:
  637. """Route.fallback
  638. Continues route's request with optional overrides. The method is similar to `route.continue_()` with the
  639. difference that other matching handlers will be invoked before sending the request.
  640. **Usage**
  641. When several routes match the given pattern, they run in the order opposite to their registration. That way the
  642. last registered route can always override all the previous ones. In the example below, request will be handled by
  643. the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
  644. registered route.
  645. ```py
  646. await page.route(\"**/*\", lambda route: route.abort()) # Runs last.
  647. await page.route(\"**/*\", lambda route: route.fallback()) # Runs second.
  648. await page.route(\"**/*\", lambda route: route.fallback()) # Runs first.
  649. ```
  650. Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for
  651. example API calls vs page resources or GET requests vs POST requests as in the example below.
  652. ```py
  653. # Handle GET requests.
  654. async def handle_get(route):
  655. if route.request.method != \"GET\":
  656. await route.fallback()
  657. return
  658. # Handling GET only.
  659. # ...
  660. # Handle POST requests.
  661. async def handle_post(route):
  662. if route.request.method != \"POST\":
  663. await route.fallback()
  664. return
  665. # Handling POST only.
  666. # ...
  667. await page.route(\"**/*\", handle_get)
  668. await page.route(\"**/*\", handle_post)
  669. ```
  670. One can also modify request while falling back to the subsequent handler, that way intermediate route handler can
  671. modify url, method, headers and postData of the request.
  672. ```py
  673. async def handle(route, request):
  674. # override headers
  675. headers = {
  676. **request.headers,
  677. \"foo\": \"foo-value\", # set \"foo\" header
  678. \"bar\": None # remove \"bar\" header
  679. }
  680. await route.fallback(headers=headers)
  681. await page.route(\"**/*\", handle)
  682. ```
  683. Use `route.continue_()` to immediately send the request to the network, other matching handlers won't be
  684. invoked in that case.
  685. Parameters
  686. ----------
  687. url : Union[str, None]
  688. If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the
  689. route matching, all the routes are matched using the original request URL.
  690. method : Union[str, None]
  691. If set changes the request method (e.g. GET or POST).
  692. headers : Union[Dict[str, str], None]
  693. If set changes the request HTTP headers. Header values will be converted to a string.
  694. post_data : Union[Any, bytes, str, None]
  695. If set changes the post data of request.
  696. """
  697. return mapping.from_maybe_impl(
  698. await self._impl_obj.fallback(
  699. url=url,
  700. method=method,
  701. headers=mapping.to_impl(headers),
  702. postData=mapping.to_impl(post_data),
  703. )
  704. )
  705. async def continue_(
  706. self,
  707. *,
  708. url: typing.Optional[str] = None,
  709. method: typing.Optional[str] = None,
  710. headers: typing.Optional[typing.Dict[str, str]] = None,
  711. post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  712. ) -> None:
  713. """Route.continue_
  714. Sends route's request to the network with optional overrides.
  715. **Usage**
  716. ```py
  717. async def handle(route, request):
  718. # override headers
  719. headers = {
  720. **request.headers,
  721. \"foo\": \"foo-value\", # set \"foo\" header
  722. \"bar\": None # remove \"bar\" header
  723. }
  724. await route.continue_(headers=headers)
  725. await page.route(\"**/*\", handle)
  726. ```
  727. **Details**
  728. The `headers` option applies to both the routed request and any redirects it initiates. However, `url`, `method`,
  729. and `postData` only apply to the original request and are not carried over to redirected requests.
  730. `route.continue_()` will immediately send the request to the network, other matching handlers won't be
  731. invoked. Use `route.fallback()` If you want next matching handler in the chain to be invoked.
  732. **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,
  733. `Content-Length` and others, see
  734. [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an
  735. override is provided for a forbidden header, it will be ignored and the original request header will be used.
  736. To set custom cookies, use `browser_context.add_cookies()`.
  737. Parameters
  738. ----------
  739. url : Union[str, None]
  740. If set changes the request URL. New URL must have same protocol as original one.
  741. method : Union[str, None]
  742. If set changes the request method (e.g. GET or POST).
  743. headers : Union[Dict[str, str], None]
  744. If set changes the request HTTP headers. Header values will be converted to a string.
  745. post_data : Union[Any, bytes, str, None]
  746. If set changes the post data of request.
  747. """
  748. return mapping.from_maybe_impl(
  749. await self._impl_obj.continue_(
  750. url=url,
  751. method=method,
  752. headers=mapping.to_impl(headers),
  753. postData=mapping.to_impl(post_data),
  754. )
  755. )
  756. mapping.register(RouteImpl, Route)
  757. class WebSocket(AsyncBase):
  758. @typing.overload
  759. def on(
  760. self,
  761. event: Literal["close"],
  762. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  763. ) -> None:
  764. """
  765. Fired when the websocket closes."""
  766. @typing.overload
  767. def on(
  768. self,
  769. event: Literal["framereceived"],
  770. f: typing.Callable[
  771. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  772. ],
  773. ) -> None:
  774. """
  775. Fired when the websocket receives a frame."""
  776. @typing.overload
  777. def on(
  778. self,
  779. event: Literal["framesent"],
  780. f: typing.Callable[
  781. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  782. ],
  783. ) -> None:
  784. """
  785. Fired when the websocket sends a frame."""
  786. @typing.overload
  787. def on(
  788. self,
  789. event: Literal["socketerror"],
  790. f: typing.Callable[["str"], "typing.Union[typing.Awaitable[None], None]"],
  791. ) -> None:
  792. """
  793. Fired when the websocket has an error."""
  794. def on(
  795. self,
  796. event: str,
  797. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  798. ) -> None:
  799. return super().on(event=event, f=f)
  800. @typing.overload
  801. def once(
  802. self,
  803. event: Literal["close"],
  804. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  805. ) -> None:
  806. """
  807. Fired when the websocket closes."""
  808. @typing.overload
  809. def once(
  810. self,
  811. event: Literal["framereceived"],
  812. f: typing.Callable[
  813. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  814. ],
  815. ) -> None:
  816. """
  817. Fired when the websocket receives a frame."""
  818. @typing.overload
  819. def once(
  820. self,
  821. event: Literal["framesent"],
  822. f: typing.Callable[
  823. ["typing.Union[bytes, str]"], "typing.Union[typing.Awaitable[None], None]"
  824. ],
  825. ) -> None:
  826. """
  827. Fired when the websocket sends a frame."""
  828. @typing.overload
  829. def once(
  830. self,
  831. event: Literal["socketerror"],
  832. f: typing.Callable[["str"], "typing.Union[typing.Awaitable[None], None]"],
  833. ) -> None:
  834. """
  835. Fired when the websocket has an error."""
  836. def once(
  837. self,
  838. event: str,
  839. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  840. ) -> None:
  841. return super().once(event=event, f=f)
  842. @property
  843. def url(self) -> str:
  844. """WebSocket.url
  845. Contains the URL of the WebSocket.
  846. Returns
  847. -------
  848. str
  849. """
  850. return mapping.from_maybe_impl(self._impl_obj.url)
  851. def expect_event(
  852. self,
  853. event: str,
  854. predicate: typing.Optional[typing.Callable] = None,
  855. *,
  856. timeout: typing.Optional[float] = None,
  857. ) -> AsyncEventContextManager:
  858. """WebSocket.expect_event
  859. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  860. value. Will throw an error if the webSocket is closed before the event is fired. Returns the event data value.
  861. Parameters
  862. ----------
  863. event : str
  864. Event name, same one would pass into `webSocket.on(event)`.
  865. predicate : Union[Callable, None]
  866. Receives the event data and resolves to truthy value when the waiting should resolve.
  867. timeout : Union[float, None]
  868. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  869. default value can be changed by using the `browser_context.set_default_timeout()`.
  870. Returns
  871. -------
  872. EventContextManager
  873. """
  874. return AsyncEventContextManager(
  875. self._impl_obj.expect_event(
  876. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  877. ).future
  878. )
  879. async def wait_for_event(
  880. self,
  881. event: str,
  882. predicate: typing.Optional[typing.Callable] = None,
  883. *,
  884. timeout: typing.Optional[float] = None,
  885. ) -> typing.Any:
  886. """WebSocket.wait_for_event
  887. **NOTE** In most cases, you should use `web_socket.expect_event()`.
  888. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  889. and waits for `predicate(event)` to return a truthy value. Will throw an error if the socket is closed before the
  890. `event` is fired.
  891. Parameters
  892. ----------
  893. event : str
  894. Event name, same one typically passed into `*.on(event)`.
  895. predicate : Union[Callable, None]
  896. Receives the event data and resolves to truthy value when the waiting should resolve.
  897. timeout : Union[float, None]
  898. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  899. default value can be changed by using the `browser_context.set_default_timeout()`.
  900. Returns
  901. -------
  902. Any
  903. """
  904. return mapping.from_maybe_impl(
  905. await self._impl_obj.wait_for_event(
  906. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  907. )
  908. )
  909. def is_closed(self) -> bool:
  910. """WebSocket.is_closed
  911. Indicates that the web socket has been closed.
  912. Returns
  913. -------
  914. bool
  915. """
  916. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  917. mapping.register(WebSocketImpl, WebSocket)
  918. class WebSocketRoute(AsyncBase):
  919. @property
  920. def url(self) -> str:
  921. """WebSocketRoute.url
  922. URL of the WebSocket created in the page.
  923. Returns
  924. -------
  925. str
  926. """
  927. return mapping.from_maybe_impl(self._impl_obj.url)
  928. async def close(
  929. self, *, code: typing.Optional[int] = None, reason: typing.Optional[str] = None
  930. ) -> None:
  931. """WebSocketRoute.close
  932. Closes one side of the WebSocket connection.
  933. Parameters
  934. ----------
  935. code : Union[int, None]
  936. Optional [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code).
  937. reason : Union[str, None]
  938. Optional [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
  939. """
  940. return mapping.from_maybe_impl(
  941. await self._impl_obj.close(code=code, reason=reason)
  942. )
  943. def connect_to_server(self) -> "WebSocketRoute":
  944. """WebSocketRoute.connect_to_server
  945. By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This
  946. method connects to the actual WebSocket server, and returns the server-side `WebSocketRoute` instance, giving the
  947. ability to send and receive messages from the server.
  948. Once connected to the server:
  949. - Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless
  950. `web_socket_route.on_message()` is called on the server-side `WebSocketRoute`.
  951. - Messages sent by the [`WebSocket.send()`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) call
  952. in the page will be **automatically forwarded** to the server, unless `web_socket_route.on_message()` is
  953. called on the original `WebSocketRoute`.
  954. See examples at the top for more details.
  955. Returns
  956. -------
  957. WebSocketRoute
  958. """
  959. return mapping.from_impl(self._impl_obj.connect_to_server())
  960. def send(self, message: typing.Union[str, bytes]) -> None:
  961. """WebSocketRoute.send
  962. Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called
  963. on the result of `web_socket_route.connect_to_server()`, sends the message to the server. See examples at the
  964. top for more details.
  965. Parameters
  966. ----------
  967. message : Union[bytes, str]
  968. Message to send.
  969. """
  970. return mapping.from_maybe_impl(self._impl_obj.send(message=message))
  971. def on_message(
  972. self, handler: typing.Callable[[typing.Union[str, bytes]], typing.Any]
  973. ) -> None:
  974. """WebSocketRoute.on_message
  975. This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.
  976. When called on the original WebSocket route, this method handles messages sent from the page. You can handle this
  977. messages by responding to them with `web_socket_route.send()`, forwarding them to the server-side connection
  978. returned by `web_socket_route.connect_to_server()` or do something else.
  979. Once this method is called, messages are not automatically forwarded to the server or to the page - you should do
  980. that manually by calling `web_socket_route.send()`. See examples at the top for more details.
  981. Calling this method again will override the handler with a new one.
  982. Parameters
  983. ----------
  984. handler : Callable[[Union[bytes, str]], Any]
  985. Function that will handle messages.
  986. """
  987. return mapping.from_maybe_impl(
  988. self._impl_obj.on_message(handler=self._wrap_handler(handler))
  989. )
  990. def on_close(
  991. self,
  992. handler: typing.Callable[
  993. [typing.Optional[int], typing.Optional[str]], typing.Any
  994. ],
  995. ) -> None:
  996. """WebSocketRoute.on_close
  997. Allows to handle [`WebSocket.close`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close).
  998. By default, closing one side of the connection, either in the page or on the server, will close the other side.
  999. However, when `web_socket_route.on_close()` handler is set up, the default forwarding of closure is disabled,
  1000. and handler should take care of it.
  1001. Parameters
  1002. ----------
  1003. handler : Callable[[Union[int, None], Union[str, None]], Any]
  1004. Function that will handle WebSocket closure. Received an optional
  1005. [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code) and an optional
  1006. [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
  1007. """
  1008. return mapping.from_maybe_impl(
  1009. self._impl_obj.on_close(handler=self._wrap_handler(handler))
  1010. )
  1011. mapping.register(WebSocketRouteImpl, WebSocketRoute)
  1012. class Keyboard(AsyncBase):
  1013. async def down(self, key: str) -> None:
  1014. """Keyboard.down
  1015. Dispatches a `keydown` event.
  1016. `key` can specify the intended
  1017. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  1018. to generate the text for. A superset of the `key` values can be found
  1019. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  1020. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  1021. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  1022. etc.
  1023. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  1024. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  1025. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  1026. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  1027. texts.
  1028. If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that
  1029. modifier active. To release the modifier key, use `keyboard.up()`.
  1030. After the key is pressed once, subsequent calls to `keyboard.down()` will have
  1031. [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,
  1032. use `keyboard.up()`.
  1033. **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
  1034. Parameters
  1035. ----------
  1036. key : str
  1037. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1038. """
  1039. return mapping.from_maybe_impl(await self._impl_obj.down(key=key))
  1040. async def up(self, key: str) -> None:
  1041. """Keyboard.up
  1042. Dispatches a `keyup` event.
  1043. Parameters
  1044. ----------
  1045. key : str
  1046. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1047. """
  1048. return mapping.from_maybe_impl(await self._impl_obj.up(key=key))
  1049. async def insert_text(self, text: str) -> None:
  1050. """Keyboard.insert_text
  1051. Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
  1052. **Usage**
  1053. ```py
  1054. await page.keyboard.insert_text(\"嗨\")
  1055. ```
  1056. **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper
  1057. case.
  1058. Parameters
  1059. ----------
  1060. text : str
  1061. Sets input to the specified text value.
  1062. """
  1063. return mapping.from_maybe_impl(await self._impl_obj.insert_text(text=text))
  1064. async def type(self, text: str, *, delay: typing.Optional[float] = None) -> None:
  1065. """Keyboard.type
  1066. **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
  1067. there is special keyboard handling on the page - in this case use `locator.press_sequentially()`.
  1068. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
  1069. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  1070. **Usage**
  1071. ```py
  1072. await page.keyboard.type(\"Hello\") # types instantly
  1073. await page.keyboard.type(\"World\", delay=100) # types slower, like a user
  1074. ```
  1075. **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.
  1076. **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.
  1077. Parameters
  1078. ----------
  1079. text : str
  1080. A text to type into a focused element.
  1081. delay : Union[float, None]
  1082. Time to wait between key presses in milliseconds. Defaults to 0.
  1083. """
  1084. return mapping.from_maybe_impl(
  1085. await self._impl_obj.type(text=text, delay=delay)
  1086. )
  1087. async def press(self, key: str, *, delay: typing.Optional[float] = None) -> None:
  1088. """Keyboard.press
  1089. **NOTE** In most cases, you should use `locator.press()` instead.
  1090. `key` can specify the intended
  1091. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  1092. to generate the text for. A superset of the `key` values can be found
  1093. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  1094. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  1095. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  1096. etc.
  1097. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  1098. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  1099. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  1100. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  1101. texts.
  1102. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  1103. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  1104. **Usage**
  1105. ```py
  1106. page = await browser.new_page()
  1107. await page.goto(\"https://keycode.info\")
  1108. await page.keyboard.press(\"a\")
  1109. await page.screenshot(path=\"a.png\")
  1110. await page.keyboard.press(\"ArrowLeft\")
  1111. await page.screenshot(path=\"arrow_left.png\")
  1112. await page.keyboard.press(\"Shift+O\")
  1113. await page.screenshot(path=\"o.png\")
  1114. await browser.close()
  1115. ```
  1116. Shortcut for `keyboard.down()` and `keyboard.up()`.
  1117. Parameters
  1118. ----------
  1119. key : str
  1120. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  1121. delay : Union[float, None]
  1122. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  1123. """
  1124. return mapping.from_maybe_impl(await self._impl_obj.press(key=key, delay=delay))
  1125. mapping.register(KeyboardImpl, Keyboard)
  1126. class Mouse(AsyncBase):
  1127. async def move(
  1128. self, x: float, y: float, *, steps: typing.Optional[int] = None
  1129. ) -> None:
  1130. """Mouse.move
  1131. Dispatches a `mousemove` event.
  1132. Parameters
  1133. ----------
  1134. x : float
  1135. X coordinate relative to the main frame's viewport in CSS pixels.
  1136. y : float
  1137. Y coordinate relative to the main frame's viewport in CSS pixels.
  1138. steps : Union[int, None]
  1139. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1140. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1141. """
  1142. return mapping.from_maybe_impl(await self._impl_obj.move(x=x, y=y, steps=steps))
  1143. async def down(
  1144. self,
  1145. *,
  1146. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1147. click_count: typing.Optional[int] = None,
  1148. ) -> None:
  1149. """Mouse.down
  1150. Dispatches a `mousedown` event.
  1151. Parameters
  1152. ----------
  1153. button : Union["left", "middle", "right", None]
  1154. Defaults to `left`.
  1155. click_count : Union[int, None]
  1156. defaults to 1. See [UIEvent.detail].
  1157. """
  1158. return mapping.from_maybe_impl(
  1159. await self._impl_obj.down(button=button, clickCount=click_count)
  1160. )
  1161. async def up(
  1162. self,
  1163. *,
  1164. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1165. click_count: typing.Optional[int] = None,
  1166. ) -> None:
  1167. """Mouse.up
  1168. Dispatches a `mouseup` event.
  1169. Parameters
  1170. ----------
  1171. button : Union["left", "middle", "right", None]
  1172. Defaults to `left`.
  1173. click_count : Union[int, None]
  1174. defaults to 1. See [UIEvent.detail].
  1175. """
  1176. return mapping.from_maybe_impl(
  1177. await self._impl_obj.up(button=button, clickCount=click_count)
  1178. )
  1179. async def click(
  1180. self,
  1181. x: float,
  1182. y: float,
  1183. *,
  1184. delay: typing.Optional[float] = None,
  1185. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1186. click_count: typing.Optional[int] = None,
  1187. ) -> None:
  1188. """Mouse.click
  1189. Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`.
  1190. Parameters
  1191. ----------
  1192. x : float
  1193. X coordinate relative to the main frame's viewport in CSS pixels.
  1194. y : float
  1195. Y coordinate relative to the main frame's viewport in CSS pixels.
  1196. delay : Union[float, None]
  1197. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1198. button : Union["left", "middle", "right", None]
  1199. Defaults to `left`.
  1200. click_count : Union[int, None]
  1201. defaults to 1. See [UIEvent.detail].
  1202. """
  1203. return mapping.from_maybe_impl(
  1204. await self._impl_obj.click(
  1205. x=x, y=y, delay=delay, button=button, clickCount=click_count
  1206. )
  1207. )
  1208. async def dblclick(
  1209. self,
  1210. x: float,
  1211. y: float,
  1212. *,
  1213. delay: typing.Optional[float] = None,
  1214. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1215. ) -> None:
  1216. """Mouse.dblclick
  1217. Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`, `mouse.down()` and
  1218. `mouse.up()`.
  1219. Parameters
  1220. ----------
  1221. x : float
  1222. X coordinate relative to the main frame's viewport in CSS pixels.
  1223. y : float
  1224. Y coordinate relative to the main frame's viewport in CSS pixels.
  1225. delay : Union[float, None]
  1226. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1227. button : Union["left", "middle", "right", None]
  1228. Defaults to `left`.
  1229. """
  1230. return mapping.from_maybe_impl(
  1231. await self._impl_obj.dblclick(x=x, y=y, delay=delay, button=button)
  1232. )
  1233. async def wheel(self, delta_x: float, delta_y: float) -> None:
  1234. """Mouse.wheel
  1235. Dispatches a `wheel` event. This method is usually used to manually scroll the page. See
  1236. [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  1237. **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling
  1238. to finish before returning.
  1239. Parameters
  1240. ----------
  1241. delta_x : float
  1242. Pixels to scroll horizontally.
  1243. delta_y : float
  1244. Pixels to scroll vertically.
  1245. """
  1246. return mapping.from_maybe_impl(
  1247. await self._impl_obj.wheel(deltaX=delta_x, deltaY=delta_y)
  1248. )
  1249. mapping.register(MouseImpl, Mouse)
  1250. class Touchscreen(AsyncBase):
  1251. async def tap(self, x: float, y: float) -> None:
  1252. """Touchscreen.tap
  1253. Dispatches a `touchstart` and `touchend` event with a single touch at the position (`x`,`y`).
  1254. **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
  1255. Parameters
  1256. ----------
  1257. x : float
  1258. X coordinate relative to the main frame's viewport in CSS pixels.
  1259. y : float
  1260. Y coordinate relative to the main frame's viewport in CSS pixels.
  1261. """
  1262. return mapping.from_maybe_impl(await self._impl_obj.tap(x=x, y=y))
  1263. mapping.register(TouchscreenImpl, Touchscreen)
  1264. class JSHandle(AsyncBase):
  1265. async def evaluate(
  1266. self, expression: str, arg: typing.Optional[typing.Any] = None
  1267. ) -> typing.Any:
  1268. """JSHandle.evaluate
  1269. Returns the return value of `expression`.
  1270. This method passes this handle as the first argument to `expression`.
  1271. If `expression` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
  1272. value.
  1273. **Usage**
  1274. ```py
  1275. tweet_handle = await page.query_selector(\".tweet .retweets\")
  1276. assert await tweet_handle.evaluate(\"node => node.innerText\") == \"10 retweets\"
  1277. ```
  1278. Parameters
  1279. ----------
  1280. expression : str
  1281. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  1282. function is automatically invoked.
  1283. arg : Union[Any, None]
  1284. Optional argument to pass to `expression`.
  1285. Returns
  1286. -------
  1287. Any
  1288. """
  1289. return mapping.from_maybe_impl(
  1290. await self._impl_obj.evaluate(
  1291. expression=expression, arg=mapping.to_impl(arg)
  1292. )
  1293. )
  1294. async def evaluate_handle(
  1295. self, expression: str, arg: typing.Optional[typing.Any] = None
  1296. ) -> "JSHandle":
  1297. """JSHandle.evaluate_handle
  1298. Returns the return value of `expression` as a `JSHandle`.
  1299. This method passes this handle as the first argument to `expression`.
  1300. The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
  1301. returns `JSHandle`.
  1302. If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
  1303. wait for the promise to resolve and return its value.
  1304. See `page.evaluate_handle()` for more details.
  1305. Parameters
  1306. ----------
  1307. expression : str
  1308. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  1309. function is automatically invoked.
  1310. arg : Union[Any, None]
  1311. Optional argument to pass to `expression`.
  1312. Returns
  1313. -------
  1314. JSHandle
  1315. """
  1316. return mapping.from_impl(
  1317. await self._impl_obj.evaluate_handle(
  1318. expression=expression, arg=mapping.to_impl(arg)
  1319. )
  1320. )
  1321. async def get_property(self, property_name: str) -> "JSHandle":
  1322. """JSHandle.get_property
  1323. Fetches a single property from the referenced object.
  1324. Parameters
  1325. ----------
  1326. property_name : str
  1327. property to get
  1328. Returns
  1329. -------
  1330. JSHandle
  1331. """
  1332. return mapping.from_impl(
  1333. await self._impl_obj.get_property(propertyName=property_name)
  1334. )
  1335. async def get_properties(self) -> typing.Dict[str, "JSHandle"]:
  1336. """JSHandle.get_properties
  1337. The method returns a map with **own property names** as keys and JSHandle instances for the property values.
  1338. **Usage**
  1339. ```py
  1340. handle = await page.evaluate_handle(\"({ window, document })\")
  1341. properties = await handle.get_properties()
  1342. window_handle = properties.get(\"window\")
  1343. document_handle = properties.get(\"document\")
  1344. await handle.dispose()
  1345. ```
  1346. Returns
  1347. -------
  1348. Dict[str, JSHandle]
  1349. """
  1350. return mapping.from_impl_dict(await self._impl_obj.get_properties())
  1351. def as_element(self) -> typing.Optional["ElementHandle"]:
  1352. """JSHandle.as_element
  1353. Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
  1354. Returns
  1355. -------
  1356. Union[ElementHandle, None]
  1357. """
  1358. return mapping.from_impl_nullable(self._impl_obj.as_element())
  1359. async def dispose(self) -> None:
  1360. """JSHandle.dispose
  1361. The `jsHandle.dispose` method stops referencing the element handle.
  1362. """
  1363. return mapping.from_maybe_impl(await self._impl_obj.dispose())
  1364. async def json_value(self) -> typing.Any:
  1365. """JSHandle.json_value
  1366. Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
  1367. **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw
  1368. an error if the object has circular references.
  1369. Returns
  1370. -------
  1371. Any
  1372. """
  1373. return mapping.from_maybe_impl(await self._impl_obj.json_value())
  1374. mapping.register(JSHandleImpl, JSHandle)
  1375. class ElementHandle(JSHandle):
  1376. def as_element(self) -> typing.Optional["ElementHandle"]:
  1377. """ElementHandle.as_element
  1378. Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
  1379. Returns
  1380. -------
  1381. Union[ElementHandle, None]
  1382. """
  1383. return mapping.from_impl_nullable(self._impl_obj.as_element())
  1384. async def owner_frame(self) -> typing.Optional["Frame"]:
  1385. """ElementHandle.owner_frame
  1386. Returns the frame containing the given element.
  1387. Returns
  1388. -------
  1389. Union[Frame, None]
  1390. """
  1391. return mapping.from_impl_nullable(await self._impl_obj.owner_frame())
  1392. async def content_frame(self) -> typing.Optional["Frame"]:
  1393. """ElementHandle.content_frame
  1394. Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
  1395. Returns
  1396. -------
  1397. Union[Frame, None]
  1398. """
  1399. return mapping.from_impl_nullable(await self._impl_obj.content_frame())
  1400. async def get_attribute(self, name: str) -> typing.Optional[str]:
  1401. """ElementHandle.get_attribute
  1402. Returns element attribute value.
  1403. Parameters
  1404. ----------
  1405. name : str
  1406. Attribute name to get the value for.
  1407. Returns
  1408. -------
  1409. Union[str, None]
  1410. """
  1411. return mapping.from_maybe_impl(await self._impl_obj.get_attribute(name=name))
  1412. async def text_content(self) -> typing.Optional[str]:
  1413. """ElementHandle.text_content
  1414. Returns the `node.textContent`.
  1415. Returns
  1416. -------
  1417. Union[str, None]
  1418. """
  1419. return mapping.from_maybe_impl(await self._impl_obj.text_content())
  1420. async def inner_text(self) -> str:
  1421. """ElementHandle.inner_text
  1422. Returns the `element.innerText`.
  1423. Returns
  1424. -------
  1425. str
  1426. """
  1427. return mapping.from_maybe_impl(await self._impl_obj.inner_text())
  1428. async def inner_html(self) -> str:
  1429. """ElementHandle.inner_html
  1430. Returns the `element.innerHTML`.
  1431. Returns
  1432. -------
  1433. str
  1434. """
  1435. return mapping.from_maybe_impl(await self._impl_obj.inner_html())
  1436. async def is_checked(self) -> bool:
  1437. """ElementHandle.is_checked
  1438. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  1439. Returns
  1440. -------
  1441. bool
  1442. """
  1443. return mapping.from_maybe_impl(await self._impl_obj.is_checked())
  1444. async def is_disabled(self) -> bool:
  1445. """ElementHandle.is_disabled
  1446. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  1447. Returns
  1448. -------
  1449. bool
  1450. """
  1451. return mapping.from_maybe_impl(await self._impl_obj.is_disabled())
  1452. async def is_editable(self) -> bool:
  1453. """ElementHandle.is_editable
  1454. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  1455. Returns
  1456. -------
  1457. bool
  1458. """
  1459. return mapping.from_maybe_impl(await self._impl_obj.is_editable())
  1460. async def is_enabled(self) -> bool:
  1461. """ElementHandle.is_enabled
  1462. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  1463. Returns
  1464. -------
  1465. bool
  1466. """
  1467. return mapping.from_maybe_impl(await self._impl_obj.is_enabled())
  1468. async def is_hidden(self) -> bool:
  1469. """ElementHandle.is_hidden
  1470. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
  1471. Returns
  1472. -------
  1473. bool
  1474. """
  1475. return mapping.from_maybe_impl(await self._impl_obj.is_hidden())
  1476. async def is_visible(self) -> bool:
  1477. """ElementHandle.is_visible
  1478. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  1479. Returns
  1480. -------
  1481. bool
  1482. """
  1483. return mapping.from_maybe_impl(await self._impl_obj.is_visible())
  1484. async def dispatch_event(
  1485. self, type: str, event_init: typing.Optional[typing.Dict] = None
  1486. ) -> None:
  1487. """ElementHandle.dispatch_event
  1488. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  1489. `click` is dispatched. This is equivalent to calling
  1490. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  1491. **Usage**
  1492. ```py
  1493. await element_handle.dispatch_event(\"click\")
  1494. ```
  1495. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  1496. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  1497. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  1498. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  1499. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  1500. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  1501. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  1502. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  1503. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  1504. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  1505. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  1506. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  1507. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  1508. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  1509. ```py
  1510. # note you can only create data_transfer in chromium and firefox
  1511. data_transfer = await page.evaluate_handle(\"new DataTransfer()\")
  1512. await element_handle.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
  1513. ```
  1514. Parameters
  1515. ----------
  1516. type : str
  1517. DOM event type: `"click"`, `"dragstart"`, etc.
  1518. event_init : Union[Dict, None]
  1519. Optional event-specific initialization properties.
  1520. """
  1521. return mapping.from_maybe_impl(
  1522. await self._impl_obj.dispatch_event(
  1523. type=type, eventInit=mapping.to_impl(event_init)
  1524. )
  1525. )
  1526. async def scroll_into_view_if_needed(
  1527. self, *, timeout: typing.Optional[float] = None
  1528. ) -> None:
  1529. """ElementHandle.scroll_into_view_if_needed
  1530. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
  1531. it is completely visible as defined by
  1532. [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
  1533. Throws when `elementHandle` does not point to an element
  1534. [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
  1535. See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  1536. Parameters
  1537. ----------
  1538. timeout : Union[float, None]
  1539. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1540. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1541. """
  1542. return mapping.from_maybe_impl(
  1543. await self._impl_obj.scroll_into_view_if_needed(timeout=timeout)
  1544. )
  1545. async def hover(
  1546. self,
  1547. *,
  1548. modifiers: typing.Optional[
  1549. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1550. ] = None,
  1551. position: typing.Optional[Position] = None,
  1552. timeout: typing.Optional[float] = None,
  1553. no_wait_after: typing.Optional[bool] = None,
  1554. force: typing.Optional[bool] = None,
  1555. trial: typing.Optional[bool] = None,
  1556. ) -> None:
  1557. """ElementHandle.hover
  1558. This method hovers over the element by performing the following steps:
  1559. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1560. 1. Scroll the element into view if needed.
  1561. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  1562. If the element is detached from the DOM at any moment during the action, this method throws.
  1563. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1564. Passing zero timeout disables this.
  1565. Parameters
  1566. ----------
  1567. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1568. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1569. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1570. "Control" on Windows and Linux and to "Meta" on macOS.
  1571. position : Union[{x: float, y: float}, None]
  1572. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1573. the element.
  1574. timeout : Union[float, None]
  1575. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1576. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1577. no_wait_after : Union[bool, None]
  1578. This option has no effect.
  1579. Deprecated: This option has no effect.
  1580. force : Union[bool, None]
  1581. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1582. trial : Union[bool, None]
  1583. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1584. to `false`. Useful to wait until the element is ready for the action without performing it.
  1585. """
  1586. return mapping.from_maybe_impl(
  1587. await self._impl_obj.hover(
  1588. modifiers=mapping.to_impl(modifiers),
  1589. position=position,
  1590. timeout=timeout,
  1591. noWaitAfter=no_wait_after,
  1592. force=force,
  1593. trial=trial,
  1594. )
  1595. )
  1596. async def click(
  1597. self,
  1598. *,
  1599. modifiers: typing.Optional[
  1600. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1601. ] = None,
  1602. position: typing.Optional[Position] = None,
  1603. delay: typing.Optional[float] = None,
  1604. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1605. click_count: typing.Optional[int] = None,
  1606. timeout: typing.Optional[float] = None,
  1607. force: typing.Optional[bool] = None,
  1608. no_wait_after: typing.Optional[bool] = None,
  1609. trial: typing.Optional[bool] = None,
  1610. steps: typing.Optional[int] = None,
  1611. ) -> None:
  1612. """ElementHandle.click
  1613. This method clicks the element by performing the following steps:
  1614. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1615. 1. Scroll the element into view if needed.
  1616. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  1617. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  1618. If the element is detached from the DOM at any moment during the action, this method throws.
  1619. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1620. Passing zero timeout disables this.
  1621. Parameters
  1622. ----------
  1623. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1624. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1625. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1626. "Control" on Windows and Linux and to "Meta" on macOS.
  1627. position : Union[{x: float, y: float}, None]
  1628. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1629. the element.
  1630. delay : Union[float, None]
  1631. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1632. button : Union["left", "middle", "right", None]
  1633. Defaults to `left`.
  1634. click_count : Union[int, None]
  1635. defaults to 1. See [UIEvent.detail].
  1636. timeout : Union[float, None]
  1637. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1638. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1639. force : Union[bool, None]
  1640. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1641. no_wait_after : Union[bool, None]
  1642. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  1643. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  1644. navigating to inaccessible pages. Defaults to `false`.
  1645. Deprecated: This option will default to `true` in the future.
  1646. trial : Union[bool, None]
  1647. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1648. to `false`. Useful to wait until the element is ready for the action without performing it.
  1649. steps : Union[int, None]
  1650. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1651. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1652. """
  1653. return mapping.from_maybe_impl(
  1654. await self._impl_obj.click(
  1655. modifiers=mapping.to_impl(modifiers),
  1656. position=position,
  1657. delay=delay,
  1658. button=button,
  1659. clickCount=click_count,
  1660. timeout=timeout,
  1661. force=force,
  1662. noWaitAfter=no_wait_after,
  1663. trial=trial,
  1664. steps=steps,
  1665. )
  1666. )
  1667. async def dblclick(
  1668. self,
  1669. *,
  1670. modifiers: typing.Optional[
  1671. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1672. ] = None,
  1673. position: typing.Optional[Position] = None,
  1674. delay: typing.Optional[float] = None,
  1675. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  1676. timeout: typing.Optional[float] = None,
  1677. force: typing.Optional[bool] = None,
  1678. no_wait_after: typing.Optional[bool] = None,
  1679. trial: typing.Optional[bool] = None,
  1680. steps: typing.Optional[int] = None,
  1681. ) -> None:
  1682. """ElementHandle.dblclick
  1683. This method double clicks the element by performing the following steps:
  1684. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1685. 1. Scroll the element into view if needed.
  1686. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  1687. If the element is detached from the DOM at any moment during the action, this method throws.
  1688. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1689. Passing zero timeout disables this.
  1690. **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
  1691. Parameters
  1692. ----------
  1693. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1694. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1695. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1696. "Control" on Windows and Linux and to "Meta" on macOS.
  1697. position : Union[{x: float, y: float}, None]
  1698. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1699. the element.
  1700. delay : Union[float, None]
  1701. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  1702. button : Union["left", "middle", "right", None]
  1703. Defaults to `left`.
  1704. timeout : Union[float, None]
  1705. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1706. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1707. force : Union[bool, None]
  1708. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1709. no_wait_after : Union[bool, None]
  1710. This option has no effect.
  1711. Deprecated: This option has no effect.
  1712. trial : Union[bool, None]
  1713. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1714. to `false`. Useful to wait until the element is ready for the action without performing it.
  1715. steps : Union[int, None]
  1716. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  1717. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  1718. """
  1719. return mapping.from_maybe_impl(
  1720. await self._impl_obj.dblclick(
  1721. modifiers=mapping.to_impl(modifiers),
  1722. position=position,
  1723. delay=delay,
  1724. button=button,
  1725. timeout=timeout,
  1726. force=force,
  1727. noWaitAfter=no_wait_after,
  1728. trial=trial,
  1729. steps=steps,
  1730. )
  1731. )
  1732. async def select_option(
  1733. self,
  1734. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  1735. *,
  1736. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  1737. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  1738. element: typing.Optional[
  1739. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  1740. ] = None,
  1741. timeout: typing.Optional[float] = None,
  1742. force: typing.Optional[bool] = None,
  1743. no_wait_after: typing.Optional[bool] = None,
  1744. ) -> typing.List[str]:
  1745. """ElementHandle.select_option
  1746. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
  1747. the `<select>` element and selects these options.
  1748. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  1749. the `<label>` element that has an associated
  1750. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  1751. instead.
  1752. Returns the array of option values that have been successfully selected.
  1753. Triggers a `change` and `input` event once all the provided options have been selected.
  1754. **Usage**
  1755. ```py
  1756. # Single selection matching the value or label
  1757. await handle.select_option(\"blue\")
  1758. # single selection matching the label
  1759. await handle.select_option(label=\"blue\")
  1760. # multiple selection
  1761. await handle.select_option(value=[\"red\", \"green\", \"blue\"])
  1762. ```
  1763. Parameters
  1764. ----------
  1765. value : Union[Sequence[str], str, None]
  1766. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  1767. otherwise only the first option matching one of the passed options is selected. Optional.
  1768. index : Union[Sequence[int], int, None]
  1769. Options to select by index. Optional.
  1770. label : Union[Sequence[str], str, None]
  1771. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  1772. otherwise only the first option matching one of the passed options is selected. Optional.
  1773. element : Union[ElementHandle, Sequence[ElementHandle], None]
  1774. Option elements to select. Optional.
  1775. timeout : Union[float, None]
  1776. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1777. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1778. force : Union[bool, None]
  1779. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1780. no_wait_after : Union[bool, None]
  1781. This option has no effect.
  1782. Deprecated: This option has no effect.
  1783. Returns
  1784. -------
  1785. List[str]
  1786. """
  1787. return mapping.from_maybe_impl(
  1788. await self._impl_obj.select_option(
  1789. value=mapping.to_impl(value),
  1790. index=mapping.to_impl(index),
  1791. label=mapping.to_impl(label),
  1792. element=mapping.to_impl(element),
  1793. timeout=timeout,
  1794. force=force,
  1795. noWaitAfter=no_wait_after,
  1796. )
  1797. )
  1798. async def tap(
  1799. self,
  1800. *,
  1801. modifiers: typing.Optional[
  1802. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  1803. ] = None,
  1804. position: typing.Optional[Position] = None,
  1805. timeout: typing.Optional[float] = None,
  1806. force: typing.Optional[bool] = None,
  1807. no_wait_after: typing.Optional[bool] = None,
  1808. trial: typing.Optional[bool] = None,
  1809. ) -> None:
  1810. """ElementHandle.tap
  1811. This method taps the element by performing the following steps:
  1812. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  1813. 1. Scroll the element into view if needed.
  1814. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  1815. If the element is detached from the DOM at any moment during the action, this method throws.
  1816. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  1817. Passing zero timeout disables this.
  1818. **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
  1819. Parameters
  1820. ----------
  1821. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  1822. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  1823. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  1824. "Control" on Windows and Linux and to "Meta" on macOS.
  1825. position : Union[{x: float, y: float}, None]
  1826. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  1827. the element.
  1828. timeout : Union[float, None]
  1829. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1830. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1831. force : Union[bool, None]
  1832. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1833. no_wait_after : Union[bool, None]
  1834. This option has no effect.
  1835. Deprecated: This option has no effect.
  1836. trial : Union[bool, None]
  1837. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  1838. to `false`. Useful to wait until the element is ready for the action without performing it.
  1839. """
  1840. return mapping.from_maybe_impl(
  1841. await self._impl_obj.tap(
  1842. modifiers=mapping.to_impl(modifiers),
  1843. position=position,
  1844. timeout=timeout,
  1845. force=force,
  1846. noWaitAfter=no_wait_after,
  1847. trial=trial,
  1848. )
  1849. )
  1850. async def fill(
  1851. self,
  1852. value: str,
  1853. *,
  1854. timeout: typing.Optional[float] = None,
  1855. no_wait_after: typing.Optional[bool] = None,
  1856. force: typing.Optional[bool] = None,
  1857. ) -> None:
  1858. """ElementHandle.fill
  1859. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
  1860. `input` event after filling. Note that you can pass an empty string to clear the input field.
  1861. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  1862. error. However, if the element is inside the `<label>` element that has an associated
  1863. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  1864. instead.
  1865. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  1866. Parameters
  1867. ----------
  1868. value : str
  1869. Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
  1870. timeout : Union[float, None]
  1871. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1872. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1873. no_wait_after : Union[bool, None]
  1874. This option has no effect.
  1875. Deprecated: This option has no effect.
  1876. force : Union[bool, None]
  1877. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1878. """
  1879. return mapping.from_maybe_impl(
  1880. await self._impl_obj.fill(
  1881. value=value, timeout=timeout, noWaitAfter=no_wait_after, force=force
  1882. )
  1883. )
  1884. async def select_text(
  1885. self,
  1886. *,
  1887. force: typing.Optional[bool] = None,
  1888. timeout: typing.Optional[float] = None,
  1889. ) -> None:
  1890. """ElementHandle.select_text
  1891. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
  1892. text content.
  1893. If the element is inside the `<label>` element that has an associated
  1894. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
  1895. the control instead.
  1896. Parameters
  1897. ----------
  1898. force : Union[bool, None]
  1899. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  1900. timeout : Union[float, None]
  1901. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1902. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1903. """
  1904. return mapping.from_maybe_impl(
  1905. await self._impl_obj.select_text(force=force, timeout=timeout)
  1906. )
  1907. async def input_value(self, *, timeout: typing.Optional[float] = None) -> str:
  1908. """ElementHandle.input_value
  1909. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  1910. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  1911. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  1912. control.
  1913. Parameters
  1914. ----------
  1915. timeout : Union[float, None]
  1916. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1917. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1918. Returns
  1919. -------
  1920. str
  1921. """
  1922. return mapping.from_maybe_impl(
  1923. await self._impl_obj.input_value(timeout=timeout)
  1924. )
  1925. async def set_input_files(
  1926. self,
  1927. files: typing.Union[
  1928. str,
  1929. pathlib.Path,
  1930. FilePayload,
  1931. typing.Sequence[typing.Union[str, pathlib.Path]],
  1932. typing.Sequence[FilePayload],
  1933. ],
  1934. *,
  1935. timeout: typing.Optional[float] = None,
  1936. no_wait_after: typing.Optional[bool] = None,
  1937. ) -> None:
  1938. """ElementHandle.set_input_files
  1939. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  1940. they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
  1941. with a `[webkitdirectory]` attribute, only a single directory path is supported.
  1942. This method expects `ElementHandle` to point to an
  1943. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  1944. the `<label>` element that has an associated
  1945. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  1946. Parameters
  1947. ----------
  1948. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  1949. timeout : Union[float, None]
  1950. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1951. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1952. no_wait_after : Union[bool, None]
  1953. This option has no effect.
  1954. Deprecated: This option has no effect.
  1955. """
  1956. return mapping.from_maybe_impl(
  1957. await self._impl_obj.set_input_files(
  1958. files=mapping.to_impl(files), timeout=timeout, noWaitAfter=no_wait_after
  1959. )
  1960. )
  1961. async def focus(self) -> None:
  1962. """ElementHandle.focus
  1963. Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
  1964. """
  1965. return mapping.from_maybe_impl(await self._impl_obj.focus())
  1966. async def type(
  1967. self,
  1968. text: str,
  1969. *,
  1970. delay: typing.Optional[float] = None,
  1971. timeout: typing.Optional[float] = None,
  1972. no_wait_after: typing.Optional[bool] = None,
  1973. ) -> None:
  1974. """ElementHandle.type
  1975. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  1976. text.
  1977. To press a special key, like `Control` or `ArrowDown`, use `element_handle.press()`.
  1978. **Usage**
  1979. Parameters
  1980. ----------
  1981. text : str
  1982. A text to type into a focused element.
  1983. delay : Union[float, None]
  1984. Time to wait between key presses in milliseconds. Defaults to 0.
  1985. timeout : Union[float, None]
  1986. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  1987. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  1988. no_wait_after : Union[bool, None]
  1989. This option has no effect.
  1990. Deprecated: This option has no effect.
  1991. """
  1992. return mapping.from_maybe_impl(
  1993. await self._impl_obj.type(
  1994. text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  1995. )
  1996. )
  1997. async def press(
  1998. self,
  1999. key: str,
  2000. *,
  2001. delay: typing.Optional[float] = None,
  2002. timeout: typing.Optional[float] = None,
  2003. no_wait_after: typing.Optional[bool] = None,
  2004. ) -> None:
  2005. """ElementHandle.press
  2006. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  2007. `key` can specify the intended
  2008. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  2009. to generate the text for. A superset of the `key` values can be found
  2010. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  2011. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  2012. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  2013. etc.
  2014. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  2015. `ControlOrMeta`.
  2016. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  2017. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  2018. texts.
  2019. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  2020. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  2021. Parameters
  2022. ----------
  2023. key : str
  2024. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  2025. delay : Union[float, None]
  2026. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  2027. timeout : Union[float, None]
  2028. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2029. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2030. no_wait_after : Union[bool, None]
  2031. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  2032. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  2033. navigating to inaccessible pages. Defaults to `false`.
  2034. Deprecated: This option will default to `true` in the future.
  2035. """
  2036. return mapping.from_maybe_impl(
  2037. await self._impl_obj.press(
  2038. key=key, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  2039. )
  2040. )
  2041. async def set_checked(
  2042. self,
  2043. checked: bool,
  2044. *,
  2045. position: typing.Optional[Position] = None,
  2046. timeout: typing.Optional[float] = None,
  2047. force: typing.Optional[bool] = None,
  2048. no_wait_after: typing.Optional[bool] = None,
  2049. trial: typing.Optional[bool] = None,
  2050. ) -> None:
  2051. """ElementHandle.set_checked
  2052. This method checks or unchecks an element by performing the following steps:
  2053. 1. Ensure that element is a checkbox or a radio input. If not, this method throws.
  2054. 1. If the element already has the right checked state, this method returns immediately.
  2055. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  2056. the element is detached during the checks, the whole action is retried.
  2057. 1. Scroll the element into view if needed.
  2058. 1. Use `page.mouse` to click in the center of the element.
  2059. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  2060. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2061. Passing zero timeout disables this.
  2062. Parameters
  2063. ----------
  2064. checked : bool
  2065. Whether to check or uncheck the checkbox.
  2066. position : Union[{x: float, y: float}, None]
  2067. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2068. the element.
  2069. timeout : Union[float, None]
  2070. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2071. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2072. force : Union[bool, None]
  2073. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2074. no_wait_after : Union[bool, None]
  2075. This option has no effect.
  2076. Deprecated: This option has no effect.
  2077. trial : Union[bool, None]
  2078. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2079. to `false`. Useful to wait until the element is ready for the action without performing it.
  2080. """
  2081. return mapping.from_maybe_impl(
  2082. await self._impl_obj.set_checked(
  2083. checked=checked,
  2084. position=position,
  2085. timeout=timeout,
  2086. force=force,
  2087. noWaitAfter=no_wait_after,
  2088. trial=trial,
  2089. )
  2090. )
  2091. async def check(
  2092. self,
  2093. *,
  2094. position: typing.Optional[Position] = None,
  2095. timeout: typing.Optional[float] = None,
  2096. force: typing.Optional[bool] = None,
  2097. no_wait_after: typing.Optional[bool] = None,
  2098. trial: typing.Optional[bool] = None,
  2099. ) -> None:
  2100. """ElementHandle.check
  2101. This method checks the element by performing the following steps:
  2102. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  2103. checked, this method returns immediately.
  2104. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  2105. 1. Scroll the element into view if needed.
  2106. 1. Use `page.mouse` to click in the center of the element.
  2107. 1. Ensure that the element is now checked. If not, this method throws.
  2108. If the element is detached from the DOM at any moment during the action, this method throws.
  2109. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2110. Passing zero timeout disables this.
  2111. Parameters
  2112. ----------
  2113. position : Union[{x: float, y: float}, None]
  2114. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2115. the element.
  2116. timeout : Union[float, None]
  2117. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2118. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2119. force : Union[bool, None]
  2120. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2121. no_wait_after : Union[bool, None]
  2122. This option has no effect.
  2123. Deprecated: This option has no effect.
  2124. trial : Union[bool, None]
  2125. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2126. to `false`. Useful to wait until the element is ready for the action without performing it.
  2127. """
  2128. return mapping.from_maybe_impl(
  2129. await self._impl_obj.check(
  2130. position=position,
  2131. timeout=timeout,
  2132. force=force,
  2133. noWaitAfter=no_wait_after,
  2134. trial=trial,
  2135. )
  2136. )
  2137. async def uncheck(
  2138. self,
  2139. *,
  2140. position: typing.Optional[Position] = None,
  2141. timeout: typing.Optional[float] = None,
  2142. force: typing.Optional[bool] = None,
  2143. no_wait_after: typing.Optional[bool] = None,
  2144. trial: typing.Optional[bool] = None,
  2145. ) -> None:
  2146. """ElementHandle.uncheck
  2147. This method checks the element by performing the following steps:
  2148. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  2149. unchecked, this method returns immediately.
  2150. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  2151. 1. Scroll the element into view if needed.
  2152. 1. Use `page.mouse` to click in the center of the element.
  2153. 1. Ensure that the element is now unchecked. If not, this method throws.
  2154. If the element is detached from the DOM at any moment during the action, this method throws.
  2155. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  2156. Passing zero timeout disables this.
  2157. Parameters
  2158. ----------
  2159. position : Union[{x: float, y: float}, None]
  2160. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  2161. the element.
  2162. timeout : Union[float, None]
  2163. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2164. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2165. force : Union[bool, None]
  2166. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  2167. no_wait_after : Union[bool, None]
  2168. This option has no effect.
  2169. Deprecated: This option has no effect.
  2170. trial : Union[bool, None]
  2171. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  2172. to `false`. Useful to wait until the element is ready for the action without performing it.
  2173. """
  2174. return mapping.from_maybe_impl(
  2175. await self._impl_obj.uncheck(
  2176. position=position,
  2177. timeout=timeout,
  2178. force=force,
  2179. noWaitAfter=no_wait_after,
  2180. trial=trial,
  2181. )
  2182. )
  2183. async def bounding_box(self) -> typing.Optional[FloatRect]:
  2184. """ElementHandle.bounding_box
  2185. This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
  2186. calculated relative to the main frame viewport - which is usually the same as the browser window.
  2187. Scrolling affects the returned bounding box, similarly to
  2188. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2189. That means `x` and/or `y` may be negative.
  2190. Elements from child frames return the bounding box relative to the main frame, unlike the
  2191. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2192. Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
  2193. following snippet should click the center of the element.
  2194. **Usage**
  2195. ```py
  2196. box = await element_handle.bounding_box()
  2197. await page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
  2198. ```
  2199. Returns
  2200. -------
  2201. Union[{x: float, y: float, width: float, height: float}, None]
  2202. """
  2203. return mapping.from_impl_nullable(await self._impl_obj.bounding_box())
  2204. async def screenshot(
  2205. self,
  2206. *,
  2207. timeout: typing.Optional[float] = None,
  2208. type: typing.Optional[Literal["jpeg", "png"]] = None,
  2209. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  2210. quality: typing.Optional[int] = None,
  2211. omit_background: typing.Optional[bool] = None,
  2212. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  2213. caret: typing.Optional[Literal["hide", "initial"]] = None,
  2214. scale: typing.Optional[Literal["css", "device"]] = None,
  2215. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  2216. mask_color: typing.Optional[str] = None,
  2217. style: typing.Optional[str] = None,
  2218. ) -> bytes:
  2219. """ElementHandle.screenshot
  2220. This method captures a screenshot of the page, clipped to the size and position of this particular element. If the
  2221. element is covered by other elements, it will not be actually visible on the screenshot. If the element is a
  2222. scrollable container, only the currently scrolled content will be visible on the screenshot.
  2223. This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
  2224. a screenshot. If the element is detached from DOM, the method throws an error.
  2225. Returns the buffer with the captured screenshot.
  2226. Parameters
  2227. ----------
  2228. timeout : Union[float, None]
  2229. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2230. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2231. type : Union["jpeg", "png", None]
  2232. Specify screenshot type, defaults to `png`.
  2233. path : Union[pathlib.Path, str, None]
  2234. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  2235. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  2236. won't be saved to the disk.
  2237. quality : Union[int, None]
  2238. The quality of the image, between 0-100. Not applicable to `png` images.
  2239. omit_background : Union[bool, None]
  2240. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  2241. Defaults to `false`.
  2242. animations : Union["allow", "disabled", None]
  2243. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  2244. treatment depending on their duration:
  2245. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  2246. - infinite animations are canceled to initial state, and then played over after the screenshot.
  2247. Defaults to `"allow"` that leaves animations untouched.
  2248. caret : Union["hide", "initial", None]
  2249. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  2250. changed. Defaults to `"hide"`.
  2251. scale : Union["css", "device", None]
  2252. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  2253. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  2254. screenshots of high-dpi devices will be twice as large or even larger.
  2255. Defaults to `"device"`.
  2256. mask : Union[Sequence[Locator], None]
  2257. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  2258. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  2259. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  2260. that.
  2261. mask_color : Union[str, None]
  2262. Specify the color of the overlay box for masked elements, in
  2263. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  2264. style : Union[str, None]
  2265. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  2266. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  2267. the Shadow DOM and applies to the inner frames.
  2268. Returns
  2269. -------
  2270. bytes
  2271. """
  2272. return mapping.from_maybe_impl(
  2273. await self._impl_obj.screenshot(
  2274. timeout=timeout,
  2275. type=type,
  2276. path=path,
  2277. quality=quality,
  2278. omitBackground=omit_background,
  2279. animations=animations,
  2280. caret=caret,
  2281. scale=scale,
  2282. mask=mapping.to_impl(mask),
  2283. maskColor=mask_color,
  2284. style=style,
  2285. )
  2286. )
  2287. async def query_selector(self, selector: str) -> typing.Optional["ElementHandle"]:
  2288. """ElementHandle.query_selector
  2289. The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
  2290. the selector, returns `null`.
  2291. Parameters
  2292. ----------
  2293. selector : str
  2294. A selector to query for.
  2295. Returns
  2296. -------
  2297. Union[ElementHandle, None]
  2298. """
  2299. return mapping.from_impl_nullable(
  2300. await self._impl_obj.query_selector(selector=selector)
  2301. )
  2302. async def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  2303. """ElementHandle.query_selector_all
  2304. The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
  2305. the selector, returns empty array.
  2306. Parameters
  2307. ----------
  2308. selector : str
  2309. A selector to query for.
  2310. Returns
  2311. -------
  2312. List[ElementHandle]
  2313. """
  2314. return mapping.from_impl_list(
  2315. await self._impl_obj.query_selector_all(selector=selector)
  2316. )
  2317. async def eval_on_selector(
  2318. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  2319. ) -> typing.Any:
  2320. """ElementHandle.eval_on_selector
  2321. Returns the return value of `expression`.
  2322. The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
  2323. first argument to `expression`. If no elements match the selector, the method throws an error.
  2324. If `expression` returns a [Promise], then `element_handle.eval_on_selector()` would wait for the promise to
  2325. resolve and return its value.
  2326. **Usage**
  2327. ```py
  2328. tweet_handle = await page.query_selector(\".tweet\")
  2329. assert await tweet_handle.eval_on_selector(\".like\", \"node => node.innerText\") == \"100\"
  2330. assert await tweet_handle.eval_on_selector(\".retweets\", \"node => node.innerText\") == \"10\"
  2331. ```
  2332. Parameters
  2333. ----------
  2334. selector : str
  2335. A selector to query for.
  2336. expression : str
  2337. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2338. function is automatically invoked.
  2339. arg : Union[Any, None]
  2340. Optional argument to pass to `expression`.
  2341. Returns
  2342. -------
  2343. Any
  2344. """
  2345. return mapping.from_maybe_impl(
  2346. await self._impl_obj.eval_on_selector(
  2347. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  2348. )
  2349. )
  2350. async def eval_on_selector_all(
  2351. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  2352. ) -> typing.Any:
  2353. """ElementHandle.eval_on_selector_all
  2354. Returns the return value of `expression`.
  2355. The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
  2356. of matched elements as a first argument to `expression`.
  2357. If `expression` returns a [Promise], then `element_handle.eval_on_selector_all()` would wait for the promise to
  2358. resolve and return its value.
  2359. **Usage**
  2360. ```html
  2361. <div class=\"feed\">
  2362. <div class=\"tweet\">Hello!</div>
  2363. <div class=\"tweet\">Hi!</div>
  2364. </div>
  2365. ```
  2366. ```py
  2367. feed_handle = await page.query_selector(\".feed\")
  2368. assert await feed_handle.eval_on_selector_all(\".tweet\", \"nodes => nodes.map(n => n.innerText)\") == [\"hello!\", \"hi!\"]
  2369. ```
  2370. Parameters
  2371. ----------
  2372. selector : str
  2373. A selector to query for.
  2374. expression : str
  2375. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2376. function is automatically invoked.
  2377. arg : Union[Any, None]
  2378. Optional argument to pass to `expression`.
  2379. Returns
  2380. -------
  2381. Any
  2382. """
  2383. return mapping.from_maybe_impl(
  2384. await self._impl_obj.eval_on_selector_all(
  2385. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  2386. )
  2387. )
  2388. async def wait_for_element_state(
  2389. self,
  2390. state: Literal[
  2391. "disabled", "editable", "enabled", "hidden", "stable", "visible"
  2392. ],
  2393. *,
  2394. timeout: typing.Optional[float] = None,
  2395. ) -> None:
  2396. """ElementHandle.wait_for_element_state
  2397. Returns when the element satisfies the `state`.
  2398. Depending on the `state` parameter, this method waits for one of the [actionability](https://playwright.dev/python/docs/actionability) checks to
  2399. pass. This method throws when the element is detached while waiting, unless waiting for the `\"hidden\"` state.
  2400. - `\"visible\"` Wait until the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  2401. - `\"hidden\"` Wait until the element is [not visible](https://playwright.dev/python/docs/actionability#visible) or not attached. Note that
  2402. waiting for hidden does not throw when the element detaches.
  2403. - `\"stable\"` Wait until the element is both [visible](https://playwright.dev/python/docs/actionability#visible) and
  2404. [stable](https://playwright.dev/python/docs/actionability#stable).
  2405. - `\"enabled\"` Wait until the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  2406. - `\"disabled\"` Wait until the element is [not enabled](https://playwright.dev/python/docs/actionability#enabled).
  2407. - `\"editable\"` Wait until the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  2408. If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
  2409. Parameters
  2410. ----------
  2411. state : Union["disabled", "editable", "enabled", "hidden", "stable", "visible"]
  2412. A state to wait for, see below for more details.
  2413. timeout : Union[float, None]
  2414. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2415. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2416. """
  2417. return mapping.from_maybe_impl(
  2418. await self._impl_obj.wait_for_element_state(state=state, timeout=timeout)
  2419. )
  2420. async def wait_for_selector(
  2421. self,
  2422. selector: str,
  2423. *,
  2424. state: typing.Optional[
  2425. Literal["attached", "detached", "hidden", "visible"]
  2426. ] = None,
  2427. timeout: typing.Optional[float] = None,
  2428. strict: typing.Optional[bool] = None,
  2429. ) -> typing.Optional["ElementHandle"]:
  2430. """ElementHandle.wait_for_selector
  2431. Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
  2432. `detached`.
  2433. Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
  2434. or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
  2435. method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
  2436. function will throw.
  2437. **Usage**
  2438. ```py
  2439. await page.set_content(\"<div><span></span></div>\")
  2440. div = await page.query_selector(\"div\")
  2441. # waiting for the \"span\" selector relative to the div.
  2442. span = await div.wait_for_selector(\"span\", state=\"attached\")
  2443. ```
  2444. **NOTE** This method does not work across navigations, use `page.wait_for_selector()` instead.
  2445. Parameters
  2446. ----------
  2447. selector : str
  2448. A selector to query for.
  2449. state : Union["attached", "detached", "hidden", "visible", None]
  2450. Defaults to `'visible'`. Can be either:
  2451. - `'attached'` - wait for element to be present in DOM.
  2452. - `'detached'` - wait for element to not be present in DOM.
  2453. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  2454. without any content or with `display:none` has an empty bounding box and is not considered visible.
  2455. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  2456. `visibility:hidden`. This is opposite to the `'visible'` option.
  2457. timeout : Union[float, None]
  2458. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2459. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2460. strict : Union[bool, None]
  2461. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2462. element, the call throws an exception.
  2463. Returns
  2464. -------
  2465. Union[ElementHandle, None]
  2466. """
  2467. return mapping.from_impl_nullable(
  2468. await self._impl_obj.wait_for_selector(
  2469. selector=selector, state=state, timeout=timeout, strict=strict
  2470. )
  2471. )
  2472. mapping.register(ElementHandleImpl, ElementHandle)
  2473. class FileChooser(AsyncBase):
  2474. @property
  2475. def page(self) -> "Page":
  2476. """FileChooser.page
  2477. Returns page this file chooser belongs to.
  2478. Returns
  2479. -------
  2480. Page
  2481. """
  2482. return mapping.from_impl(self._impl_obj.page)
  2483. @property
  2484. def element(self) -> "ElementHandle":
  2485. """FileChooser.element
  2486. Returns input element associated with this file chooser.
  2487. Returns
  2488. -------
  2489. ElementHandle
  2490. """
  2491. return mapping.from_impl(self._impl_obj.element)
  2492. def is_multiple(self) -> bool:
  2493. """FileChooser.is_multiple
  2494. Returns whether this file chooser accepts multiple files.
  2495. Returns
  2496. -------
  2497. bool
  2498. """
  2499. return mapping.from_maybe_impl(self._impl_obj.is_multiple())
  2500. async def set_files(
  2501. self,
  2502. files: typing.Union[
  2503. str,
  2504. pathlib.Path,
  2505. FilePayload,
  2506. typing.Sequence[typing.Union[str, pathlib.Path]],
  2507. typing.Sequence[FilePayload],
  2508. ],
  2509. *,
  2510. timeout: typing.Optional[float] = None,
  2511. no_wait_after: typing.Optional[bool] = None,
  2512. ) -> None:
  2513. """FileChooser.set_files
  2514. Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,
  2515. then they are resolved relative to the current working directory. For empty array, clears the selected files.
  2516. Parameters
  2517. ----------
  2518. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  2519. timeout : Union[float, None]
  2520. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2521. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2522. no_wait_after : Union[bool, None]
  2523. This option has no effect.
  2524. Deprecated: This option has no effect.
  2525. """
  2526. return mapping.from_maybe_impl(
  2527. await self._impl_obj.set_files(
  2528. files=mapping.to_impl(files), timeout=timeout, noWaitAfter=no_wait_after
  2529. )
  2530. )
  2531. mapping.register(FileChooserImpl, FileChooser)
  2532. class Frame(AsyncBase):
  2533. @property
  2534. def page(self) -> "Page":
  2535. """Frame.page
  2536. Returns the page containing this frame.
  2537. Returns
  2538. -------
  2539. Page
  2540. """
  2541. return mapping.from_impl(self._impl_obj.page)
  2542. @property
  2543. def name(self) -> str:
  2544. """Frame.name
  2545. Returns frame's name attribute as specified in the tag.
  2546. If the name is empty, returns the id attribute instead.
  2547. **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed
  2548. later.
  2549. Returns
  2550. -------
  2551. str
  2552. """
  2553. return mapping.from_maybe_impl(self._impl_obj.name)
  2554. @property
  2555. def url(self) -> str:
  2556. """Frame.url
  2557. Returns frame's url.
  2558. Returns
  2559. -------
  2560. str
  2561. """
  2562. return mapping.from_maybe_impl(self._impl_obj.url)
  2563. @property
  2564. def parent_frame(self) -> typing.Optional["Frame"]:
  2565. """Frame.parent_frame
  2566. Parent frame, if any. Detached frames and main frames return `null`.
  2567. Returns
  2568. -------
  2569. Union[Frame, None]
  2570. """
  2571. return mapping.from_impl_nullable(self._impl_obj.parent_frame)
  2572. @property
  2573. def child_frames(self) -> typing.List["Frame"]:
  2574. """Frame.child_frames
  2575. Returns
  2576. -------
  2577. List[Frame]
  2578. """
  2579. return mapping.from_impl_list(self._impl_obj.child_frames)
  2580. async def goto(
  2581. self,
  2582. url: str,
  2583. *,
  2584. timeout: typing.Optional[float] = None,
  2585. wait_until: typing.Optional[
  2586. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2587. ] = None,
  2588. referer: typing.Optional[str] = None,
  2589. ) -> typing.Optional["Response"]:
  2590. """Frame.goto
  2591. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  2592. the last redirect.
  2593. The method will throw an error if:
  2594. - there's an SSL error (e.g. in case of self-signed certificates).
  2595. - target URL is invalid.
  2596. - the `timeout` is exceeded during navigation.
  2597. - the remote server does not respond or is unreachable.
  2598. - the main resource failed to load.
  2599. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
  2600. \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
  2601. `response.status()`.
  2602. **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
  2603. to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
  2604. **NOTE** Headless mode doesn't support navigation to a PDF document. See the
  2605. [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
  2606. Parameters
  2607. ----------
  2608. url : str
  2609. URL to navigate frame to. The url should include scheme, e.g. `https://`.
  2610. timeout : Union[float, None]
  2611. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2612. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2613. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2614. `page.set_default_timeout()` methods.
  2615. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2616. When to consider operation succeeded, defaults to `load`. Events can be either:
  2617. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2618. - `'load'` - consider operation to be finished when the `load` event is fired.
  2619. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2620. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2621. - `'commit'` - consider operation to be finished when network response is received and the document started
  2622. loading.
  2623. referer : Union[str, None]
  2624. Referer header value. If provided it will take preference over the referer header value set by
  2625. `page.set_extra_http_headers()`.
  2626. Returns
  2627. -------
  2628. Union[Response, None]
  2629. """
  2630. return mapping.from_impl_nullable(
  2631. await self._impl_obj.goto(
  2632. url=url, timeout=timeout, waitUntil=wait_until, referer=referer
  2633. )
  2634. )
  2635. def expect_navigation(
  2636. self,
  2637. *,
  2638. url: typing.Optional[
  2639. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  2640. ] = None,
  2641. wait_until: typing.Optional[
  2642. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2643. ] = None,
  2644. timeout: typing.Optional[float] = None,
  2645. ) -> AsyncEventContextManager["Response"]:
  2646. """Frame.expect_navigation
  2647. Waits for the frame navigation and returns the main resource response. In case of multiple redirects, the
  2648. navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
  2649. navigation due to History API usage, the navigation will resolve with `null`.
  2650. **Usage**
  2651. This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly
  2652. cause the frame to navigate. Consider this example:
  2653. ```py
  2654. async with frame.expect_navigation():
  2655. await frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  2656. # Resolves after navigation has finished
  2657. ```
  2658. **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
  2659. is considered a navigation.
  2660. Parameters
  2661. ----------
  2662. url : Union[Callable[[str], bool], Pattern[str], str, None]
  2663. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  2664. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  2665. equal to the string.
  2666. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2667. When to consider operation succeeded, defaults to `load`. Events can be either:
  2668. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2669. - `'load'` - consider operation to be finished when the `load` event is fired.
  2670. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2671. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2672. - `'commit'` - consider operation to be finished when network response is received and the document started
  2673. loading.
  2674. timeout : Union[float, None]
  2675. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2676. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2677. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2678. `page.set_default_timeout()` methods.
  2679. Returns
  2680. -------
  2681. EventContextManager[Response]
  2682. """
  2683. return AsyncEventContextManager(
  2684. self._impl_obj.expect_navigation(
  2685. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  2686. ).future
  2687. )
  2688. async def wait_for_url(
  2689. self,
  2690. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  2691. *,
  2692. wait_until: typing.Optional[
  2693. Literal["commit", "domcontentloaded", "load", "networkidle"]
  2694. ] = None,
  2695. timeout: typing.Optional[float] = None,
  2696. ) -> None:
  2697. """Frame.wait_for_url
  2698. Waits for the frame to navigate to the given URL.
  2699. **Usage**
  2700. ```py
  2701. await frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  2702. await frame.wait_for_url(\"**/target.html\")
  2703. ```
  2704. Parameters
  2705. ----------
  2706. url : Union[Callable[[str], bool], Pattern[str], str]
  2707. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  2708. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  2709. equal to the string.
  2710. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  2711. When to consider operation succeeded, defaults to `load`. Events can be either:
  2712. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  2713. - `'load'` - consider operation to be finished when the `load` event is fired.
  2714. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  2715. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  2716. - `'commit'` - consider operation to be finished when network response is received and the document started
  2717. loading.
  2718. timeout : Union[float, None]
  2719. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2720. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2721. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2722. `page.set_default_timeout()` methods.
  2723. """
  2724. return mapping.from_maybe_impl(
  2725. await self._impl_obj.wait_for_url(
  2726. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  2727. )
  2728. )
  2729. async def wait_for_load_state(
  2730. self,
  2731. state: typing.Optional[
  2732. Literal["domcontentloaded", "load", "networkidle"]
  2733. ] = None,
  2734. *,
  2735. timeout: typing.Optional[float] = None,
  2736. ) -> None:
  2737. """Frame.wait_for_load_state
  2738. Waits for the required load state to be reached.
  2739. This returns when the frame reaches a required load state, `load` by default. The navigation must have been
  2740. committed when this method is called. If current document has already reached the required state, resolves
  2741. immediately.
  2742. **NOTE** Most of the time, this method is not needed because Playwright
  2743. [auto-waits before every action](https://playwright.dev/python/docs/actionability).
  2744. **Usage**
  2745. ```py
  2746. await frame.click(\"button\") # click triggers navigation.
  2747. await frame.wait_for_load_state() # the promise resolves after \"load\" event.
  2748. ```
  2749. Parameters
  2750. ----------
  2751. state : Union["domcontentloaded", "load", "networkidle", None]
  2752. Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
  2753. document, the method resolves immediately. Can be one of:
  2754. - `'load'` - wait for the `load` event to be fired.
  2755. - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
  2756. - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
  2757. this method for testing, rely on web assertions to assess readiness instead.
  2758. timeout : Union[float, None]
  2759. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  2760. be changed by using the `browser_context.set_default_navigation_timeout()`,
  2761. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  2762. `page.set_default_timeout()` methods.
  2763. """
  2764. return mapping.from_maybe_impl(
  2765. await self._impl_obj.wait_for_load_state(state=state, timeout=timeout)
  2766. )
  2767. async def frame_element(self) -> "ElementHandle":
  2768. """Frame.frame_element
  2769. Returns the `frame` or `iframe` element handle which corresponds to this frame.
  2770. This is an inverse of `element_handle.content_frame()`. Note that returned handle actually belongs to the
  2771. parent frame.
  2772. This method throws an error if the frame has been detached before `frameElement()` returns.
  2773. **Usage**
  2774. ```py
  2775. frame_element = await frame.frame_element()
  2776. content_frame = await frame_element.content_frame()
  2777. assert frame == content_frame
  2778. ```
  2779. Returns
  2780. -------
  2781. ElementHandle
  2782. """
  2783. return mapping.from_impl(await self._impl_obj.frame_element())
  2784. async def evaluate(
  2785. self, expression: str, arg: typing.Optional[typing.Any] = None
  2786. ) -> typing.Any:
  2787. """Frame.evaluate
  2788. Returns the return value of `expression`.
  2789. If the function passed to the `frame.evaluate()` returns a [Promise], then `frame.evaluate()` would
  2790. wait for the promise to resolve and return its value.
  2791. If the function passed to the `frame.evaluate()` returns a non-[Serializable] value, then
  2792. `frame.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
  2793. are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  2794. **Usage**
  2795. ```py
  2796. result = await frame.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
  2797. print(result) # prints \"56\"
  2798. ```
  2799. A string can also be passed in instead of a function.
  2800. ```py
  2801. print(await frame.evaluate(\"1 + 2\")) # prints \"3\"
  2802. x = 10
  2803. print(await frame.evaluate(f\"1 + {x}\")) # prints \"11\"
  2804. ```
  2805. `ElementHandle` instances can be passed as an argument to the `frame.evaluate()`:
  2806. ```py
  2807. body_handle = await frame.evaluate(\"document.body\")
  2808. html = await frame.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
  2809. await body_handle.dispose()
  2810. ```
  2811. Parameters
  2812. ----------
  2813. expression : str
  2814. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2815. function is automatically invoked.
  2816. arg : Union[Any, None]
  2817. Optional argument to pass to `expression`.
  2818. Returns
  2819. -------
  2820. Any
  2821. """
  2822. return mapping.from_maybe_impl(
  2823. await self._impl_obj.evaluate(
  2824. expression=expression, arg=mapping.to_impl(arg)
  2825. )
  2826. )
  2827. async def evaluate_handle(
  2828. self, expression: str, arg: typing.Optional[typing.Any] = None
  2829. ) -> "JSHandle":
  2830. """Frame.evaluate_handle
  2831. Returns the return value of `expression` as a `JSHandle`.
  2832. The only difference between `frame.evaluate()` and `frame.evaluate_handle()` is that
  2833. `frame.evaluate_handle()` returns `JSHandle`.
  2834. If the function, passed to the `frame.evaluate_handle()`, returns a [Promise], then
  2835. `frame.evaluate_handle()` would wait for the promise to resolve and return its value.
  2836. **Usage**
  2837. ```py
  2838. a_window_handle = await frame.evaluate_handle(\"Promise.resolve(window)\")
  2839. a_window_handle # handle for the window object.
  2840. ```
  2841. A string can also be passed in instead of a function.
  2842. ```py
  2843. a_handle = await page.evaluate_handle(\"document\") # handle for the \"document\"
  2844. ```
  2845. `JSHandle` instances can be passed as an argument to the `frame.evaluate_handle()`:
  2846. ```py
  2847. a_handle = await page.evaluate_handle(\"document.body\")
  2848. result_handle = await page.evaluate_handle(\"body => body.innerHTML\", a_handle)
  2849. print(await result_handle.json_value())
  2850. await result_handle.dispose()
  2851. ```
  2852. Parameters
  2853. ----------
  2854. expression : str
  2855. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  2856. function is automatically invoked.
  2857. arg : Union[Any, None]
  2858. Optional argument to pass to `expression`.
  2859. Returns
  2860. -------
  2861. JSHandle
  2862. """
  2863. return mapping.from_impl(
  2864. await self._impl_obj.evaluate_handle(
  2865. expression=expression, arg=mapping.to_impl(arg)
  2866. )
  2867. )
  2868. async def query_selector(
  2869. self, selector: str, *, strict: typing.Optional[bool] = None
  2870. ) -> typing.Optional["ElementHandle"]:
  2871. """Frame.query_selector
  2872. Returns the ElementHandle pointing to the frame element.
  2873. **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects and web-first assertions instead.
  2874. The method finds an element matching the specified selector within the frame. If no elements match the selector,
  2875. returns `null`.
  2876. Parameters
  2877. ----------
  2878. selector : str
  2879. A selector to query for.
  2880. strict : Union[bool, None]
  2881. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2882. element, the call throws an exception.
  2883. Returns
  2884. -------
  2885. Union[ElementHandle, None]
  2886. """
  2887. return mapping.from_impl_nullable(
  2888. await self._impl_obj.query_selector(selector=selector, strict=strict)
  2889. )
  2890. async def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  2891. """Frame.query_selector_all
  2892. Returns the ElementHandles pointing to the frame elements.
  2893. **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects instead.
  2894. The method finds all elements matching the specified selector within the frame. If no elements match the selector,
  2895. returns empty array.
  2896. Parameters
  2897. ----------
  2898. selector : str
  2899. A selector to query for.
  2900. Returns
  2901. -------
  2902. List[ElementHandle]
  2903. """
  2904. return mapping.from_impl_list(
  2905. await self._impl_obj.query_selector_all(selector=selector)
  2906. )
  2907. async def wait_for_selector(
  2908. self,
  2909. selector: str,
  2910. *,
  2911. strict: typing.Optional[bool] = None,
  2912. timeout: typing.Optional[float] = None,
  2913. state: typing.Optional[
  2914. Literal["attached", "detached", "hidden", "visible"]
  2915. ] = None,
  2916. ) -> typing.Optional["ElementHandle"]:
  2917. """Frame.wait_for_selector
  2918. Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
  2919. `detached`.
  2920. **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
  2921. objects and web-first assertions make the code wait-for-selector-free.
  2922. Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
  2923. at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
  2924. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
  2925. **Usage**
  2926. This method works across navigations:
  2927. ```py
  2928. import asyncio
  2929. from playwright.async_api import async_playwright, Playwright
  2930. async def run(playwright: Playwright):
  2931. chromium = playwright.chromium
  2932. browser = await chromium.launch()
  2933. page = await browser.new_page()
  2934. for current_url in [\"https://google.com\", \"https://bbc.com\"]:
  2935. await page.goto(current_url, wait_until=\"domcontentloaded\")
  2936. element = await page.main_frame.wait_for_selector(\"img\")
  2937. print(\"Loaded image: \" + str(await element.get_attribute(\"src\")))
  2938. await browser.close()
  2939. async def main():
  2940. async with async_playwright() as playwright:
  2941. await run(playwright)
  2942. asyncio.run(main())
  2943. ```
  2944. Parameters
  2945. ----------
  2946. selector : str
  2947. A selector to query for.
  2948. strict : Union[bool, None]
  2949. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2950. element, the call throws an exception.
  2951. timeout : Union[float, None]
  2952. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2953. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2954. state : Union["attached", "detached", "hidden", "visible", None]
  2955. Defaults to `'visible'`. Can be either:
  2956. - `'attached'` - wait for element to be present in DOM.
  2957. - `'detached'` - wait for element to not be present in DOM.
  2958. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  2959. without any content or with `display:none` has an empty bounding box and is not considered visible.
  2960. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  2961. `visibility:hidden`. This is opposite to the `'visible'` option.
  2962. Returns
  2963. -------
  2964. Union[ElementHandle, None]
  2965. """
  2966. return mapping.from_impl_nullable(
  2967. await self._impl_obj.wait_for_selector(
  2968. selector=selector, strict=strict, timeout=timeout, state=state
  2969. )
  2970. )
  2971. async def is_checked(
  2972. self,
  2973. selector: str,
  2974. *,
  2975. strict: typing.Optional[bool] = None,
  2976. timeout: typing.Optional[float] = None,
  2977. ) -> bool:
  2978. """Frame.is_checked
  2979. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  2980. Parameters
  2981. ----------
  2982. selector : str
  2983. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  2984. used.
  2985. strict : Union[bool, None]
  2986. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  2987. element, the call throws an exception.
  2988. timeout : Union[float, None]
  2989. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  2990. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  2991. Returns
  2992. -------
  2993. bool
  2994. """
  2995. return mapping.from_maybe_impl(
  2996. await self._impl_obj.is_checked(
  2997. selector=selector, strict=strict, timeout=timeout
  2998. )
  2999. )
  3000. async def is_disabled(
  3001. self,
  3002. selector: str,
  3003. *,
  3004. strict: typing.Optional[bool] = None,
  3005. timeout: typing.Optional[float] = None,
  3006. ) -> bool:
  3007. """Frame.is_disabled
  3008. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  3009. Parameters
  3010. ----------
  3011. selector : str
  3012. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3013. used.
  3014. strict : Union[bool, None]
  3015. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3016. element, the call throws an exception.
  3017. timeout : Union[float, None]
  3018. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3019. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3020. Returns
  3021. -------
  3022. bool
  3023. """
  3024. return mapping.from_maybe_impl(
  3025. await self._impl_obj.is_disabled(
  3026. selector=selector, strict=strict, timeout=timeout
  3027. )
  3028. )
  3029. async def is_editable(
  3030. self,
  3031. selector: str,
  3032. *,
  3033. strict: typing.Optional[bool] = None,
  3034. timeout: typing.Optional[float] = None,
  3035. ) -> bool:
  3036. """Frame.is_editable
  3037. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  3038. Parameters
  3039. ----------
  3040. selector : str
  3041. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3042. used.
  3043. strict : Union[bool, None]
  3044. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3045. element, the call throws an exception.
  3046. timeout : Union[float, None]
  3047. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3048. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3049. Returns
  3050. -------
  3051. bool
  3052. """
  3053. return mapping.from_maybe_impl(
  3054. await self._impl_obj.is_editable(
  3055. selector=selector, strict=strict, timeout=timeout
  3056. )
  3057. )
  3058. async def is_enabled(
  3059. self,
  3060. selector: str,
  3061. *,
  3062. strict: typing.Optional[bool] = None,
  3063. timeout: typing.Optional[float] = None,
  3064. ) -> bool:
  3065. """Frame.is_enabled
  3066. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  3067. Parameters
  3068. ----------
  3069. selector : str
  3070. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3071. used.
  3072. strict : Union[bool, None]
  3073. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3074. element, the call throws an exception.
  3075. timeout : Union[float, None]
  3076. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3077. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3078. Returns
  3079. -------
  3080. bool
  3081. """
  3082. return mapping.from_maybe_impl(
  3083. await self._impl_obj.is_enabled(
  3084. selector=selector, strict=strict, timeout=timeout
  3085. )
  3086. )
  3087. async def is_hidden(
  3088. self, selector: str, *, strict: typing.Optional[bool] = None
  3089. ) -> bool:
  3090. """Frame.is_hidden
  3091. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
  3092. does not match any elements is considered hidden.
  3093. Parameters
  3094. ----------
  3095. selector : str
  3096. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3097. used.
  3098. strict : Union[bool, None]
  3099. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3100. element, the call throws an exception.
  3101. Returns
  3102. -------
  3103. bool
  3104. """
  3105. return mapping.from_maybe_impl(
  3106. await self._impl_obj.is_hidden(selector=selector, strict=strict)
  3107. )
  3108. async def is_visible(
  3109. self, selector: str, *, strict: typing.Optional[bool] = None
  3110. ) -> bool:
  3111. """Frame.is_visible
  3112. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
  3113. is considered not visible.
  3114. Parameters
  3115. ----------
  3116. selector : str
  3117. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3118. used.
  3119. strict : Union[bool, None]
  3120. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3121. element, the call throws an exception.
  3122. Returns
  3123. -------
  3124. bool
  3125. """
  3126. return mapping.from_maybe_impl(
  3127. await self._impl_obj.is_visible(selector=selector, strict=strict)
  3128. )
  3129. async def dispatch_event(
  3130. self,
  3131. selector: str,
  3132. type: str,
  3133. event_init: typing.Optional[typing.Dict] = None,
  3134. *,
  3135. strict: typing.Optional[bool] = None,
  3136. timeout: typing.Optional[float] = None,
  3137. ) -> None:
  3138. """Frame.dispatch_event
  3139. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  3140. `click` is dispatched. This is equivalent to calling
  3141. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  3142. **Usage**
  3143. ```py
  3144. await frame.dispatch_event(\"button#submit\", \"click\")
  3145. ```
  3146. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  3147. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  3148. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  3149. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  3150. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  3151. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  3152. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  3153. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  3154. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  3155. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  3156. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  3157. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  3158. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  3159. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  3160. ```py
  3161. # note you can only create data_transfer in chromium and firefox
  3162. data_transfer = await frame.evaluate_handle(\"new DataTransfer()\")
  3163. await frame.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
  3164. ```
  3165. Parameters
  3166. ----------
  3167. selector : str
  3168. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3169. used.
  3170. type : str
  3171. DOM event type: `"click"`, `"dragstart"`, etc.
  3172. event_init : Union[Dict, None]
  3173. Optional event-specific initialization properties.
  3174. strict : Union[bool, None]
  3175. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3176. element, the call throws an exception.
  3177. timeout : Union[float, None]
  3178. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3179. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3180. """
  3181. return mapping.from_maybe_impl(
  3182. await self._impl_obj.dispatch_event(
  3183. selector=selector,
  3184. type=type,
  3185. eventInit=mapping.to_impl(event_init),
  3186. strict=strict,
  3187. timeout=timeout,
  3188. )
  3189. )
  3190. async def eval_on_selector(
  3191. self,
  3192. selector: str,
  3193. expression: str,
  3194. arg: typing.Optional[typing.Any] = None,
  3195. *,
  3196. strict: typing.Optional[bool] = None,
  3197. ) -> typing.Any:
  3198. """Frame.eval_on_selector
  3199. Returns the return value of `expression`.
  3200. The method finds an element matching the specified selector within the frame and passes it as a first argument to
  3201. `expression`. If no elements match the selector, the method throws an error.
  3202. If `expression` returns a [Promise], then `frame.eval_on_selector()` would wait for the promise to resolve
  3203. and return its value.
  3204. **Usage**
  3205. ```py
  3206. search_value = await frame.eval_on_selector(\"#search\", \"el => el.value\")
  3207. preload_href = await frame.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
  3208. html = await frame.eval_on_selector(\".main-container\", \"(e, suffix) => e.outerHTML + suffix\", \"hello\")
  3209. ```
  3210. Parameters
  3211. ----------
  3212. selector : str
  3213. A selector to query for.
  3214. expression : str
  3215. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3216. function is automatically invoked.
  3217. arg : Union[Any, None]
  3218. Optional argument to pass to `expression`.
  3219. strict : Union[bool, None]
  3220. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3221. element, the call throws an exception.
  3222. Returns
  3223. -------
  3224. Any
  3225. """
  3226. return mapping.from_maybe_impl(
  3227. await self._impl_obj.eval_on_selector(
  3228. selector=selector,
  3229. expression=expression,
  3230. arg=mapping.to_impl(arg),
  3231. strict=strict,
  3232. )
  3233. )
  3234. async def eval_on_selector_all(
  3235. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  3236. ) -> typing.Any:
  3237. """Frame.eval_on_selector_all
  3238. Returns the return value of `expression`.
  3239. The method finds all elements matching the specified selector within the frame and passes an array of matched
  3240. elements as a first argument to `expression`.
  3241. If `expression` returns a [Promise], then `frame.eval_on_selector_all()` would wait for the promise to resolve
  3242. and return its value.
  3243. **Usage**
  3244. ```py
  3245. divs_counts = await frame.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
  3246. ```
  3247. Parameters
  3248. ----------
  3249. selector : str
  3250. A selector to query for.
  3251. expression : str
  3252. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  3253. function is automatically invoked.
  3254. arg : Union[Any, None]
  3255. Optional argument to pass to `expression`.
  3256. Returns
  3257. -------
  3258. Any
  3259. """
  3260. return mapping.from_maybe_impl(
  3261. await self._impl_obj.eval_on_selector_all(
  3262. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  3263. )
  3264. )
  3265. async def content(self) -> str:
  3266. """Frame.content
  3267. Gets the full HTML contents of the frame, including the doctype.
  3268. Returns
  3269. -------
  3270. str
  3271. """
  3272. return mapping.from_maybe_impl(await self._impl_obj.content())
  3273. async def set_content(
  3274. self,
  3275. html: str,
  3276. *,
  3277. timeout: typing.Optional[float] = None,
  3278. wait_until: typing.Optional[
  3279. Literal["commit", "domcontentloaded", "load", "networkidle"]
  3280. ] = None,
  3281. ) -> None:
  3282. """Frame.set_content
  3283. This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
  3284. inheriting all its specific characteristics and behaviors.
  3285. Parameters
  3286. ----------
  3287. html : str
  3288. HTML markup to assign to the page.
  3289. timeout : Union[float, None]
  3290. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  3291. be changed by using the `browser_context.set_default_navigation_timeout()`,
  3292. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  3293. `page.set_default_timeout()` methods.
  3294. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  3295. When to consider operation succeeded, defaults to `load`. Events can be either:
  3296. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  3297. - `'load'` - consider operation to be finished when the `load` event is fired.
  3298. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  3299. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  3300. - `'commit'` - consider operation to be finished when network response is received and the document started
  3301. loading.
  3302. """
  3303. return mapping.from_maybe_impl(
  3304. await self._impl_obj.set_content(
  3305. html=html, timeout=timeout, waitUntil=wait_until
  3306. )
  3307. )
  3308. def is_detached(self) -> bool:
  3309. """Frame.is_detached
  3310. Returns `true` if the frame has been detached, or `false` otherwise.
  3311. Returns
  3312. -------
  3313. bool
  3314. """
  3315. return mapping.from_maybe_impl(self._impl_obj.is_detached())
  3316. async def add_script_tag(
  3317. self,
  3318. *,
  3319. url: typing.Optional[str] = None,
  3320. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  3321. content: typing.Optional[str] = None,
  3322. type: typing.Optional[str] = None,
  3323. ) -> "ElementHandle":
  3324. """Frame.add_script_tag
  3325. Returns the added tag when the script's onload fires or when the script content was injected into frame.
  3326. Adds a `<script>` tag into the page with the desired url or content.
  3327. Parameters
  3328. ----------
  3329. url : Union[str, None]
  3330. URL of a script to be added.
  3331. path : Union[pathlib.Path, str, None]
  3332. Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
  3333. to the current working directory.
  3334. content : Union[str, None]
  3335. Raw JavaScript content to be injected into frame.
  3336. type : Union[str, None]
  3337. Script type. Use 'module' in order to load a JavaScript ES6 module. See
  3338. [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
  3339. Returns
  3340. -------
  3341. ElementHandle
  3342. """
  3343. return mapping.from_impl(
  3344. await self._impl_obj.add_script_tag(
  3345. url=url, path=path, content=content, type=type
  3346. )
  3347. )
  3348. async def add_style_tag(
  3349. self,
  3350. *,
  3351. url: typing.Optional[str] = None,
  3352. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  3353. content: typing.Optional[str] = None,
  3354. ) -> "ElementHandle":
  3355. """Frame.add_style_tag
  3356. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
  3357. Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
  3358. content.
  3359. Parameters
  3360. ----------
  3361. url : Union[str, None]
  3362. URL of the `<link>` tag.
  3363. path : Union[pathlib.Path, str, None]
  3364. Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
  3365. current working directory.
  3366. content : Union[str, None]
  3367. Raw CSS content to be injected into frame.
  3368. Returns
  3369. -------
  3370. ElementHandle
  3371. """
  3372. return mapping.from_impl(
  3373. await self._impl_obj.add_style_tag(url=url, path=path, content=content)
  3374. )
  3375. async def click(
  3376. self,
  3377. selector: str,
  3378. *,
  3379. modifiers: typing.Optional[
  3380. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3381. ] = None,
  3382. position: typing.Optional[Position] = None,
  3383. delay: typing.Optional[float] = None,
  3384. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  3385. click_count: typing.Optional[int] = None,
  3386. timeout: typing.Optional[float] = None,
  3387. force: typing.Optional[bool] = None,
  3388. no_wait_after: typing.Optional[bool] = None,
  3389. strict: typing.Optional[bool] = None,
  3390. trial: typing.Optional[bool] = None,
  3391. ) -> None:
  3392. """Frame.click
  3393. This method clicks an element matching `selector` by performing the following steps:
  3394. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3395. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3396. the element is detached during the checks, the whole action is retried.
  3397. 1. Scroll the element into view if needed.
  3398. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  3399. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  3400. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3401. Passing zero timeout disables this.
  3402. Parameters
  3403. ----------
  3404. selector : str
  3405. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3406. used.
  3407. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3408. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3409. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3410. "Control" on Windows and Linux and to "Meta" on macOS.
  3411. position : Union[{x: float, y: float}, None]
  3412. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3413. the element.
  3414. delay : Union[float, None]
  3415. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  3416. button : Union["left", "middle", "right", None]
  3417. Defaults to `left`.
  3418. click_count : Union[int, None]
  3419. defaults to 1. See [UIEvent.detail].
  3420. timeout : Union[float, None]
  3421. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3422. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3423. force : Union[bool, None]
  3424. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3425. no_wait_after : Union[bool, None]
  3426. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  3427. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  3428. navigating to inaccessible pages. Defaults to `false`.
  3429. Deprecated: This option will default to `true` in the future.
  3430. strict : Union[bool, None]
  3431. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3432. element, the call throws an exception.
  3433. trial : Union[bool, None]
  3434. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3435. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3436. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3437. are pressed.
  3438. """
  3439. return mapping.from_maybe_impl(
  3440. await self._impl_obj.click(
  3441. selector=selector,
  3442. modifiers=mapping.to_impl(modifiers),
  3443. position=position,
  3444. delay=delay,
  3445. button=button,
  3446. clickCount=click_count,
  3447. timeout=timeout,
  3448. force=force,
  3449. noWaitAfter=no_wait_after,
  3450. strict=strict,
  3451. trial=trial,
  3452. )
  3453. )
  3454. async def dblclick(
  3455. self,
  3456. selector: str,
  3457. *,
  3458. modifiers: typing.Optional[
  3459. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3460. ] = None,
  3461. position: typing.Optional[Position] = None,
  3462. delay: typing.Optional[float] = None,
  3463. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  3464. timeout: typing.Optional[float] = None,
  3465. force: typing.Optional[bool] = None,
  3466. no_wait_after: typing.Optional[bool] = None,
  3467. strict: typing.Optional[bool] = None,
  3468. trial: typing.Optional[bool] = None,
  3469. ) -> None:
  3470. """Frame.dblclick
  3471. This method double clicks an element matching `selector` by performing the following steps:
  3472. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3473. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3474. the element is detached during the checks, the whole action is retried.
  3475. 1. Scroll the element into view if needed.
  3476. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`. if
  3477. the first click of the `dblclick()` triggers a navigation event, this method will throw.
  3478. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3479. Passing zero timeout disables this.
  3480. **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
  3481. Parameters
  3482. ----------
  3483. selector : str
  3484. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3485. used.
  3486. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3487. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3488. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3489. "Control" on Windows and Linux and to "Meta" on macOS.
  3490. position : Union[{x: float, y: float}, None]
  3491. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3492. the element.
  3493. delay : Union[float, None]
  3494. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  3495. button : Union["left", "middle", "right", None]
  3496. Defaults to `left`.
  3497. timeout : Union[float, None]
  3498. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3499. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3500. force : Union[bool, None]
  3501. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3502. no_wait_after : Union[bool, None]
  3503. This option has no effect.
  3504. Deprecated: This option has no effect.
  3505. strict : Union[bool, None]
  3506. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3507. element, the call throws an exception.
  3508. trial : Union[bool, None]
  3509. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3510. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3511. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3512. are pressed.
  3513. """
  3514. return mapping.from_maybe_impl(
  3515. await self._impl_obj.dblclick(
  3516. selector=selector,
  3517. modifiers=mapping.to_impl(modifiers),
  3518. position=position,
  3519. delay=delay,
  3520. button=button,
  3521. timeout=timeout,
  3522. force=force,
  3523. noWaitAfter=no_wait_after,
  3524. strict=strict,
  3525. trial=trial,
  3526. )
  3527. )
  3528. async def tap(
  3529. self,
  3530. selector: str,
  3531. *,
  3532. modifiers: typing.Optional[
  3533. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  3534. ] = None,
  3535. position: typing.Optional[Position] = None,
  3536. timeout: typing.Optional[float] = None,
  3537. force: typing.Optional[bool] = None,
  3538. no_wait_after: typing.Optional[bool] = None,
  3539. strict: typing.Optional[bool] = None,
  3540. trial: typing.Optional[bool] = None,
  3541. ) -> None:
  3542. """Frame.tap
  3543. This method taps an element matching `selector` by performing the following steps:
  3544. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  3545. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  3546. the element is detached during the checks, the whole action is retried.
  3547. 1. Scroll the element into view if needed.
  3548. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  3549. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  3550. Passing zero timeout disables this.
  3551. **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
  3552. Parameters
  3553. ----------
  3554. selector : str
  3555. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3556. used.
  3557. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  3558. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  3559. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  3560. "Control" on Windows and Linux and to "Meta" on macOS.
  3561. position : Union[{x: float, y: float}, None]
  3562. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  3563. the element.
  3564. timeout : Union[float, None]
  3565. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3566. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3567. force : Union[bool, None]
  3568. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3569. no_wait_after : Union[bool, None]
  3570. This option has no effect.
  3571. Deprecated: This option has no effect.
  3572. strict : Union[bool, None]
  3573. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3574. element, the call throws an exception.
  3575. trial : Union[bool, None]
  3576. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  3577. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  3578. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  3579. are pressed.
  3580. """
  3581. return mapping.from_maybe_impl(
  3582. await self._impl_obj.tap(
  3583. selector=selector,
  3584. modifiers=mapping.to_impl(modifiers),
  3585. position=position,
  3586. timeout=timeout,
  3587. force=force,
  3588. noWaitAfter=no_wait_after,
  3589. strict=strict,
  3590. trial=trial,
  3591. )
  3592. )
  3593. async def fill(
  3594. self,
  3595. selector: str,
  3596. value: str,
  3597. *,
  3598. timeout: typing.Optional[float] = None,
  3599. no_wait_after: typing.Optional[bool] = None,
  3600. strict: typing.Optional[bool] = None,
  3601. force: typing.Optional[bool] = None,
  3602. ) -> None:
  3603. """Frame.fill
  3604. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
  3605. focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
  3606. to clear the input field.
  3607. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  3608. error. However, if the element is inside the `<label>` element that has an associated
  3609. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  3610. instead.
  3611. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  3612. Parameters
  3613. ----------
  3614. selector : str
  3615. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  3616. used.
  3617. value : str
  3618. Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
  3619. timeout : Union[float, None]
  3620. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  3621. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  3622. no_wait_after : Union[bool, None]
  3623. This option has no effect.
  3624. Deprecated: This option has no effect.
  3625. strict : Union[bool, None]
  3626. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  3627. element, the call throws an exception.
  3628. force : Union[bool, None]
  3629. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  3630. """
  3631. return mapping.from_maybe_impl(
  3632. await self._impl_obj.fill(
  3633. selector=selector,
  3634. value=value,
  3635. timeout=timeout,
  3636. noWaitAfter=no_wait_after,
  3637. strict=strict,
  3638. force=force,
  3639. )
  3640. )
  3641. def locator(
  3642. self,
  3643. selector: str,
  3644. *,
  3645. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3646. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3647. has: typing.Optional["Locator"] = None,
  3648. has_not: typing.Optional["Locator"] = None,
  3649. ) -> "Locator":
  3650. """Frame.locator
  3651. The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
  3652. to the element immediately before performing an action, so a series of actions on the same locator can in fact be
  3653. performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
  3654. [Learn more about locators](https://playwright.dev/python/docs/locators).
  3655. [Learn more about locators](https://playwright.dev/python/docs/locators).
  3656. Parameters
  3657. ----------
  3658. selector : str
  3659. A selector to use when resolving DOM element.
  3660. has_text : Union[Pattern[str], str, None]
  3661. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  3662. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  3663. `<article><div>Playwright</div></article>`.
  3664. has_not_text : Union[Pattern[str], str, None]
  3665. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  3666. When passed a [string], matching is case-insensitive and searches for a substring.
  3667. has : Union[Locator, None]
  3668. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  3669. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  3670. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  3671. the document root. For example, you can find `content` that has `div` in
  3672. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  3673. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  3674. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  3675. has_not : Union[Locator, None]
  3676. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  3677. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  3678. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  3679. Returns
  3680. -------
  3681. Locator
  3682. """
  3683. return mapping.from_impl(
  3684. self._impl_obj.locator(
  3685. selector=selector,
  3686. hasText=has_text,
  3687. hasNotText=has_not_text,
  3688. has=has._impl_obj if has else None,
  3689. hasNot=has_not._impl_obj if has_not else None,
  3690. )
  3691. )
  3692. def get_by_alt_text(
  3693. self,
  3694. text: typing.Union[str, typing.Pattern[str]],
  3695. *,
  3696. exact: typing.Optional[bool] = None,
  3697. ) -> "Locator":
  3698. """Frame.get_by_alt_text
  3699. Allows locating elements by their alt text.
  3700. **Usage**
  3701. For example, this method will find the image by alt text \"Playwright logo\":
  3702. ```html
  3703. <img alt='Playwright logo'>
  3704. ```
  3705. ```py
  3706. await page.get_by_alt_text(\"Playwright logo\").click()
  3707. ```
  3708. Parameters
  3709. ----------
  3710. text : Union[Pattern[str], str]
  3711. Text to locate the element for.
  3712. exact : Union[bool, None]
  3713. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3714. regular expression. Note that exact match still trims whitespace.
  3715. Returns
  3716. -------
  3717. Locator
  3718. """
  3719. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  3720. def get_by_label(
  3721. self,
  3722. text: typing.Union[str, typing.Pattern[str]],
  3723. *,
  3724. exact: typing.Optional[bool] = None,
  3725. ) -> "Locator":
  3726. """Frame.get_by_label
  3727. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  3728. `aria-label` attribute.
  3729. **Usage**
  3730. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  3731. ```html
  3732. <input aria-label=\"Username\">
  3733. <label for=\"password-input\">Password:</label>
  3734. <input id=\"password-input\">
  3735. ```
  3736. ```py
  3737. await page.get_by_label(\"Username\").fill(\"john\")
  3738. await page.get_by_label(\"Password\").fill(\"secret\")
  3739. ```
  3740. Parameters
  3741. ----------
  3742. text : Union[Pattern[str], str]
  3743. Text to locate the element for.
  3744. exact : Union[bool, None]
  3745. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3746. regular expression. Note that exact match still trims whitespace.
  3747. Returns
  3748. -------
  3749. Locator
  3750. """
  3751. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  3752. def get_by_placeholder(
  3753. self,
  3754. text: typing.Union[str, typing.Pattern[str]],
  3755. *,
  3756. exact: typing.Optional[bool] = None,
  3757. ) -> "Locator":
  3758. """Frame.get_by_placeholder
  3759. Allows locating input elements by the placeholder text.
  3760. **Usage**
  3761. For example, consider the following DOM structure.
  3762. ```html
  3763. <input type=\"email\" placeholder=\"name@example.com\" />
  3764. ```
  3765. You can fill the input after locating it by the placeholder text:
  3766. ```py
  3767. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  3768. ```
  3769. Parameters
  3770. ----------
  3771. text : Union[Pattern[str], str]
  3772. Text to locate the element for.
  3773. exact : Union[bool, None]
  3774. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  3775. regular expression. Note that exact match still trims whitespace.
  3776. Returns
  3777. -------
  3778. Locator
  3779. """
  3780. return mapping.from_impl(
  3781. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  3782. )
  3783. def get_by_role(
  3784. self,
  3785. role: Literal[
  3786. "alert",
  3787. "alertdialog",
  3788. "application",
  3789. "article",
  3790. "banner",
  3791. "blockquote",
  3792. "button",
  3793. "caption",
  3794. "cell",
  3795. "checkbox",
  3796. "code",
  3797. "columnheader",
  3798. "combobox",
  3799. "complementary",
  3800. "contentinfo",
  3801. "definition",
  3802. "deletion",
  3803. "dialog",
  3804. "directory",
  3805. "document",
  3806. "emphasis",
  3807. "feed",
  3808. "figure",
  3809. "form",
  3810. "generic",
  3811. "grid",
  3812. "gridcell",
  3813. "group",
  3814. "heading",
  3815. "img",
  3816. "insertion",
  3817. "link",
  3818. "list",
  3819. "listbox",
  3820. "listitem",
  3821. "log",
  3822. "main",
  3823. "marquee",
  3824. "math",
  3825. "menu",
  3826. "menubar",
  3827. "menuitem",
  3828. "menuitemcheckbox",
  3829. "menuitemradio",
  3830. "meter",
  3831. "navigation",
  3832. "none",
  3833. "note",
  3834. "option",
  3835. "paragraph",
  3836. "presentation",
  3837. "progressbar",
  3838. "radio",
  3839. "radiogroup",
  3840. "region",
  3841. "row",
  3842. "rowgroup",
  3843. "rowheader",
  3844. "scrollbar",
  3845. "search",
  3846. "searchbox",
  3847. "separator",
  3848. "slider",
  3849. "spinbutton",
  3850. "status",
  3851. "strong",
  3852. "subscript",
  3853. "superscript",
  3854. "switch",
  3855. "tab",
  3856. "table",
  3857. "tablist",
  3858. "tabpanel",
  3859. "term",
  3860. "textbox",
  3861. "time",
  3862. "timer",
  3863. "toolbar",
  3864. "tooltip",
  3865. "tree",
  3866. "treegrid",
  3867. "treeitem",
  3868. ],
  3869. *,
  3870. checked: typing.Optional[bool] = None,
  3871. disabled: typing.Optional[bool] = None,
  3872. expanded: typing.Optional[bool] = None,
  3873. include_hidden: typing.Optional[bool] = None,
  3874. level: typing.Optional[int] = None,
  3875. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  3876. pressed: typing.Optional[bool] = None,
  3877. selected: typing.Optional[bool] = None,
  3878. exact: typing.Optional[bool] = None,
  3879. ) -> "Locator":
  3880. """Frame.get_by_role
  3881. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  3882. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  3883. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  3884. **Usage**
  3885. Consider the following DOM structure.
  3886. ```html
  3887. <h3>Sign up</h3>
  3888. <label>
  3889. <input type=\"checkbox\" /> Subscribe
  3890. </label>
  3891. <br/>
  3892. <button>Submit</button>
  3893. ```
  3894. You can locate each element by it's implicit role:
  3895. ```py
  3896. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  3897. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  3898. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  3899. ```
  3900. **Details**
  3901. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  3902. about the ARIA guidelines.
  3903. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  3904. that is recognized by the role selector. You can find all the
  3905. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  3906. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  3907. Parameters
  3908. ----------
  3909. 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"]
  3910. Required aria role.
  3911. checked : Union[bool, None]
  3912. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  3913. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  3914. disabled : Union[bool, None]
  3915. An attribute that is usually set by `aria-disabled` or `disabled`.
  3916. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  3917. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  3918. expanded : Union[bool, None]
  3919. An attribute that is usually set by `aria-expanded`.
  3920. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  3921. include_hidden : Union[bool, None]
  3922. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  3923. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  3924. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  3925. level : Union[int, None]
  3926. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  3927. for `<h1>-<h6>` elements.
  3928. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  3929. name : Union[Pattern[str], str, None]
  3930. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  3931. case-insensitive and searches for a substring, use `exact` to control this behavior.
  3932. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  3933. pressed : Union[bool, None]
  3934. An attribute that is usually set by `aria-pressed`.
  3935. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  3936. selected : Union[bool, None]
  3937. An attribute that is usually set by `aria-selected`.
  3938. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  3939. exact : Union[bool, None]
  3940. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  3941. regular expression. Note that exact match still trims whitespace.
  3942. Returns
  3943. -------
  3944. Locator
  3945. """
  3946. return mapping.from_impl(
  3947. self._impl_obj.get_by_role(
  3948. role=role,
  3949. checked=checked,
  3950. disabled=disabled,
  3951. expanded=expanded,
  3952. includeHidden=include_hidden,
  3953. level=level,
  3954. name=name,
  3955. pressed=pressed,
  3956. selected=selected,
  3957. exact=exact,
  3958. )
  3959. )
  3960. def get_by_test_id(
  3961. self, test_id: typing.Union[str, typing.Pattern[str]]
  3962. ) -> "Locator":
  3963. """Frame.get_by_test_id
  3964. Locate element by the test id.
  3965. **Usage**
  3966. Consider the following DOM structure.
  3967. ```html
  3968. <button data-testid=\"directions\">Itinéraire</button>
  3969. ```
  3970. You can locate the element by it's test id:
  3971. ```py
  3972. await page.get_by_test_id(\"directions\").click()
  3973. ```
  3974. **Details**
  3975. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  3976. configure a different test id attribute if necessary.
  3977. Parameters
  3978. ----------
  3979. test_id : Union[Pattern[str], str]
  3980. Id to locate the element by.
  3981. Returns
  3982. -------
  3983. Locator
  3984. """
  3985. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  3986. def get_by_text(
  3987. self,
  3988. text: typing.Union[str, typing.Pattern[str]],
  3989. *,
  3990. exact: typing.Optional[bool] = None,
  3991. ) -> "Locator":
  3992. """Frame.get_by_text
  3993. Allows locating elements that contain given text.
  3994. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  3995. filter by the text content.
  3996. **Usage**
  3997. Consider the following DOM structure:
  3998. ```html
  3999. <div>Hello <span>world</span></div>
  4000. <div>Hello</div>
  4001. ```
  4002. You can locate by text substring, exact string, or a regular expression:
  4003. ```py
  4004. # Matches <span>
  4005. page.get_by_text(\"world\")
  4006. # Matches first <div>
  4007. page.get_by_text(\"Hello world\")
  4008. # Matches second <div>
  4009. page.get_by_text(\"Hello\", exact=True)
  4010. # Matches both <div>s
  4011. page.get_by_text(re.compile(\"Hello\"))
  4012. # Matches second <div>
  4013. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  4014. ```
  4015. **Details**
  4016. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  4017. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  4018. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  4019. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  4020. Parameters
  4021. ----------
  4022. text : Union[Pattern[str], str]
  4023. Text to locate the element for.
  4024. exact : Union[bool, None]
  4025. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4026. regular expression. Note that exact match still trims whitespace.
  4027. Returns
  4028. -------
  4029. Locator
  4030. """
  4031. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  4032. def get_by_title(
  4033. self,
  4034. text: typing.Union[str, typing.Pattern[str]],
  4035. *,
  4036. exact: typing.Optional[bool] = None,
  4037. ) -> "Locator":
  4038. """Frame.get_by_title
  4039. Allows locating elements by their title attribute.
  4040. **Usage**
  4041. Consider the following DOM structure.
  4042. ```html
  4043. <span title='Issues count'>25 issues</span>
  4044. ```
  4045. You can check the issues count after locating it by the title text:
  4046. ```py
  4047. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  4048. ```
  4049. Parameters
  4050. ----------
  4051. text : Union[Pattern[str], str]
  4052. Text to locate the element for.
  4053. exact : Union[bool, None]
  4054. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4055. regular expression. Note that exact match still trims whitespace.
  4056. Returns
  4057. -------
  4058. Locator
  4059. """
  4060. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  4061. def frame_locator(self, selector: str) -> "FrameLocator":
  4062. """Frame.frame_locator
  4063. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  4064. in that iframe.
  4065. **Usage**
  4066. Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
  4067. id=\"my-frame\">`:
  4068. ```py
  4069. locator = frame.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
  4070. await locator.click()
  4071. ```
  4072. Parameters
  4073. ----------
  4074. selector : str
  4075. A selector to use when resolving DOM element.
  4076. Returns
  4077. -------
  4078. FrameLocator
  4079. """
  4080. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  4081. async def focus(
  4082. self,
  4083. selector: str,
  4084. *,
  4085. strict: typing.Optional[bool] = None,
  4086. timeout: typing.Optional[float] = None,
  4087. ) -> None:
  4088. """Frame.focus
  4089. This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
  4090. method waits until a matching element appears in the DOM.
  4091. Parameters
  4092. ----------
  4093. selector : str
  4094. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4095. used.
  4096. strict : Union[bool, None]
  4097. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4098. element, the call throws an exception.
  4099. timeout : Union[float, None]
  4100. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4101. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4102. """
  4103. return mapping.from_maybe_impl(
  4104. await self._impl_obj.focus(
  4105. selector=selector, strict=strict, timeout=timeout
  4106. )
  4107. )
  4108. async def text_content(
  4109. self,
  4110. selector: str,
  4111. *,
  4112. strict: typing.Optional[bool] = None,
  4113. timeout: typing.Optional[float] = None,
  4114. ) -> typing.Optional[str]:
  4115. """Frame.text_content
  4116. Returns `element.textContent`.
  4117. Parameters
  4118. ----------
  4119. selector : str
  4120. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4121. used.
  4122. strict : Union[bool, None]
  4123. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4124. element, the call throws an exception.
  4125. timeout : Union[float, None]
  4126. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4127. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4128. Returns
  4129. -------
  4130. Union[str, None]
  4131. """
  4132. return mapping.from_maybe_impl(
  4133. await self._impl_obj.text_content(
  4134. selector=selector, strict=strict, timeout=timeout
  4135. )
  4136. )
  4137. async def inner_text(
  4138. self,
  4139. selector: str,
  4140. *,
  4141. strict: typing.Optional[bool] = None,
  4142. timeout: typing.Optional[float] = None,
  4143. ) -> str:
  4144. """Frame.inner_text
  4145. Returns `element.innerText`.
  4146. Parameters
  4147. ----------
  4148. selector : str
  4149. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4150. used.
  4151. strict : Union[bool, None]
  4152. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4153. element, the call throws an exception.
  4154. timeout : Union[float, None]
  4155. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4156. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4157. Returns
  4158. -------
  4159. str
  4160. """
  4161. return mapping.from_maybe_impl(
  4162. await self._impl_obj.inner_text(
  4163. selector=selector, strict=strict, timeout=timeout
  4164. )
  4165. )
  4166. async def inner_html(
  4167. self,
  4168. selector: str,
  4169. *,
  4170. strict: typing.Optional[bool] = None,
  4171. timeout: typing.Optional[float] = None,
  4172. ) -> str:
  4173. """Frame.inner_html
  4174. Returns `element.innerHTML`.
  4175. Parameters
  4176. ----------
  4177. selector : str
  4178. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4179. used.
  4180. strict : Union[bool, None]
  4181. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4182. element, the call throws an exception.
  4183. timeout : Union[float, None]
  4184. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4185. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4186. Returns
  4187. -------
  4188. str
  4189. """
  4190. return mapping.from_maybe_impl(
  4191. await self._impl_obj.inner_html(
  4192. selector=selector, strict=strict, timeout=timeout
  4193. )
  4194. )
  4195. async def get_attribute(
  4196. self,
  4197. selector: str,
  4198. name: str,
  4199. *,
  4200. strict: typing.Optional[bool] = None,
  4201. timeout: typing.Optional[float] = None,
  4202. ) -> typing.Optional[str]:
  4203. """Frame.get_attribute
  4204. Returns element attribute value.
  4205. Parameters
  4206. ----------
  4207. selector : str
  4208. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4209. used.
  4210. name : str
  4211. Attribute name to get the value for.
  4212. strict : Union[bool, None]
  4213. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4214. element, the call throws an exception.
  4215. timeout : Union[float, None]
  4216. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4217. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4218. Returns
  4219. -------
  4220. Union[str, None]
  4221. """
  4222. return mapping.from_maybe_impl(
  4223. await self._impl_obj.get_attribute(
  4224. selector=selector, name=name, strict=strict, timeout=timeout
  4225. )
  4226. )
  4227. async def hover(
  4228. self,
  4229. selector: str,
  4230. *,
  4231. modifiers: typing.Optional[
  4232. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  4233. ] = None,
  4234. position: typing.Optional[Position] = None,
  4235. timeout: typing.Optional[float] = None,
  4236. no_wait_after: typing.Optional[bool] = None,
  4237. force: typing.Optional[bool] = None,
  4238. strict: typing.Optional[bool] = None,
  4239. trial: typing.Optional[bool] = None,
  4240. ) -> None:
  4241. """Frame.hover
  4242. This method hovers over an element matching `selector` by performing the following steps:
  4243. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4244. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4245. the element is detached during the checks, the whole action is retried.
  4246. 1. Scroll the element into view if needed.
  4247. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  4248. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4249. Passing zero timeout disables this.
  4250. Parameters
  4251. ----------
  4252. selector : str
  4253. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4254. used.
  4255. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  4256. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  4257. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  4258. "Control" on Windows and Linux and to "Meta" on macOS.
  4259. position : Union[{x: float, y: float}, None]
  4260. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4261. the element.
  4262. timeout : Union[float, None]
  4263. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4264. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4265. no_wait_after : Union[bool, None]
  4266. This option has no effect.
  4267. Deprecated: This option has no effect.
  4268. force : Union[bool, None]
  4269. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4270. strict : Union[bool, None]
  4271. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4272. element, the call throws an exception.
  4273. trial : Union[bool, None]
  4274. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4275. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  4276. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  4277. are pressed.
  4278. """
  4279. return mapping.from_maybe_impl(
  4280. await self._impl_obj.hover(
  4281. selector=selector,
  4282. modifiers=mapping.to_impl(modifiers),
  4283. position=position,
  4284. timeout=timeout,
  4285. noWaitAfter=no_wait_after,
  4286. force=force,
  4287. strict=strict,
  4288. trial=trial,
  4289. )
  4290. )
  4291. async def drag_and_drop(
  4292. self,
  4293. source: str,
  4294. target: str,
  4295. *,
  4296. source_position: typing.Optional[Position] = None,
  4297. target_position: typing.Optional[Position] = None,
  4298. force: typing.Optional[bool] = None,
  4299. no_wait_after: typing.Optional[bool] = None,
  4300. strict: typing.Optional[bool] = None,
  4301. timeout: typing.Optional[float] = None,
  4302. trial: typing.Optional[bool] = None,
  4303. steps: typing.Optional[int] = None,
  4304. ) -> None:
  4305. """Frame.drag_and_drop
  4306. Parameters
  4307. ----------
  4308. source : str
  4309. A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
  4310. be used.
  4311. target : str
  4312. A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
  4313. will be used.
  4314. source_position : Union[{x: float, y: float}, None]
  4315. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  4316. specified, some visible point of the element is used.
  4317. target_position : Union[{x: float, y: float}, None]
  4318. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  4319. specified, some visible point of the element is used.
  4320. force : Union[bool, None]
  4321. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4322. no_wait_after : Union[bool, None]
  4323. This option has no effect.
  4324. Deprecated: This option has no effect.
  4325. strict : Union[bool, None]
  4326. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4327. element, the call throws an exception.
  4328. timeout : Union[float, None]
  4329. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4330. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4331. trial : Union[bool, None]
  4332. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4333. to `false`. Useful to wait until the element is ready for the action without performing it.
  4334. steps : Union[int, None]
  4335. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  4336. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  4337. """
  4338. return mapping.from_maybe_impl(
  4339. await self._impl_obj.drag_and_drop(
  4340. source=source,
  4341. target=target,
  4342. sourcePosition=source_position,
  4343. targetPosition=target_position,
  4344. force=force,
  4345. noWaitAfter=no_wait_after,
  4346. strict=strict,
  4347. timeout=timeout,
  4348. trial=trial,
  4349. steps=steps,
  4350. )
  4351. )
  4352. async def select_option(
  4353. self,
  4354. selector: str,
  4355. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  4356. *,
  4357. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  4358. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  4359. element: typing.Optional[
  4360. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  4361. ] = None,
  4362. timeout: typing.Optional[float] = None,
  4363. no_wait_after: typing.Optional[bool] = None,
  4364. strict: typing.Optional[bool] = None,
  4365. force: typing.Optional[bool] = None,
  4366. ) -> typing.List[str]:
  4367. """Frame.select_option
  4368. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
  4369. until all specified options are present in the `<select>` element and selects these options.
  4370. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  4371. the `<label>` element that has an associated
  4372. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  4373. instead.
  4374. Returns the array of option values that have been successfully selected.
  4375. Triggers a `change` and `input` event once all the provided options have been selected.
  4376. **Usage**
  4377. ```py
  4378. # Single selection matching the value or label
  4379. await frame.select_option(\"select#colors\", \"blue\")
  4380. # single selection matching the label
  4381. await frame.select_option(\"select#colors\", label=\"blue\")
  4382. # multiple selection
  4383. await frame.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
  4384. ```
  4385. Parameters
  4386. ----------
  4387. selector : str
  4388. A selector to query for.
  4389. value : Union[Sequence[str], str, None]
  4390. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  4391. otherwise only the first option matching one of the passed options is selected. Optional.
  4392. index : Union[Sequence[int], int, None]
  4393. Options to select by index. Optional.
  4394. label : Union[Sequence[str], str, None]
  4395. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  4396. otherwise only the first option matching one of the passed options is selected. Optional.
  4397. element : Union[ElementHandle, Sequence[ElementHandle], None]
  4398. Option elements to select. Optional.
  4399. timeout : Union[float, None]
  4400. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4401. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4402. no_wait_after : Union[bool, None]
  4403. This option has no effect.
  4404. Deprecated: This option has no effect.
  4405. strict : Union[bool, None]
  4406. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4407. element, the call throws an exception.
  4408. force : Union[bool, None]
  4409. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4410. Returns
  4411. -------
  4412. List[str]
  4413. """
  4414. return mapping.from_maybe_impl(
  4415. await self._impl_obj.select_option(
  4416. selector=selector,
  4417. value=mapping.to_impl(value),
  4418. index=mapping.to_impl(index),
  4419. label=mapping.to_impl(label),
  4420. element=mapping.to_impl(element),
  4421. timeout=timeout,
  4422. noWaitAfter=no_wait_after,
  4423. strict=strict,
  4424. force=force,
  4425. )
  4426. )
  4427. async def input_value(
  4428. self,
  4429. selector: str,
  4430. *,
  4431. strict: typing.Optional[bool] = None,
  4432. timeout: typing.Optional[float] = None,
  4433. ) -> str:
  4434. """Frame.input_value
  4435. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  4436. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  4437. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  4438. control.
  4439. Parameters
  4440. ----------
  4441. selector : str
  4442. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4443. used.
  4444. strict : Union[bool, None]
  4445. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4446. element, the call throws an exception.
  4447. timeout : Union[float, None]
  4448. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4449. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4450. Returns
  4451. -------
  4452. str
  4453. """
  4454. return mapping.from_maybe_impl(
  4455. await self._impl_obj.input_value(
  4456. selector=selector, strict=strict, timeout=timeout
  4457. )
  4458. )
  4459. async def set_input_files(
  4460. self,
  4461. selector: str,
  4462. files: typing.Union[
  4463. str,
  4464. pathlib.Path,
  4465. FilePayload,
  4466. typing.Sequence[typing.Union[str, pathlib.Path]],
  4467. typing.Sequence[FilePayload],
  4468. ],
  4469. *,
  4470. strict: typing.Optional[bool] = None,
  4471. timeout: typing.Optional[float] = None,
  4472. no_wait_after: typing.Optional[bool] = None,
  4473. ) -> None:
  4474. """Frame.set_input_files
  4475. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  4476. they are resolved relative to the current working directory. For empty array, clears the selected files.
  4477. This method expects `selector` to point to an
  4478. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  4479. the `<label>` element that has an associated
  4480. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  4481. Parameters
  4482. ----------
  4483. selector : str
  4484. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4485. used.
  4486. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  4487. strict : Union[bool, None]
  4488. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4489. element, the call throws an exception.
  4490. timeout : Union[float, None]
  4491. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4492. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4493. no_wait_after : Union[bool, None]
  4494. This option has no effect.
  4495. Deprecated: This option has no effect.
  4496. """
  4497. return mapping.from_maybe_impl(
  4498. await self._impl_obj.set_input_files(
  4499. selector=selector,
  4500. files=mapping.to_impl(files),
  4501. strict=strict,
  4502. timeout=timeout,
  4503. noWaitAfter=no_wait_after,
  4504. )
  4505. )
  4506. async def type(
  4507. self,
  4508. selector: str,
  4509. text: str,
  4510. *,
  4511. delay: typing.Optional[float] = None,
  4512. strict: typing.Optional[bool] = None,
  4513. timeout: typing.Optional[float] = None,
  4514. no_wait_after: typing.Optional[bool] = None,
  4515. ) -> None:
  4516. """Frame.type
  4517. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used
  4518. to send fine-grained keyboard events. To fill values in form fields, use `frame.fill()`.
  4519. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  4520. **Usage**
  4521. Parameters
  4522. ----------
  4523. selector : str
  4524. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4525. used.
  4526. text : str
  4527. A text to type into a focused element.
  4528. delay : Union[float, None]
  4529. Time to wait between key presses in milliseconds. Defaults to 0.
  4530. strict : Union[bool, None]
  4531. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4532. element, the call throws an exception.
  4533. timeout : Union[float, None]
  4534. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4535. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4536. no_wait_after : Union[bool, None]
  4537. This option has no effect.
  4538. Deprecated: This option has no effect.
  4539. """
  4540. return mapping.from_maybe_impl(
  4541. await self._impl_obj.type(
  4542. selector=selector,
  4543. text=text,
  4544. delay=delay,
  4545. strict=strict,
  4546. timeout=timeout,
  4547. noWaitAfter=no_wait_after,
  4548. )
  4549. )
  4550. async def press(
  4551. self,
  4552. selector: str,
  4553. key: str,
  4554. *,
  4555. delay: typing.Optional[float] = None,
  4556. strict: typing.Optional[bool] = None,
  4557. timeout: typing.Optional[float] = None,
  4558. no_wait_after: typing.Optional[bool] = None,
  4559. ) -> None:
  4560. """Frame.press
  4561. `key` can specify the intended
  4562. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  4563. to generate the text for. A superset of the `key` values can be found
  4564. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  4565. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  4566. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  4567. etc.
  4568. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  4569. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  4570. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  4571. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  4572. texts.
  4573. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  4574. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  4575. Parameters
  4576. ----------
  4577. selector : str
  4578. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4579. used.
  4580. key : str
  4581. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  4582. delay : Union[float, None]
  4583. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  4584. strict : Union[bool, None]
  4585. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4586. element, the call throws an exception.
  4587. timeout : Union[float, None]
  4588. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4589. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4590. no_wait_after : Union[bool, None]
  4591. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  4592. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  4593. navigating to inaccessible pages. Defaults to `false`.
  4594. Deprecated: This option will default to `true` in the future.
  4595. """
  4596. return mapping.from_maybe_impl(
  4597. await self._impl_obj.press(
  4598. selector=selector,
  4599. key=key,
  4600. delay=delay,
  4601. strict=strict,
  4602. timeout=timeout,
  4603. noWaitAfter=no_wait_after,
  4604. )
  4605. )
  4606. async def check(
  4607. self,
  4608. selector: str,
  4609. *,
  4610. position: typing.Optional[Position] = None,
  4611. timeout: typing.Optional[float] = None,
  4612. force: typing.Optional[bool] = None,
  4613. no_wait_after: typing.Optional[bool] = None,
  4614. strict: typing.Optional[bool] = None,
  4615. trial: typing.Optional[bool] = None,
  4616. ) -> None:
  4617. """Frame.check
  4618. This method checks an element matching `selector` by performing the following steps:
  4619. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4620. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  4621. already checked, this method returns immediately.
  4622. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4623. the element is detached during the checks, the whole action is retried.
  4624. 1. Scroll the element into view if needed.
  4625. 1. Use `page.mouse` to click in the center of the element.
  4626. 1. Ensure that the element is now checked. If not, this method throws.
  4627. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4628. Passing zero timeout disables this.
  4629. Parameters
  4630. ----------
  4631. selector : str
  4632. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4633. used.
  4634. position : Union[{x: float, y: float}, None]
  4635. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4636. the element.
  4637. timeout : Union[float, None]
  4638. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4639. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4640. force : Union[bool, None]
  4641. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4642. no_wait_after : Union[bool, None]
  4643. This option has no effect.
  4644. Deprecated: This option has no effect.
  4645. strict : Union[bool, None]
  4646. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4647. element, the call throws an exception.
  4648. trial : Union[bool, None]
  4649. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4650. to `false`. Useful to wait until the element is ready for the action without performing it.
  4651. """
  4652. return mapping.from_maybe_impl(
  4653. await self._impl_obj.check(
  4654. selector=selector,
  4655. position=position,
  4656. timeout=timeout,
  4657. force=force,
  4658. noWaitAfter=no_wait_after,
  4659. strict=strict,
  4660. trial=trial,
  4661. )
  4662. )
  4663. async def uncheck(
  4664. self,
  4665. selector: str,
  4666. *,
  4667. position: typing.Optional[Position] = None,
  4668. timeout: typing.Optional[float] = None,
  4669. force: typing.Optional[bool] = None,
  4670. no_wait_after: typing.Optional[bool] = None,
  4671. strict: typing.Optional[bool] = None,
  4672. trial: typing.Optional[bool] = None,
  4673. ) -> None:
  4674. """Frame.uncheck
  4675. This method checks an element matching `selector` by performing the following steps:
  4676. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4677. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  4678. already unchecked, this method returns immediately.
  4679. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4680. the element is detached during the checks, the whole action is retried.
  4681. 1. Scroll the element into view if needed.
  4682. 1. Use `page.mouse` to click in the center of the element.
  4683. 1. Ensure that the element is now unchecked. If not, this method throws.
  4684. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4685. Passing zero timeout disables this.
  4686. Parameters
  4687. ----------
  4688. selector : str
  4689. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4690. used.
  4691. position : Union[{x: float, y: float}, None]
  4692. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4693. the element.
  4694. timeout : Union[float, None]
  4695. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4696. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4697. force : Union[bool, None]
  4698. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4699. no_wait_after : Union[bool, None]
  4700. This option has no effect.
  4701. Deprecated: This option has no effect.
  4702. strict : Union[bool, None]
  4703. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4704. element, the call throws an exception.
  4705. trial : Union[bool, None]
  4706. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4707. to `false`. Useful to wait until the element is ready for the action without performing it.
  4708. """
  4709. return mapping.from_maybe_impl(
  4710. await self._impl_obj.uncheck(
  4711. selector=selector,
  4712. position=position,
  4713. timeout=timeout,
  4714. force=force,
  4715. noWaitAfter=no_wait_after,
  4716. strict=strict,
  4717. trial=trial,
  4718. )
  4719. )
  4720. async def wait_for_timeout(self, timeout: float) -> None:
  4721. """Frame.wait_for_timeout
  4722. Waits for the given `timeout` in milliseconds.
  4723. Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
  4724. to be flaky. Use signals such as network events, selectors becoming visible and others instead.
  4725. Parameters
  4726. ----------
  4727. timeout : float
  4728. A timeout to wait for
  4729. """
  4730. return mapping.from_maybe_impl(
  4731. await self._impl_obj.wait_for_timeout(timeout=timeout)
  4732. )
  4733. async def wait_for_function(
  4734. self,
  4735. expression: str,
  4736. *,
  4737. arg: typing.Optional[typing.Any] = None,
  4738. timeout: typing.Optional[float] = None,
  4739. polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
  4740. ) -> "JSHandle":
  4741. """Frame.wait_for_function
  4742. Returns when the `expression` returns a truthy value, returns that value.
  4743. **Usage**
  4744. The `frame.wait_for_function()` can be used to observe viewport size change:
  4745. ```py
  4746. import asyncio
  4747. from playwright.async_api import async_playwright, Playwright
  4748. async def run(playwright: Playwright):
  4749. webkit = playwright.webkit
  4750. browser = await webkit.launch()
  4751. page = await browser.new_page()
  4752. await page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
  4753. await page.main_frame.wait_for_function(\"() => window.x > 0\")
  4754. await browser.close()
  4755. async def main():
  4756. async with async_playwright() as playwright:
  4757. await run(playwright)
  4758. asyncio.run(main())
  4759. ```
  4760. To pass an argument to the predicate of `frame.waitForFunction` function:
  4761. ```py
  4762. selector = \".foo\"
  4763. await frame.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
  4764. ```
  4765. Parameters
  4766. ----------
  4767. expression : str
  4768. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  4769. function is automatically invoked.
  4770. arg : Union[Any, None]
  4771. Optional argument to pass to `expression`.
  4772. timeout : Union[float, None]
  4773. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  4774. default value can be changed by using the `browser_context.set_default_timeout()` or
  4775. `page.set_default_timeout()` methods.
  4776. polling : Union["raf", float, None]
  4777. If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
  4778. is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
  4779. `raf`.
  4780. Returns
  4781. -------
  4782. JSHandle
  4783. """
  4784. return mapping.from_impl(
  4785. await self._impl_obj.wait_for_function(
  4786. expression=expression,
  4787. arg=mapping.to_impl(arg),
  4788. timeout=timeout,
  4789. polling=polling,
  4790. )
  4791. )
  4792. async def title(self) -> str:
  4793. """Frame.title
  4794. Returns the page title.
  4795. Returns
  4796. -------
  4797. str
  4798. """
  4799. return mapping.from_maybe_impl(await self._impl_obj.title())
  4800. async def set_checked(
  4801. self,
  4802. selector: str,
  4803. checked: bool,
  4804. *,
  4805. position: typing.Optional[Position] = None,
  4806. timeout: typing.Optional[float] = None,
  4807. force: typing.Optional[bool] = None,
  4808. no_wait_after: typing.Optional[bool] = None,
  4809. strict: typing.Optional[bool] = None,
  4810. trial: typing.Optional[bool] = None,
  4811. ) -> None:
  4812. """Frame.set_checked
  4813. This method checks or unchecks an element matching `selector` by performing the following steps:
  4814. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  4815. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  4816. 1. If the element already has the right checked state, this method returns immediately.
  4817. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  4818. the element is detached during the checks, the whole action is retried.
  4819. 1. Scroll the element into view if needed.
  4820. 1. Use `page.mouse` to click in the center of the element.
  4821. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  4822. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  4823. Passing zero timeout disables this.
  4824. Parameters
  4825. ----------
  4826. selector : str
  4827. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  4828. used.
  4829. checked : bool
  4830. Whether to check or uncheck the checkbox.
  4831. position : Union[{x: float, y: float}, None]
  4832. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  4833. the element.
  4834. timeout : Union[float, None]
  4835. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  4836. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  4837. force : Union[bool, None]
  4838. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  4839. no_wait_after : Union[bool, None]
  4840. This option has no effect.
  4841. Deprecated: This option has no effect.
  4842. strict : Union[bool, None]
  4843. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  4844. element, the call throws an exception.
  4845. trial : Union[bool, None]
  4846. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  4847. to `false`. Useful to wait until the element is ready for the action without performing it.
  4848. """
  4849. return mapping.from_maybe_impl(
  4850. await self._impl_obj.set_checked(
  4851. selector=selector,
  4852. checked=checked,
  4853. position=position,
  4854. timeout=timeout,
  4855. force=force,
  4856. noWaitAfter=no_wait_after,
  4857. strict=strict,
  4858. trial=trial,
  4859. )
  4860. )
  4861. mapping.register(FrameImpl, Frame)
  4862. class FrameLocator(AsyncBase):
  4863. @property
  4864. def first(self) -> "FrameLocator":
  4865. """FrameLocator.first
  4866. Returns locator to the first matching frame.
  4867. Returns
  4868. -------
  4869. FrameLocator
  4870. """
  4871. return mapping.from_impl(self._impl_obj.first)
  4872. @property
  4873. def last(self) -> "FrameLocator":
  4874. """FrameLocator.last
  4875. Returns locator to the last matching frame.
  4876. Returns
  4877. -------
  4878. FrameLocator
  4879. """
  4880. return mapping.from_impl(self._impl_obj.last)
  4881. @property
  4882. def owner(self) -> "Locator":
  4883. """FrameLocator.owner
  4884. Returns a `Locator` object pointing to the same `iframe` as this frame locator.
  4885. Useful when you have a `FrameLocator` object obtained somewhere, and later on would like to interact with the
  4886. `iframe` element.
  4887. For a reverse operation, use `locator.content_frame()`.
  4888. **Usage**
  4889. ```py
  4890. frame_locator = page.locator(\"iframe[name=\\\"embedded\\\"]\").content_frame
  4891. # ...
  4892. locator = frame_locator.owner
  4893. await expect(locator).to_be_visible()
  4894. ```
  4895. Returns
  4896. -------
  4897. Locator
  4898. """
  4899. return mapping.from_impl(self._impl_obj.owner)
  4900. def locator(
  4901. self,
  4902. selector_or_locator: typing.Union["Locator", str],
  4903. *,
  4904. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  4905. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  4906. has: typing.Optional["Locator"] = None,
  4907. has_not: typing.Optional["Locator"] = None,
  4908. ) -> "Locator":
  4909. """FrameLocator.locator
  4910. The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
  4911. options, similar to `locator.filter()` method.
  4912. [Learn more about locators](https://playwright.dev/python/docs/locators).
  4913. Parameters
  4914. ----------
  4915. selector_or_locator : Union[Locator, str]
  4916. A selector or locator to use when resolving DOM element.
  4917. has_text : Union[Pattern[str], str, None]
  4918. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  4919. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  4920. `<article><div>Playwright</div></article>`.
  4921. has_not_text : Union[Pattern[str], str, None]
  4922. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  4923. When passed a [string], matching is case-insensitive and searches for a substring.
  4924. has : Union[Locator, None]
  4925. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  4926. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  4927. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  4928. the document root. For example, you can find `content` that has `div` in
  4929. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  4930. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  4931. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  4932. has_not : Union[Locator, None]
  4933. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  4934. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  4935. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  4936. Returns
  4937. -------
  4938. Locator
  4939. """
  4940. return mapping.from_impl(
  4941. self._impl_obj.locator(
  4942. selectorOrLocator=selector_or_locator,
  4943. hasText=has_text,
  4944. hasNotText=has_not_text,
  4945. has=has._impl_obj if has else None,
  4946. hasNot=has_not._impl_obj if has_not else None,
  4947. )
  4948. )
  4949. def get_by_alt_text(
  4950. self,
  4951. text: typing.Union[str, typing.Pattern[str]],
  4952. *,
  4953. exact: typing.Optional[bool] = None,
  4954. ) -> "Locator":
  4955. """FrameLocator.get_by_alt_text
  4956. Allows locating elements by their alt text.
  4957. **Usage**
  4958. For example, this method will find the image by alt text \"Playwright logo\":
  4959. ```html
  4960. <img alt='Playwright logo'>
  4961. ```
  4962. ```py
  4963. await page.get_by_alt_text(\"Playwright logo\").click()
  4964. ```
  4965. Parameters
  4966. ----------
  4967. text : Union[Pattern[str], str]
  4968. Text to locate the element for.
  4969. exact : Union[bool, None]
  4970. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  4971. regular expression. Note that exact match still trims whitespace.
  4972. Returns
  4973. -------
  4974. Locator
  4975. """
  4976. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  4977. def get_by_label(
  4978. self,
  4979. text: typing.Union[str, typing.Pattern[str]],
  4980. *,
  4981. exact: typing.Optional[bool] = None,
  4982. ) -> "Locator":
  4983. """FrameLocator.get_by_label
  4984. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  4985. `aria-label` attribute.
  4986. **Usage**
  4987. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  4988. ```html
  4989. <input aria-label=\"Username\">
  4990. <label for=\"password-input\">Password:</label>
  4991. <input id=\"password-input\">
  4992. ```
  4993. ```py
  4994. await page.get_by_label(\"Username\").fill(\"john\")
  4995. await page.get_by_label(\"Password\").fill(\"secret\")
  4996. ```
  4997. Parameters
  4998. ----------
  4999. text : Union[Pattern[str], str]
  5000. Text to locate the element for.
  5001. exact : Union[bool, None]
  5002. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5003. regular expression. Note that exact match still trims whitespace.
  5004. Returns
  5005. -------
  5006. Locator
  5007. """
  5008. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  5009. def get_by_placeholder(
  5010. self,
  5011. text: typing.Union[str, typing.Pattern[str]],
  5012. *,
  5013. exact: typing.Optional[bool] = None,
  5014. ) -> "Locator":
  5015. """FrameLocator.get_by_placeholder
  5016. Allows locating input elements by the placeholder text.
  5017. **Usage**
  5018. For example, consider the following DOM structure.
  5019. ```html
  5020. <input type=\"email\" placeholder=\"name@example.com\" />
  5021. ```
  5022. You can fill the input after locating it by the placeholder text:
  5023. ```py
  5024. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  5025. ```
  5026. Parameters
  5027. ----------
  5028. text : Union[Pattern[str], str]
  5029. Text to locate the element for.
  5030. exact : Union[bool, None]
  5031. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5032. regular expression. Note that exact match still trims whitespace.
  5033. Returns
  5034. -------
  5035. Locator
  5036. """
  5037. return mapping.from_impl(
  5038. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  5039. )
  5040. def get_by_role(
  5041. self,
  5042. role: Literal[
  5043. "alert",
  5044. "alertdialog",
  5045. "application",
  5046. "article",
  5047. "banner",
  5048. "blockquote",
  5049. "button",
  5050. "caption",
  5051. "cell",
  5052. "checkbox",
  5053. "code",
  5054. "columnheader",
  5055. "combobox",
  5056. "complementary",
  5057. "contentinfo",
  5058. "definition",
  5059. "deletion",
  5060. "dialog",
  5061. "directory",
  5062. "document",
  5063. "emphasis",
  5064. "feed",
  5065. "figure",
  5066. "form",
  5067. "generic",
  5068. "grid",
  5069. "gridcell",
  5070. "group",
  5071. "heading",
  5072. "img",
  5073. "insertion",
  5074. "link",
  5075. "list",
  5076. "listbox",
  5077. "listitem",
  5078. "log",
  5079. "main",
  5080. "marquee",
  5081. "math",
  5082. "menu",
  5083. "menubar",
  5084. "menuitem",
  5085. "menuitemcheckbox",
  5086. "menuitemradio",
  5087. "meter",
  5088. "navigation",
  5089. "none",
  5090. "note",
  5091. "option",
  5092. "paragraph",
  5093. "presentation",
  5094. "progressbar",
  5095. "radio",
  5096. "radiogroup",
  5097. "region",
  5098. "row",
  5099. "rowgroup",
  5100. "rowheader",
  5101. "scrollbar",
  5102. "search",
  5103. "searchbox",
  5104. "separator",
  5105. "slider",
  5106. "spinbutton",
  5107. "status",
  5108. "strong",
  5109. "subscript",
  5110. "superscript",
  5111. "switch",
  5112. "tab",
  5113. "table",
  5114. "tablist",
  5115. "tabpanel",
  5116. "term",
  5117. "textbox",
  5118. "time",
  5119. "timer",
  5120. "toolbar",
  5121. "tooltip",
  5122. "tree",
  5123. "treegrid",
  5124. "treeitem",
  5125. ],
  5126. *,
  5127. checked: typing.Optional[bool] = None,
  5128. disabled: typing.Optional[bool] = None,
  5129. expanded: typing.Optional[bool] = None,
  5130. include_hidden: typing.Optional[bool] = None,
  5131. level: typing.Optional[int] = None,
  5132. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  5133. pressed: typing.Optional[bool] = None,
  5134. selected: typing.Optional[bool] = None,
  5135. exact: typing.Optional[bool] = None,
  5136. ) -> "Locator":
  5137. """FrameLocator.get_by_role
  5138. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  5139. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  5140. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  5141. **Usage**
  5142. Consider the following DOM structure.
  5143. ```html
  5144. <h3>Sign up</h3>
  5145. <label>
  5146. <input type=\"checkbox\" /> Subscribe
  5147. </label>
  5148. <br/>
  5149. <button>Submit</button>
  5150. ```
  5151. You can locate each element by it's implicit role:
  5152. ```py
  5153. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  5154. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  5155. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  5156. ```
  5157. **Details**
  5158. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  5159. about the ARIA guidelines.
  5160. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  5161. that is recognized by the role selector. You can find all the
  5162. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  5163. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  5164. Parameters
  5165. ----------
  5166. 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"]
  5167. Required aria role.
  5168. checked : Union[bool, None]
  5169. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  5170. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  5171. disabled : Union[bool, None]
  5172. An attribute that is usually set by `aria-disabled` or `disabled`.
  5173. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  5174. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  5175. expanded : Union[bool, None]
  5176. An attribute that is usually set by `aria-expanded`.
  5177. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  5178. include_hidden : Union[bool, None]
  5179. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  5180. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  5181. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  5182. level : Union[int, None]
  5183. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  5184. for `<h1>-<h6>` elements.
  5185. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  5186. name : Union[Pattern[str], str, None]
  5187. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  5188. case-insensitive and searches for a substring, use `exact` to control this behavior.
  5189. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  5190. pressed : Union[bool, None]
  5191. An attribute that is usually set by `aria-pressed`.
  5192. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  5193. selected : Union[bool, None]
  5194. An attribute that is usually set by `aria-selected`.
  5195. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  5196. exact : Union[bool, None]
  5197. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  5198. regular expression. Note that exact match still trims whitespace.
  5199. Returns
  5200. -------
  5201. Locator
  5202. """
  5203. return mapping.from_impl(
  5204. self._impl_obj.get_by_role(
  5205. role=role,
  5206. checked=checked,
  5207. disabled=disabled,
  5208. expanded=expanded,
  5209. includeHidden=include_hidden,
  5210. level=level,
  5211. name=name,
  5212. pressed=pressed,
  5213. selected=selected,
  5214. exact=exact,
  5215. )
  5216. )
  5217. def get_by_test_id(
  5218. self, test_id: typing.Union[str, typing.Pattern[str]]
  5219. ) -> "Locator":
  5220. """FrameLocator.get_by_test_id
  5221. Locate element by the test id.
  5222. **Usage**
  5223. Consider the following DOM structure.
  5224. ```html
  5225. <button data-testid=\"directions\">Itinéraire</button>
  5226. ```
  5227. You can locate the element by it's test id:
  5228. ```py
  5229. await page.get_by_test_id(\"directions\").click()
  5230. ```
  5231. **Details**
  5232. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  5233. configure a different test id attribute if necessary.
  5234. Parameters
  5235. ----------
  5236. test_id : Union[Pattern[str], str]
  5237. Id to locate the element by.
  5238. Returns
  5239. -------
  5240. Locator
  5241. """
  5242. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  5243. def get_by_text(
  5244. self,
  5245. text: typing.Union[str, typing.Pattern[str]],
  5246. *,
  5247. exact: typing.Optional[bool] = None,
  5248. ) -> "Locator":
  5249. """FrameLocator.get_by_text
  5250. Allows locating elements that contain given text.
  5251. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  5252. filter by the text content.
  5253. **Usage**
  5254. Consider the following DOM structure:
  5255. ```html
  5256. <div>Hello <span>world</span></div>
  5257. <div>Hello</div>
  5258. ```
  5259. You can locate by text substring, exact string, or a regular expression:
  5260. ```py
  5261. # Matches <span>
  5262. page.get_by_text(\"world\")
  5263. # Matches first <div>
  5264. page.get_by_text(\"Hello world\")
  5265. # Matches second <div>
  5266. page.get_by_text(\"Hello\", exact=True)
  5267. # Matches both <div>s
  5268. page.get_by_text(re.compile(\"Hello\"))
  5269. # Matches second <div>
  5270. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  5271. ```
  5272. **Details**
  5273. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  5274. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  5275. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  5276. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  5277. Parameters
  5278. ----------
  5279. text : Union[Pattern[str], str]
  5280. Text to locate the element for.
  5281. exact : Union[bool, None]
  5282. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5283. regular expression. Note that exact match still trims whitespace.
  5284. Returns
  5285. -------
  5286. Locator
  5287. """
  5288. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  5289. def get_by_title(
  5290. self,
  5291. text: typing.Union[str, typing.Pattern[str]],
  5292. *,
  5293. exact: typing.Optional[bool] = None,
  5294. ) -> "Locator":
  5295. """FrameLocator.get_by_title
  5296. Allows locating elements by their title attribute.
  5297. **Usage**
  5298. Consider the following DOM structure.
  5299. ```html
  5300. <span title='Issues count'>25 issues</span>
  5301. ```
  5302. You can check the issues count after locating it by the title text:
  5303. ```py
  5304. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  5305. ```
  5306. Parameters
  5307. ----------
  5308. text : Union[Pattern[str], str]
  5309. Text to locate the element for.
  5310. exact : Union[bool, None]
  5311. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  5312. regular expression. Note that exact match still trims whitespace.
  5313. Returns
  5314. -------
  5315. Locator
  5316. """
  5317. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  5318. def frame_locator(self, selector: str) -> "FrameLocator":
  5319. """FrameLocator.frame_locator
  5320. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  5321. in that iframe.
  5322. Parameters
  5323. ----------
  5324. selector : str
  5325. A selector to use when resolving DOM element.
  5326. Returns
  5327. -------
  5328. FrameLocator
  5329. """
  5330. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  5331. def nth(self, index: int) -> "FrameLocator":
  5332. """FrameLocator.nth
  5333. Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.
  5334. Parameters
  5335. ----------
  5336. index : int
  5337. Returns
  5338. -------
  5339. FrameLocator
  5340. """
  5341. return mapping.from_impl(self._impl_obj.nth(index=index))
  5342. mapping.register(FrameLocatorImpl, FrameLocator)
  5343. class Worker(AsyncBase):
  5344. @typing.overload
  5345. def on(
  5346. self,
  5347. event: Literal["close"],
  5348. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  5349. ) -> None:
  5350. """
  5351. Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
  5352. terminated."""
  5353. @typing.overload
  5354. def on(
  5355. self,
  5356. event: Literal["console"],
  5357. f: typing.Callable[
  5358. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  5359. ],
  5360. ) -> None:
  5361. """
  5362. Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
  5363. """
  5364. def on(
  5365. self,
  5366. event: str,
  5367. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  5368. ) -> None:
  5369. return super().on(event=event, f=f)
  5370. @typing.overload
  5371. def once(
  5372. self,
  5373. event: Literal["close"],
  5374. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  5375. ) -> None:
  5376. """
  5377. Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
  5378. terminated."""
  5379. @typing.overload
  5380. def once(
  5381. self,
  5382. event: Literal["console"],
  5383. f: typing.Callable[
  5384. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  5385. ],
  5386. ) -> None:
  5387. """
  5388. Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
  5389. """
  5390. def once(
  5391. self,
  5392. event: str,
  5393. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  5394. ) -> None:
  5395. return super().once(event=event, f=f)
  5396. @property
  5397. def url(self) -> str:
  5398. """Worker.url
  5399. Returns
  5400. -------
  5401. str
  5402. """
  5403. return mapping.from_maybe_impl(self._impl_obj.url)
  5404. async def evaluate(
  5405. self, expression: str, arg: typing.Optional[typing.Any] = None
  5406. ) -> typing.Any:
  5407. """Worker.evaluate
  5408. Returns the return value of `expression`.
  5409. If the function passed to the `worker.evaluate()` returns a [Promise], then `worker.evaluate()`
  5410. would wait for the promise to resolve and return its value.
  5411. If the function passed to the `worker.evaluate()` returns a non-[Serializable] value, then
  5412. `worker.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
  5413. are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  5414. Parameters
  5415. ----------
  5416. expression : str
  5417. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  5418. function is automatically invoked.
  5419. arg : Union[Any, None]
  5420. Optional argument to pass to `expression`.
  5421. Returns
  5422. -------
  5423. Any
  5424. """
  5425. return mapping.from_maybe_impl(
  5426. await self._impl_obj.evaluate(
  5427. expression=expression, arg=mapping.to_impl(arg)
  5428. )
  5429. )
  5430. async def evaluate_handle(
  5431. self, expression: str, arg: typing.Optional[typing.Any] = None
  5432. ) -> "JSHandle":
  5433. """Worker.evaluate_handle
  5434. Returns the return value of `expression` as a `JSHandle`.
  5435. The only difference between `worker.evaluate()` and `worker.evaluate_handle()` is that
  5436. `worker.evaluate_handle()` returns `JSHandle`.
  5437. If the function passed to the `worker.evaluate_handle()` returns a [Promise], then
  5438. `worker.evaluate_handle()` would wait for the promise to resolve and return its value.
  5439. Parameters
  5440. ----------
  5441. expression : str
  5442. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  5443. function is automatically invoked.
  5444. arg : Union[Any, None]
  5445. Optional argument to pass to `expression`.
  5446. Returns
  5447. -------
  5448. JSHandle
  5449. """
  5450. return mapping.from_impl(
  5451. await self._impl_obj.evaluate_handle(
  5452. expression=expression, arg=mapping.to_impl(arg)
  5453. )
  5454. )
  5455. def expect_event(
  5456. self,
  5457. event: str,
  5458. predicate: typing.Optional[typing.Callable] = None,
  5459. *,
  5460. timeout: typing.Optional[float] = None,
  5461. ) -> AsyncEventContextManager:
  5462. """Worker.expect_event
  5463. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  5464. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
  5465. **Usage**
  5466. ```py
  5467. async with worker.expect_event(\"console\") as event_info:
  5468. await worker.evaluate(\"console.log(42)\")
  5469. message = await event_info.value
  5470. ```
  5471. Parameters
  5472. ----------
  5473. event : str
  5474. Event name, same one typically passed into `*.on(event)`.
  5475. predicate : Union[Callable, None]
  5476. Receives the event data and resolves to truthy value when the waiting should resolve.
  5477. timeout : Union[float, None]
  5478. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  5479. default value can be changed by using the `browser_context.set_default_timeout()`.
  5480. Returns
  5481. -------
  5482. EventContextManager
  5483. """
  5484. return AsyncEventContextManager(
  5485. self._impl_obj.expect_event(
  5486. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  5487. ).future
  5488. )
  5489. mapping.register(WorkerImpl, Worker)
  5490. class Selectors(AsyncBase):
  5491. async def register(
  5492. self,
  5493. name: str,
  5494. script: typing.Optional[str] = None,
  5495. *,
  5496. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  5497. content_script: typing.Optional[bool] = None,
  5498. ) -> None:
  5499. """Selectors.register
  5500. Selectors must be registered before creating the page.
  5501. **Usage**
  5502. An example of registering selector engine that queries elements based on a tag name:
  5503. ```py
  5504. import asyncio
  5505. from playwright.async_api import async_playwright, Playwright
  5506. async def run(playwright: Playwright):
  5507. tag_selector = \"\"\"
  5508. {
  5509. // Returns the first element matching given selector in the root's subtree.
  5510. query(root, selector) {
  5511. return root.querySelector(selector);
  5512. },
  5513. // Returns all elements matching given selector in the root's subtree.
  5514. queryAll(root, selector) {
  5515. return Array.from(root.querySelectorAll(selector));
  5516. }
  5517. }\"\"\"
  5518. # Register the engine. Selectors will be prefixed with \"tag=\".
  5519. await playwright.selectors.register(\"tag\", tag_selector)
  5520. browser = await playwright.chromium.launch()
  5521. page = await browser.new_page()
  5522. await page.set_content('<div><button>Click me</button></div>')
  5523. # Use the selector prefixed with its name.
  5524. button = await page.query_selector('tag=button')
  5525. # Combine it with built-in locators.
  5526. await page.locator('tag=div').get_by_text('Click me').click()
  5527. # Can use it in any methods supporting selectors.
  5528. button_count = await page.locator('tag=button').count()
  5529. print(button_count)
  5530. await browser.close()
  5531. async def main():
  5532. async with async_playwright() as playwright:
  5533. await run(playwright)
  5534. asyncio.run(main())
  5535. ```
  5536. Parameters
  5537. ----------
  5538. name : str
  5539. Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only
  5540. contain `[a-zA-Z0-9_]` characters.
  5541. script : Union[str, None]
  5542. Raw script content.
  5543. path : Union[pathlib.Path, str, None]
  5544. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  5545. directory.
  5546. content_script : Union[bool, None]
  5547. Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same
  5548. DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content
  5549. script is not guaranteed when this engine is used together with other registered engines.
  5550. """
  5551. return mapping.from_maybe_impl(
  5552. await self._impl_obj.register(
  5553. name=name, script=script, path=path, contentScript=content_script
  5554. )
  5555. )
  5556. def set_test_id_attribute(self, attribute_name: str) -> None:
  5557. """Selectors.set_test_id_attribute
  5558. Defines custom attribute name to be used in `page.get_by_test_id()`. `data-testid` is used by default.
  5559. Parameters
  5560. ----------
  5561. attribute_name : str
  5562. Test id attribute name.
  5563. """
  5564. return mapping.from_maybe_impl(
  5565. self._impl_obj.set_test_id_attribute(attributeName=attribute_name)
  5566. )
  5567. mapping.register(SelectorsImpl, Selectors)
  5568. class Clock(AsyncBase):
  5569. async def install(
  5570. self,
  5571. *,
  5572. time: typing.Optional[typing.Union[float, str, datetime.datetime]] = None,
  5573. ) -> None:
  5574. """Clock.install
  5575. Install fake implementations for the following time-related functions:
  5576. - `Date`
  5577. - `setTimeout`
  5578. - `clearTimeout`
  5579. - `setInterval`
  5580. - `clearInterval`
  5581. - `requestAnimationFrame`
  5582. - `cancelAnimationFrame`
  5583. - `requestIdleCallback`
  5584. - `cancelIdleCallback`
  5585. - `performance`
  5586. Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,
  5587. and control the behavior of time-dependent functions. See `clock.run_for()` and
  5588. `clock.fast_forward()` for more information.
  5589. Parameters
  5590. ----------
  5591. time : Union[datetime.datetime, float, str, None]
  5592. Time to initialize with, current system time by default.
  5593. """
  5594. return mapping.from_maybe_impl(await self._impl_obj.install(time=time))
  5595. async def fast_forward(self, ticks: typing.Union[int, str]) -> None:
  5596. """Clock.fast_forward
  5597. Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user
  5598. closing the laptop lid for a while and reopening it later, after given time.
  5599. **Usage**
  5600. ```py
  5601. await page.clock.fast_forward(1000)
  5602. await page.clock.fast_forward(\"30:00\")
  5603. ```
  5604. Parameters
  5605. ----------
  5606. ticks : Union[int, str]
  5607. Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
  5608. "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
  5609. """
  5610. return mapping.from_maybe_impl(await self._impl_obj.fast_forward(ticks=ticks))
  5611. async def pause_at(self, time: typing.Union[float, str, datetime.datetime]) -> None:
  5612. """Clock.pause_at
  5613. Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired
  5614. unless `clock.run_for()`, `clock.fast_forward()`, `clock.pause_at()` or
  5615. `clock.resume()` is called.
  5616. Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it
  5617. at the specified time and pausing.
  5618. **Usage**
  5619. ```py
  5620. await page.clock.pause_at(datetime.datetime(2020, 2, 2))
  5621. await page.clock.pause_at(\"2020-02-02\")
  5622. ```
  5623. For best results, install the clock before navigating the page and set it to a time slightly before the intended
  5624. test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.
  5625. Once the page has fully loaded, you can safely use `clock.pause_at()` to pause the clock.
  5626. ```py
  5627. # Initialize clock with some time before the test time and let the page load
  5628. # naturally. `Date.now` will progress as the timers fire.
  5629. await page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0))
  5630. await page.goto(\"http://localhost:3333\")
  5631. await page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0))
  5632. ```
  5633. Parameters
  5634. ----------
  5635. time : Union[datetime.datetime, float, str]
  5636. Time to pause at.
  5637. """
  5638. return mapping.from_maybe_impl(await self._impl_obj.pause_at(time=time))
  5639. async def resume(self) -> None:
  5640. """Clock.resume
  5641. Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.
  5642. """
  5643. return mapping.from_maybe_impl(await self._impl_obj.resume())
  5644. async def run_for(self, ticks: typing.Union[int, str]) -> None:
  5645. """Clock.run_for
  5646. Advance the clock, firing all the time-related callbacks.
  5647. **Usage**
  5648. ```py
  5649. await page.clock.run_for(1000);
  5650. await page.clock.run_for(\"30:00\")
  5651. ```
  5652. Parameters
  5653. ----------
  5654. ticks : Union[int, str]
  5655. Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
  5656. "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
  5657. """
  5658. return mapping.from_maybe_impl(await self._impl_obj.run_for(ticks=ticks))
  5659. async def set_fixed_time(
  5660. self, time: typing.Union[float, str, datetime.datetime]
  5661. ) -> None:
  5662. """Clock.set_fixed_time
  5663. Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.
  5664. Use this method for simple scenarios where you only need to test with a predefined time. For more advanced
  5665. scenarios, use `clock.install()` instead. Read docs on [clock emulation](https://playwright.dev/python/docs/clock) to learn more.
  5666. **Usage**
  5667. ```py
  5668. await page.clock.set_fixed_time(datetime.datetime.now())
  5669. await page.clock.set_fixed_time(datetime.datetime(2020, 2, 2))
  5670. await page.clock.set_fixed_time(\"2020-02-02\")
  5671. ```
  5672. Parameters
  5673. ----------
  5674. time : Union[datetime.datetime, float, str]
  5675. Time to be set.
  5676. """
  5677. return mapping.from_maybe_impl(await self._impl_obj.set_fixed_time(time=time))
  5678. async def set_system_time(
  5679. self, time: typing.Union[float, str, datetime.datetime]
  5680. ) -> None:
  5681. """Clock.set_system_time
  5682. Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for
  5683. example switching from summer to winter time, or changing time zones.
  5684. **Usage**
  5685. ```py
  5686. await page.clock.set_system_time(datetime.datetime.now())
  5687. await page.clock.set_system_time(datetime.datetime(2020, 2, 2))
  5688. await page.clock.set_system_time(\"2020-02-02\")
  5689. ```
  5690. Parameters
  5691. ----------
  5692. time : Union[datetime.datetime, float, str]
  5693. Time to be set.
  5694. """
  5695. return mapping.from_maybe_impl(await self._impl_obj.set_system_time(time=time))
  5696. mapping.register(ClockImpl, Clock)
  5697. class ConsoleMessage(AsyncBase):
  5698. @property
  5699. def type(
  5700. self,
  5701. ) -> typing.Union[
  5702. Literal["assert"],
  5703. Literal["clear"],
  5704. Literal["count"],
  5705. Literal["debug"],
  5706. Literal["dir"],
  5707. Literal["dirxml"],
  5708. Literal["endGroup"],
  5709. Literal["error"],
  5710. Literal["info"],
  5711. Literal["log"],
  5712. Literal["profile"],
  5713. Literal["profileEnd"],
  5714. Literal["startGroup"],
  5715. Literal["startGroupCollapsed"],
  5716. Literal["table"],
  5717. Literal["time"],
  5718. Literal["timeEnd"],
  5719. Literal["trace"],
  5720. Literal["warning"],
  5721. ]:
  5722. """ConsoleMessage.type
  5723. Returns
  5724. -------
  5725. Union["assert", "clear", "count", "debug", "dir", "dirxml", "endGroup", "error", "info", "log", "profile", "profileEnd", "startGroup", "startGroupCollapsed", "table", "time", "timeEnd", "trace", "warning"]
  5726. """
  5727. return mapping.from_maybe_impl(self._impl_obj.type)
  5728. @property
  5729. def text(self) -> str:
  5730. """ConsoleMessage.text
  5731. The text of the console message.
  5732. Returns
  5733. -------
  5734. str
  5735. """
  5736. return mapping.from_maybe_impl(self._impl_obj.text)
  5737. @property
  5738. def args(self) -> typing.List["JSHandle"]:
  5739. """ConsoleMessage.args
  5740. List of arguments passed to a `console` function call. See also `page.on('console')`.
  5741. Returns
  5742. -------
  5743. List[JSHandle]
  5744. """
  5745. return mapping.from_impl_list(self._impl_obj.args)
  5746. @property
  5747. def location(self) -> SourceLocation:
  5748. """ConsoleMessage.location
  5749. Returns
  5750. -------
  5751. {url: str, lineNumber: int, columnNumber: int}
  5752. """
  5753. return mapping.from_impl(self._impl_obj.location)
  5754. @property
  5755. def page(self) -> typing.Optional["Page"]:
  5756. """ConsoleMessage.page
  5757. The page that produced this console message, if any.
  5758. Returns
  5759. -------
  5760. Union[Page, None]
  5761. """
  5762. return mapping.from_impl_nullable(self._impl_obj.page)
  5763. @property
  5764. def worker(self) -> typing.Optional["Worker"]:
  5765. """ConsoleMessage.worker
  5766. The web worker or service worker that produced this console message, if any. Note that console messages from web
  5767. workers also have non-null `console_message.page()`.
  5768. Returns
  5769. -------
  5770. Union[Worker, None]
  5771. """
  5772. return mapping.from_impl_nullable(self._impl_obj.worker)
  5773. mapping.register(ConsoleMessageImpl, ConsoleMessage)
  5774. class Dialog(AsyncBase):
  5775. @property
  5776. def type(self) -> str:
  5777. """Dialog.type
  5778. Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
  5779. Returns
  5780. -------
  5781. str
  5782. """
  5783. return mapping.from_maybe_impl(self._impl_obj.type)
  5784. @property
  5785. def message(self) -> str:
  5786. """Dialog.message
  5787. A message displayed in the dialog.
  5788. Returns
  5789. -------
  5790. str
  5791. """
  5792. return mapping.from_maybe_impl(self._impl_obj.message)
  5793. @property
  5794. def default_value(self) -> str:
  5795. """Dialog.default_value
  5796. If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
  5797. Returns
  5798. -------
  5799. str
  5800. """
  5801. return mapping.from_maybe_impl(self._impl_obj.default_value)
  5802. @property
  5803. def page(self) -> typing.Optional["Page"]:
  5804. """Dialog.page
  5805. The page that initiated this dialog, if available.
  5806. Returns
  5807. -------
  5808. Union[Page, None]
  5809. """
  5810. return mapping.from_impl_nullable(self._impl_obj.page)
  5811. async def accept(self, prompt_text: typing.Optional[str] = None) -> None:
  5812. """Dialog.accept
  5813. Returns when the dialog has been accepted.
  5814. Parameters
  5815. ----------
  5816. prompt_text : Union[str, None]
  5817. A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.
  5818. """
  5819. return mapping.from_maybe_impl(
  5820. await self._impl_obj.accept(promptText=prompt_text)
  5821. )
  5822. async def dismiss(self) -> None:
  5823. """Dialog.dismiss
  5824. Returns when the dialog has been dismissed.
  5825. """
  5826. return mapping.from_maybe_impl(await self._impl_obj.dismiss())
  5827. mapping.register(DialogImpl, Dialog)
  5828. class Download(AsyncBase):
  5829. @property
  5830. def page(self) -> "Page":
  5831. """Download.page
  5832. Get the page that the download belongs to.
  5833. Returns
  5834. -------
  5835. Page
  5836. """
  5837. return mapping.from_impl(self._impl_obj.page)
  5838. @property
  5839. def url(self) -> str:
  5840. """Download.url
  5841. Returns downloaded url.
  5842. Returns
  5843. -------
  5844. str
  5845. """
  5846. return mapping.from_maybe_impl(self._impl_obj.url)
  5847. @property
  5848. def suggested_filename(self) -> str:
  5849. """Download.suggested_filename
  5850. Returns suggested filename for this download. It is typically computed by the browser from the
  5851. [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response
  5852. header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).
  5853. Different browsers can use different logic for computing it.
  5854. Returns
  5855. -------
  5856. str
  5857. """
  5858. return mapping.from_maybe_impl(self._impl_obj.suggested_filename)
  5859. async def delete(self) -> None:
  5860. """Download.delete
  5861. Deletes the downloaded file. Will wait for the download to finish if necessary.
  5862. """
  5863. return mapping.from_maybe_impl(await self._impl_obj.delete())
  5864. async def failure(self) -> typing.Optional[str]:
  5865. """Download.failure
  5866. Returns download error if any. Will wait for the download to finish if necessary.
  5867. Returns
  5868. -------
  5869. Union[str, None]
  5870. """
  5871. return mapping.from_maybe_impl(await self._impl_obj.failure())
  5872. async def path(self) -> pathlib.Path:
  5873. """Download.path
  5874. Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method
  5875. will wait for the download to finish if necessary. The method throws when connected remotely.
  5876. Note that the download's file name is a random GUID, use `download.suggested_filename()` to get suggested
  5877. file name.
  5878. Returns
  5879. -------
  5880. pathlib.Path
  5881. """
  5882. return mapping.from_maybe_impl(await self._impl_obj.path())
  5883. async def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
  5884. """Download.save_as
  5885. Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.
  5886. Will wait for the download to finish if necessary.
  5887. **Usage**
  5888. ```py
  5889. await download.save_as(\"/path/to/save/at/\" + download.suggested_filename)
  5890. ```
  5891. Parameters
  5892. ----------
  5893. path : Union[pathlib.Path, str]
  5894. Path where the download should be copied.
  5895. """
  5896. return mapping.from_maybe_impl(await self._impl_obj.save_as(path=path))
  5897. async def cancel(self) -> None:
  5898. """Download.cancel
  5899. Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,
  5900. `download.failure()` would resolve to `'canceled'`.
  5901. """
  5902. return mapping.from_maybe_impl(await self._impl_obj.cancel())
  5903. mapping.register(DownloadImpl, Download)
  5904. class Video(AsyncBase):
  5905. async def path(self) -> pathlib.Path:
  5906. """Video.path
  5907. Returns the file system path this video will be recorded to. The video is guaranteed to be written to the
  5908. filesystem upon closing the browser context. This method throws when connected remotely.
  5909. Returns
  5910. -------
  5911. pathlib.Path
  5912. """
  5913. return mapping.from_maybe_impl(await self._impl_obj.path())
  5914. async def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
  5915. """Video.save_as
  5916. Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or
  5917. after the page has closed. This method waits until the page is closed and the video is fully saved.
  5918. Parameters
  5919. ----------
  5920. path : Union[pathlib.Path, str]
  5921. Path where the video should be saved.
  5922. """
  5923. return mapping.from_maybe_impl(await self._impl_obj.save_as(path=path))
  5924. async def delete(self) -> None:
  5925. """Video.delete
  5926. Deletes the video file. Will wait for the video to finish if necessary.
  5927. """
  5928. return mapping.from_maybe_impl(await self._impl_obj.delete())
  5929. mapping.register(VideoImpl, Video)
  5930. class Page(AsyncContextManager):
  5931. @typing.overload
  5932. def on(
  5933. self,
  5934. event: Literal["close"],
  5935. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  5936. ) -> None:
  5937. """
  5938. Emitted when the page closes."""
  5939. @typing.overload
  5940. def on(
  5941. self,
  5942. event: Literal["console"],
  5943. f: typing.Callable[
  5944. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  5945. ],
  5946. ) -> None:
  5947. """
  5948. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  5949. The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
  5950. **Usage**
  5951. ```py
  5952. async def print_args(msg):
  5953. values = []
  5954. for arg in msg.args:
  5955. values.append(await arg.json_value())
  5956. print(values)
  5957. page.on(\"console\", print_args)
  5958. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  5959. ```"""
  5960. @typing.overload
  5961. def on(
  5962. self,
  5963. event: Literal["crash"],
  5964. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  5965. ) -> None:
  5966. """
  5967. Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
  5968. crashes, ongoing and subsequent operations will throw.
  5969. The most common way to deal with crashes is to catch an exception:
  5970. ```py
  5971. try:
  5972. # crash might happen during a click.
  5973. await page.click(\"button\")
  5974. # or while waiting for an event.
  5975. await page.wait_for_event(\"popup\")
  5976. except Error as e:
  5977. pass
  5978. # when the page crashes, exception message contains \"crash\".
  5979. ```"""
  5980. @typing.overload
  5981. def on(
  5982. self,
  5983. event: Literal["dialog"],
  5984. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  5985. ) -> None:
  5986. """
  5987. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  5988. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  5989. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  5990. and actions like click will never finish.
  5991. **Usage**
  5992. ```python
  5993. page.on(\"dialog\", lambda dialog: dialog.accept())
  5994. ```
  5995. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  5996. automatically dismissed."""
  5997. @typing.overload
  5998. def on(
  5999. self,
  6000. event: Literal["domcontentloaded"],
  6001. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6002. ) -> None:
  6003. """
  6004. Emitted when the JavaScript
  6005. [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
  6006. """
  6007. @typing.overload
  6008. def on(
  6009. self,
  6010. event: Literal["download"],
  6011. f: typing.Callable[["Download"], "typing.Union[typing.Awaitable[None], None]"],
  6012. ) -> None:
  6013. """
  6014. Emitted when attachment download started. User can access basic file operations on downloaded content via the
  6015. passed `Download` instance."""
  6016. @typing.overload
  6017. def on(
  6018. self,
  6019. event: Literal["filechooser"],
  6020. f: typing.Callable[
  6021. ["FileChooser"], "typing.Union[typing.Awaitable[None], None]"
  6022. ],
  6023. ) -> None:
  6024. """
  6025. Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
  6026. respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
  6027. ```py
  6028. page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
  6029. ```"""
  6030. @typing.overload
  6031. def on(
  6032. self,
  6033. event: Literal["frameattached"],
  6034. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6035. ) -> None:
  6036. """
  6037. Emitted when a frame is attached."""
  6038. @typing.overload
  6039. def on(
  6040. self,
  6041. event: Literal["framedetached"],
  6042. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6043. ) -> None:
  6044. """
  6045. Emitted when a frame is detached."""
  6046. @typing.overload
  6047. def on(
  6048. self,
  6049. event: Literal["framenavigated"],
  6050. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6051. ) -> None:
  6052. """
  6053. Emitted when a frame is navigated to a new url."""
  6054. @typing.overload
  6055. def on(
  6056. self,
  6057. event: Literal["load"],
  6058. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6059. ) -> None:
  6060. """
  6061. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
  6062. """
  6063. @typing.overload
  6064. def on(
  6065. self,
  6066. event: Literal["pageerror"],
  6067. f: typing.Callable[["Error"], "typing.Union[typing.Awaitable[None], None]"],
  6068. ) -> None:
  6069. """
  6070. Emitted when an uncaught exception happens within the page.
  6071. ```py
  6072. # Log all uncaught errors to the terminal
  6073. page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
  6074. # Navigate to a page with an exception.
  6075. await page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
  6076. ```"""
  6077. @typing.overload
  6078. def on(
  6079. self,
  6080. event: Literal["popup"],
  6081. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6082. ) -> None:
  6083. """
  6084. Emitted when the page opens a new tab or window. This event is emitted in addition to the
  6085. `browser_context.on('page')`, but only for popups relevant to this page.
  6086. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  6087. popup with `window.open('http://example.com')`, this event will fire when the network request to
  6088. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  6089. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  6090. instead of similar methods on the `Page`.
  6091. ```py
  6092. async with page.expect_event(\"popup\") as page_info:
  6093. await page.get_by_text(\"open the popup\").click()
  6094. popup = await page_info.value
  6095. print(await popup.evaluate(\"location.href\"))
  6096. ```
  6097. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  6098. need it in most cases)."""
  6099. @typing.overload
  6100. def on(
  6101. self,
  6102. event: Literal["request"],
  6103. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6104. ) -> None:
  6105. """
  6106. Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
  6107. see `page.route()` or `browser_context.route()`."""
  6108. @typing.overload
  6109. def on(
  6110. self,
  6111. event: Literal["requestfailed"],
  6112. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6113. ) -> None:
  6114. """
  6115. Emitted when a request fails, for example by timing out.
  6116. ```python
  6117. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
  6118. ```
  6119. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  6120. will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
  6121. only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
  6122. net::ERR_FAILED."""
  6123. @typing.overload
  6124. def on(
  6125. self,
  6126. event: Literal["requestfinished"],
  6127. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6128. ) -> None:
  6129. """
  6130. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  6131. sequence of events is `request`, `response` and `requestfinished`."""
  6132. @typing.overload
  6133. def on(
  6134. self,
  6135. event: Literal["response"],
  6136. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  6137. ) -> None:
  6138. """
  6139. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  6140. events is `request`, `response` and `requestfinished`."""
  6141. @typing.overload
  6142. def on(
  6143. self,
  6144. event: Literal["websocket"],
  6145. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  6146. ) -> None:
  6147. """
  6148. Emitted when `WebSocket` request is sent."""
  6149. @typing.overload
  6150. def on(
  6151. self,
  6152. event: Literal["worker"],
  6153. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  6154. ) -> None:
  6155. """
  6156. Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
  6157. by the page."""
  6158. def on(
  6159. self,
  6160. event: str,
  6161. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6162. ) -> None:
  6163. return super().on(event=event, f=f)
  6164. @typing.overload
  6165. def once(
  6166. self,
  6167. event: Literal["close"],
  6168. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6169. ) -> None:
  6170. """
  6171. Emitted when the page closes."""
  6172. @typing.overload
  6173. def once(
  6174. self,
  6175. event: Literal["console"],
  6176. f: typing.Callable[
  6177. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  6178. ],
  6179. ) -> None:
  6180. """
  6181. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  6182. The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
  6183. **Usage**
  6184. ```py
  6185. async def print_args(msg):
  6186. values = []
  6187. for arg in msg.args:
  6188. values.append(await arg.json_value())
  6189. print(values)
  6190. page.on(\"console\", print_args)
  6191. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  6192. ```"""
  6193. @typing.overload
  6194. def once(
  6195. self,
  6196. event: Literal["crash"],
  6197. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6198. ) -> None:
  6199. """
  6200. Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
  6201. crashes, ongoing and subsequent operations will throw.
  6202. The most common way to deal with crashes is to catch an exception:
  6203. ```py
  6204. try:
  6205. # crash might happen during a click.
  6206. await page.click(\"button\")
  6207. # or while waiting for an event.
  6208. await page.wait_for_event(\"popup\")
  6209. except Error as e:
  6210. pass
  6211. # when the page crashes, exception message contains \"crash\".
  6212. ```"""
  6213. @typing.overload
  6214. def once(
  6215. self,
  6216. event: Literal["dialog"],
  6217. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  6218. ) -> None:
  6219. """
  6220. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  6221. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  6222. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  6223. and actions like click will never finish.
  6224. **Usage**
  6225. ```python
  6226. page.on(\"dialog\", lambda dialog: dialog.accept())
  6227. ```
  6228. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  6229. automatically dismissed."""
  6230. @typing.overload
  6231. def once(
  6232. self,
  6233. event: Literal["domcontentloaded"],
  6234. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6235. ) -> None:
  6236. """
  6237. Emitted when the JavaScript
  6238. [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
  6239. """
  6240. @typing.overload
  6241. def once(
  6242. self,
  6243. event: Literal["download"],
  6244. f: typing.Callable[["Download"], "typing.Union[typing.Awaitable[None], None]"],
  6245. ) -> None:
  6246. """
  6247. Emitted when attachment download started. User can access basic file operations on downloaded content via the
  6248. passed `Download` instance."""
  6249. @typing.overload
  6250. def once(
  6251. self,
  6252. event: Literal["filechooser"],
  6253. f: typing.Callable[
  6254. ["FileChooser"], "typing.Union[typing.Awaitable[None], None]"
  6255. ],
  6256. ) -> None:
  6257. """
  6258. Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
  6259. respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
  6260. ```py
  6261. page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
  6262. ```"""
  6263. @typing.overload
  6264. def once(
  6265. self,
  6266. event: Literal["frameattached"],
  6267. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6268. ) -> None:
  6269. """
  6270. Emitted when a frame is attached."""
  6271. @typing.overload
  6272. def once(
  6273. self,
  6274. event: Literal["framedetached"],
  6275. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6276. ) -> None:
  6277. """
  6278. Emitted when a frame is detached."""
  6279. @typing.overload
  6280. def once(
  6281. self,
  6282. event: Literal["framenavigated"],
  6283. f: typing.Callable[["Frame"], "typing.Union[typing.Awaitable[None], None]"],
  6284. ) -> None:
  6285. """
  6286. Emitted when a frame is navigated to a new url."""
  6287. @typing.overload
  6288. def once(
  6289. self,
  6290. event: Literal["load"],
  6291. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6292. ) -> None:
  6293. """
  6294. Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
  6295. """
  6296. @typing.overload
  6297. def once(
  6298. self,
  6299. event: Literal["pageerror"],
  6300. f: typing.Callable[["Error"], "typing.Union[typing.Awaitable[None], None]"],
  6301. ) -> None:
  6302. """
  6303. Emitted when an uncaught exception happens within the page.
  6304. ```py
  6305. # Log all uncaught errors to the terminal
  6306. page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
  6307. # Navigate to a page with an exception.
  6308. await page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
  6309. ```"""
  6310. @typing.overload
  6311. def once(
  6312. self,
  6313. event: Literal["popup"],
  6314. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  6315. ) -> None:
  6316. """
  6317. Emitted when the page opens a new tab or window. This event is emitted in addition to the
  6318. `browser_context.on('page')`, but only for popups relevant to this page.
  6319. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  6320. popup with `window.open('http://example.com')`, this event will fire when the network request to
  6321. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  6322. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  6323. instead of similar methods on the `Page`.
  6324. ```py
  6325. async with page.expect_event(\"popup\") as page_info:
  6326. await page.get_by_text(\"open the popup\").click()
  6327. popup = await page_info.value
  6328. print(await popup.evaluate(\"location.href\"))
  6329. ```
  6330. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  6331. need it in most cases)."""
  6332. @typing.overload
  6333. def once(
  6334. self,
  6335. event: Literal["request"],
  6336. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6337. ) -> None:
  6338. """
  6339. Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
  6340. see `page.route()` or `browser_context.route()`."""
  6341. @typing.overload
  6342. def once(
  6343. self,
  6344. event: Literal["requestfailed"],
  6345. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6346. ) -> None:
  6347. """
  6348. Emitted when a request fails, for example by timing out.
  6349. ```python
  6350. page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
  6351. ```
  6352. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  6353. will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
  6354. only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
  6355. net::ERR_FAILED."""
  6356. @typing.overload
  6357. def once(
  6358. self,
  6359. event: Literal["requestfinished"],
  6360. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  6361. ) -> None:
  6362. """
  6363. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  6364. sequence of events is `request`, `response` and `requestfinished`."""
  6365. @typing.overload
  6366. def once(
  6367. self,
  6368. event: Literal["response"],
  6369. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  6370. ) -> None:
  6371. """
  6372. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  6373. events is `request`, `response` and `requestfinished`."""
  6374. @typing.overload
  6375. def once(
  6376. self,
  6377. event: Literal["websocket"],
  6378. f: typing.Callable[["WebSocket"], "typing.Union[typing.Awaitable[None], None]"],
  6379. ) -> None:
  6380. """
  6381. Emitted when `WebSocket` request is sent."""
  6382. @typing.overload
  6383. def once(
  6384. self,
  6385. event: Literal["worker"],
  6386. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  6387. ) -> None:
  6388. """
  6389. Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
  6390. by the page."""
  6391. def once(
  6392. self,
  6393. event: str,
  6394. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  6395. ) -> None:
  6396. return super().once(event=event, f=f)
  6397. @property
  6398. def keyboard(self) -> "Keyboard":
  6399. """Page.keyboard
  6400. Returns
  6401. -------
  6402. Keyboard
  6403. """
  6404. return mapping.from_impl(self._impl_obj.keyboard)
  6405. @property
  6406. def mouse(self) -> "Mouse":
  6407. """Page.mouse
  6408. Returns
  6409. -------
  6410. Mouse
  6411. """
  6412. return mapping.from_impl(self._impl_obj.mouse)
  6413. @property
  6414. def touchscreen(self) -> "Touchscreen":
  6415. """Page.touchscreen
  6416. Returns
  6417. -------
  6418. Touchscreen
  6419. """
  6420. return mapping.from_impl(self._impl_obj.touchscreen)
  6421. @property
  6422. def context(self) -> "BrowserContext":
  6423. """Page.context
  6424. Get the browser context that the page belongs to.
  6425. Returns
  6426. -------
  6427. BrowserContext
  6428. """
  6429. return mapping.from_impl(self._impl_obj.context)
  6430. @property
  6431. def clock(self) -> "Clock":
  6432. """Page.clock
  6433. Playwright has ability to mock clock and passage of time.
  6434. Returns
  6435. -------
  6436. Clock
  6437. """
  6438. return mapping.from_impl(self._impl_obj.clock)
  6439. @property
  6440. def main_frame(self) -> "Frame":
  6441. """Page.main_frame
  6442. The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
  6443. Returns
  6444. -------
  6445. Frame
  6446. """
  6447. return mapping.from_impl(self._impl_obj.main_frame)
  6448. @property
  6449. def frames(self) -> typing.List["Frame"]:
  6450. """Page.frames
  6451. An array of all frames attached to the page.
  6452. Returns
  6453. -------
  6454. List[Frame]
  6455. """
  6456. return mapping.from_impl_list(self._impl_obj.frames)
  6457. @property
  6458. def url(self) -> str:
  6459. """Page.url
  6460. Returns
  6461. -------
  6462. str
  6463. """
  6464. return mapping.from_maybe_impl(self._impl_obj.url)
  6465. @property
  6466. def viewport_size(self) -> typing.Optional[ViewportSize]:
  6467. """Page.viewport_size
  6468. Returns
  6469. -------
  6470. Union[{width: int, height: int}, None]
  6471. """
  6472. return mapping.from_impl_nullable(self._impl_obj.viewport_size)
  6473. @property
  6474. def workers(self) -> typing.List["Worker"]:
  6475. """Page.workers
  6476. This method returns all of the dedicated
  6477. [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
  6478. **NOTE** This does not contain ServiceWorkers
  6479. Returns
  6480. -------
  6481. List[Worker]
  6482. """
  6483. return mapping.from_impl_list(self._impl_obj.workers)
  6484. @property
  6485. def request(self) -> "APIRequestContext":
  6486. """Page.request
  6487. API testing helper associated with this page. This method returns the same instance as
  6488. `browser_context.request` on the page's context. See `browser_context.request` for more
  6489. details.
  6490. Returns
  6491. -------
  6492. APIRequestContext
  6493. """
  6494. return mapping.from_impl(self._impl_obj.request)
  6495. @property
  6496. def video(self) -> typing.Optional["Video"]:
  6497. """Page.video
  6498. Video object associated with this page.
  6499. Returns
  6500. -------
  6501. Union[Video, None]
  6502. """
  6503. return mapping.from_impl_nullable(self._impl_obj.video)
  6504. async def opener(self) -> typing.Optional["Page"]:
  6505. """Page.opener
  6506. Returns the opener for popup pages and `null` for others. If the opener has been closed already the returns `null`.
  6507. Returns
  6508. -------
  6509. Union[Page, None]
  6510. """
  6511. return mapping.from_impl_nullable(await self._impl_obj.opener())
  6512. def frame(
  6513. self,
  6514. name: typing.Optional[str] = None,
  6515. *,
  6516. url: typing.Optional[
  6517. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  6518. ] = None,
  6519. ) -> typing.Optional["Frame"]:
  6520. """Page.frame
  6521. Returns frame matching the specified criteria. Either `name` or `url` must be specified.
  6522. **Usage**
  6523. ```py
  6524. frame = page.frame(name=\"frame-name\")
  6525. ```
  6526. Parameters
  6527. ----------
  6528. name : Union[str, None]
  6529. Frame name specified in the `iframe`'s `name` attribute. Optional.
  6530. url : Union[Callable[[str], bool], Pattern[str], str, None]
  6531. A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object. Optional.
  6532. Returns
  6533. -------
  6534. Union[Frame, None]
  6535. """
  6536. return mapping.from_impl_nullable(
  6537. self._impl_obj.frame(name=name, url=self._wrap_handler(url))
  6538. )
  6539. def set_default_navigation_timeout(self, timeout: float) -> None:
  6540. """Page.set_default_navigation_timeout
  6541. This setting will change the default maximum navigation time for the following methods and related shortcuts:
  6542. - `page.go_back()`
  6543. - `page.go_forward()`
  6544. - `page.goto()`
  6545. - `page.reload()`
  6546. - `page.set_content()`
  6547. - `page.expect_navigation()`
  6548. - `page.wait_for_url()`
  6549. **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`,
  6550. `browser_context.set_default_timeout()` and `browser_context.set_default_navigation_timeout()`.
  6551. Parameters
  6552. ----------
  6553. timeout : float
  6554. Maximum navigation time in milliseconds
  6555. """
  6556. return mapping.from_maybe_impl(
  6557. self._impl_obj.set_default_navigation_timeout(timeout=timeout)
  6558. )
  6559. def set_default_timeout(self, timeout: float) -> None:
  6560. """Page.set_default_timeout
  6561. This setting will change the default maximum time for all the methods accepting `timeout` option.
  6562. **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`.
  6563. Parameters
  6564. ----------
  6565. timeout : float
  6566. Maximum time in milliseconds. Pass `0` to disable timeout.
  6567. """
  6568. return mapping.from_maybe_impl(
  6569. self._impl_obj.set_default_timeout(timeout=timeout)
  6570. )
  6571. async def query_selector(
  6572. self, selector: str, *, strict: typing.Optional[bool] = None
  6573. ) -> typing.Optional["ElementHandle"]:
  6574. """Page.query_selector
  6575. The method finds an element matching the specified selector within the page. If no elements match the selector, the
  6576. return value resolves to `null`. To wait for an element on the page, use `locator.wait_for()`.
  6577. Parameters
  6578. ----------
  6579. selector : str
  6580. A selector to query for.
  6581. strict : Union[bool, None]
  6582. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6583. element, the call throws an exception.
  6584. Returns
  6585. -------
  6586. Union[ElementHandle, None]
  6587. """
  6588. return mapping.from_impl_nullable(
  6589. await self._impl_obj.query_selector(selector=selector, strict=strict)
  6590. )
  6591. async def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
  6592. """Page.query_selector_all
  6593. The method finds all elements matching the specified selector within the page. If no elements match the selector,
  6594. the return value resolves to `[]`.
  6595. Parameters
  6596. ----------
  6597. selector : str
  6598. A selector to query for.
  6599. Returns
  6600. -------
  6601. List[ElementHandle]
  6602. """
  6603. return mapping.from_impl_list(
  6604. await self._impl_obj.query_selector_all(selector=selector)
  6605. )
  6606. async def wait_for_selector(
  6607. self,
  6608. selector: str,
  6609. *,
  6610. timeout: typing.Optional[float] = None,
  6611. state: typing.Optional[
  6612. Literal["attached", "detached", "hidden", "visible"]
  6613. ] = None,
  6614. strict: typing.Optional[bool] = None,
  6615. ) -> typing.Optional["ElementHandle"]:
  6616. """Page.wait_for_selector
  6617. Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
  6618. `detached`.
  6619. **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
  6620. objects and web-first assertions makes the code wait-for-selector-free.
  6621. Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
  6622. at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
  6623. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
  6624. **Usage**
  6625. This method works across navigations:
  6626. ```py
  6627. import asyncio
  6628. from playwright.async_api import async_playwright, Playwright
  6629. async def run(playwright: Playwright):
  6630. chromium = playwright.chromium
  6631. browser = await chromium.launch()
  6632. page = await browser.new_page()
  6633. for current_url in [\"https://google.com\", \"https://bbc.com\"]:
  6634. await page.goto(current_url, wait_until=\"domcontentloaded\")
  6635. element = await page.wait_for_selector(\"img\")
  6636. print(\"Loaded image: \" + str(await element.get_attribute(\"src\")))
  6637. await browser.close()
  6638. async def main():
  6639. async with async_playwright() as playwright:
  6640. await run(playwright)
  6641. asyncio.run(main())
  6642. ```
  6643. Parameters
  6644. ----------
  6645. selector : str
  6646. A selector to query for.
  6647. timeout : Union[float, None]
  6648. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6649. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6650. state : Union["attached", "detached", "hidden", "visible", None]
  6651. Defaults to `'visible'`. Can be either:
  6652. - `'attached'` - wait for element to be present in DOM.
  6653. - `'detached'` - wait for element to not be present in DOM.
  6654. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  6655. without any content or with `display:none` has an empty bounding box and is not considered visible.
  6656. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  6657. `visibility:hidden`. This is opposite to the `'visible'` option.
  6658. strict : Union[bool, None]
  6659. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6660. element, the call throws an exception.
  6661. Returns
  6662. -------
  6663. Union[ElementHandle, None]
  6664. """
  6665. return mapping.from_impl_nullable(
  6666. await self._impl_obj.wait_for_selector(
  6667. selector=selector, timeout=timeout, state=state, strict=strict
  6668. )
  6669. )
  6670. async def is_checked(
  6671. self,
  6672. selector: str,
  6673. *,
  6674. strict: typing.Optional[bool] = None,
  6675. timeout: typing.Optional[float] = None,
  6676. ) -> bool:
  6677. """Page.is_checked
  6678. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  6679. Parameters
  6680. ----------
  6681. selector : str
  6682. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6683. used.
  6684. strict : Union[bool, None]
  6685. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6686. element, the call throws an exception.
  6687. timeout : Union[float, None]
  6688. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6689. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6690. Returns
  6691. -------
  6692. bool
  6693. """
  6694. return mapping.from_maybe_impl(
  6695. await self._impl_obj.is_checked(
  6696. selector=selector, strict=strict, timeout=timeout
  6697. )
  6698. )
  6699. async def is_disabled(
  6700. self,
  6701. selector: str,
  6702. *,
  6703. strict: typing.Optional[bool] = None,
  6704. timeout: typing.Optional[float] = None,
  6705. ) -> bool:
  6706. """Page.is_disabled
  6707. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  6708. Parameters
  6709. ----------
  6710. selector : str
  6711. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6712. used.
  6713. strict : Union[bool, None]
  6714. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6715. element, the call throws an exception.
  6716. timeout : Union[float, None]
  6717. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6718. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6719. Returns
  6720. -------
  6721. bool
  6722. """
  6723. return mapping.from_maybe_impl(
  6724. await self._impl_obj.is_disabled(
  6725. selector=selector, strict=strict, timeout=timeout
  6726. )
  6727. )
  6728. async def is_editable(
  6729. self,
  6730. selector: str,
  6731. *,
  6732. strict: typing.Optional[bool] = None,
  6733. timeout: typing.Optional[float] = None,
  6734. ) -> bool:
  6735. """Page.is_editable
  6736. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
  6737. Parameters
  6738. ----------
  6739. selector : str
  6740. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6741. used.
  6742. strict : Union[bool, None]
  6743. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6744. element, the call throws an exception.
  6745. timeout : Union[float, None]
  6746. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6747. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6748. Returns
  6749. -------
  6750. bool
  6751. """
  6752. return mapping.from_maybe_impl(
  6753. await self._impl_obj.is_editable(
  6754. selector=selector, strict=strict, timeout=timeout
  6755. )
  6756. )
  6757. async def is_enabled(
  6758. self,
  6759. selector: str,
  6760. *,
  6761. strict: typing.Optional[bool] = None,
  6762. timeout: typing.Optional[float] = None,
  6763. ) -> bool:
  6764. """Page.is_enabled
  6765. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  6766. Parameters
  6767. ----------
  6768. selector : str
  6769. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6770. used.
  6771. strict : Union[bool, None]
  6772. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6773. element, the call throws an exception.
  6774. timeout : Union[float, None]
  6775. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6776. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6777. Returns
  6778. -------
  6779. bool
  6780. """
  6781. return mapping.from_maybe_impl(
  6782. await self._impl_obj.is_enabled(
  6783. selector=selector, strict=strict, timeout=timeout
  6784. )
  6785. )
  6786. async def is_hidden(
  6787. self,
  6788. selector: str,
  6789. *,
  6790. strict: typing.Optional[bool] = None,
  6791. timeout: typing.Optional[float] = None,
  6792. ) -> bool:
  6793. """Page.is_hidden
  6794. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
  6795. does not match any elements is considered hidden.
  6796. Parameters
  6797. ----------
  6798. selector : str
  6799. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6800. used.
  6801. strict : Union[bool, None]
  6802. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6803. element, the call throws an exception.
  6804. timeout : Union[float, None]
  6805. Deprecated: This option is ignored. `page.is_hidden()` does not wait for the↵element to become hidden and returns immediately.
  6806. Returns
  6807. -------
  6808. bool
  6809. """
  6810. return mapping.from_maybe_impl(
  6811. await self._impl_obj.is_hidden(
  6812. selector=selector, strict=strict, timeout=timeout
  6813. )
  6814. )
  6815. async def is_visible(
  6816. self,
  6817. selector: str,
  6818. *,
  6819. strict: typing.Optional[bool] = None,
  6820. timeout: typing.Optional[float] = None,
  6821. ) -> bool:
  6822. """Page.is_visible
  6823. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
  6824. is considered not visible.
  6825. Parameters
  6826. ----------
  6827. selector : str
  6828. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6829. used.
  6830. strict : Union[bool, None]
  6831. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6832. element, the call throws an exception.
  6833. timeout : Union[float, None]
  6834. Deprecated: This option is ignored. `page.is_visible()` does not wait↵for the element to become visible and returns immediately.
  6835. Returns
  6836. -------
  6837. bool
  6838. """
  6839. return mapping.from_maybe_impl(
  6840. await self._impl_obj.is_visible(
  6841. selector=selector, strict=strict, timeout=timeout
  6842. )
  6843. )
  6844. async def dispatch_event(
  6845. self,
  6846. selector: str,
  6847. type: str,
  6848. event_init: typing.Optional[typing.Dict] = None,
  6849. *,
  6850. timeout: typing.Optional[float] = None,
  6851. strict: typing.Optional[bool] = None,
  6852. ) -> None:
  6853. """Page.dispatch_event
  6854. The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
  6855. `click` is dispatched. This is equivalent to calling
  6856. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  6857. **Usage**
  6858. ```py
  6859. await page.dispatch_event(\"button#submit\", \"click\")
  6860. ```
  6861. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  6862. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  6863. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  6864. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  6865. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  6866. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  6867. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  6868. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  6869. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  6870. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  6871. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  6872. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  6873. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  6874. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  6875. ```py
  6876. # note you can only create data_transfer in chromium and firefox
  6877. data_transfer = await page.evaluate_handle(\"new DataTransfer()\")
  6878. await page.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
  6879. ```
  6880. Parameters
  6881. ----------
  6882. selector : str
  6883. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  6884. used.
  6885. type : str
  6886. DOM event type: `"click"`, `"dragstart"`, etc.
  6887. event_init : Union[Dict, None]
  6888. Optional event-specific initialization properties.
  6889. timeout : Union[float, None]
  6890. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  6891. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  6892. strict : Union[bool, None]
  6893. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  6894. element, the call throws an exception.
  6895. """
  6896. return mapping.from_maybe_impl(
  6897. await self._impl_obj.dispatch_event(
  6898. selector=selector,
  6899. type=type,
  6900. eventInit=mapping.to_impl(event_init),
  6901. timeout=timeout,
  6902. strict=strict,
  6903. )
  6904. )
  6905. async def evaluate(
  6906. self, expression: str, arg: typing.Optional[typing.Any] = None
  6907. ) -> typing.Any:
  6908. """Page.evaluate
  6909. Returns the value of the `expression` invocation.
  6910. If the function passed to the `page.evaluate()` returns a [Promise], then `page.evaluate()` would
  6911. wait for the promise to resolve and return its value.
  6912. If the function passed to the `page.evaluate()` returns a non-[Serializable] value, then
  6913. `page.evaluate()` resolves to `undefined`. Playwright also supports transferring some additional values
  6914. that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
  6915. **Usage**
  6916. Passing argument to `expression`:
  6917. ```py
  6918. result = await page.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
  6919. print(result) # prints \"56\"
  6920. ```
  6921. A string can also be passed in instead of a function:
  6922. ```py
  6923. print(await page.evaluate(\"1 + 2\")) # prints \"3\"
  6924. x = 10
  6925. print(await page.evaluate(f\"1 + {x}\")) # prints \"11\"
  6926. ```
  6927. `ElementHandle` instances can be passed as an argument to the `page.evaluate()`:
  6928. ```py
  6929. body_handle = await page.evaluate(\"document.body\")
  6930. html = await page.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
  6931. await body_handle.dispose()
  6932. ```
  6933. Parameters
  6934. ----------
  6935. expression : str
  6936. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  6937. function is automatically invoked.
  6938. arg : Union[Any, None]
  6939. Optional argument to pass to `expression`.
  6940. Returns
  6941. -------
  6942. Any
  6943. """
  6944. return mapping.from_maybe_impl(
  6945. await self._impl_obj.evaluate(
  6946. expression=expression, arg=mapping.to_impl(arg)
  6947. )
  6948. )
  6949. async def evaluate_handle(
  6950. self, expression: str, arg: typing.Optional[typing.Any] = None
  6951. ) -> "JSHandle":
  6952. """Page.evaluate_handle
  6953. Returns the value of the `expression` invocation as a `JSHandle`.
  6954. The only difference between `page.evaluate()` and `page.evaluate_handle()` is that
  6955. `page.evaluate_handle()` returns `JSHandle`.
  6956. If the function passed to the `page.evaluate_handle()` returns a [Promise], then
  6957. `page.evaluate_handle()` would wait for the promise to resolve and return its value.
  6958. **Usage**
  6959. ```py
  6960. a_window_handle = await page.evaluate_handle(\"Promise.resolve(window)\")
  6961. a_window_handle # handle for the window object.
  6962. ```
  6963. A string can also be passed in instead of a function:
  6964. ```py
  6965. a_handle = await page.evaluate_handle(\"document\") # handle for the \"document\"
  6966. ```
  6967. `JSHandle` instances can be passed as an argument to the `page.evaluate_handle()`:
  6968. ```py
  6969. a_handle = await page.evaluate_handle(\"document.body\")
  6970. result_handle = await page.evaluate_handle(\"body => body.innerHTML\", a_handle)
  6971. print(await result_handle.json_value())
  6972. await result_handle.dispose()
  6973. ```
  6974. Parameters
  6975. ----------
  6976. expression : str
  6977. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  6978. function is automatically invoked.
  6979. arg : Union[Any, None]
  6980. Optional argument to pass to `expression`.
  6981. Returns
  6982. -------
  6983. JSHandle
  6984. """
  6985. return mapping.from_impl(
  6986. await self._impl_obj.evaluate_handle(
  6987. expression=expression, arg=mapping.to_impl(arg)
  6988. )
  6989. )
  6990. async def eval_on_selector(
  6991. self,
  6992. selector: str,
  6993. expression: str,
  6994. arg: typing.Optional[typing.Any] = None,
  6995. *,
  6996. strict: typing.Optional[bool] = None,
  6997. ) -> typing.Any:
  6998. """Page.eval_on_selector
  6999. The method finds an element matching the specified selector within the page and passes it as a first argument to
  7000. `expression`. If no elements match the selector, the method throws an error. Returns the value of `expression`.
  7001. If `expression` returns a [Promise], then `page.eval_on_selector()` would wait for the promise to resolve and
  7002. return its value.
  7003. **Usage**
  7004. ```py
  7005. search_value = await page.eval_on_selector(\"#search\", \"el => el.value\")
  7006. preload_href = await page.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
  7007. html = await page.eval_on_selector(\".main-container\", \"(e, suffix) => e.outer_html + suffix\", \"hello\")
  7008. ```
  7009. Parameters
  7010. ----------
  7011. selector : str
  7012. A selector to query for.
  7013. expression : str
  7014. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7015. function is automatically invoked.
  7016. arg : Union[Any, None]
  7017. Optional argument to pass to `expression`.
  7018. strict : Union[bool, None]
  7019. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  7020. element, the call throws an exception.
  7021. Returns
  7022. -------
  7023. Any
  7024. """
  7025. return mapping.from_maybe_impl(
  7026. await self._impl_obj.eval_on_selector(
  7027. selector=selector,
  7028. expression=expression,
  7029. arg=mapping.to_impl(arg),
  7030. strict=strict,
  7031. )
  7032. )
  7033. async def eval_on_selector_all(
  7034. self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
  7035. ) -> typing.Any:
  7036. """Page.eval_on_selector_all
  7037. The method finds all elements matching the specified selector within the page and passes an array of matched
  7038. elements as a first argument to `expression`. Returns the result of `expression` invocation.
  7039. If `expression` returns a [Promise], then `page.eval_on_selector_all()` would wait for the promise to resolve
  7040. and return its value.
  7041. **Usage**
  7042. ```py
  7043. div_counts = await page.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
  7044. ```
  7045. Parameters
  7046. ----------
  7047. selector : str
  7048. A selector to query for.
  7049. expression : str
  7050. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  7051. function is automatically invoked.
  7052. arg : Union[Any, None]
  7053. Optional argument to pass to `expression`.
  7054. Returns
  7055. -------
  7056. Any
  7057. """
  7058. return mapping.from_maybe_impl(
  7059. await self._impl_obj.eval_on_selector_all(
  7060. selector=selector, expression=expression, arg=mapping.to_impl(arg)
  7061. )
  7062. )
  7063. async def add_script_tag(
  7064. self,
  7065. *,
  7066. url: typing.Optional[str] = None,
  7067. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7068. content: typing.Optional[str] = None,
  7069. type: typing.Optional[str] = None,
  7070. ) -> "ElementHandle":
  7071. """Page.add_script_tag
  7072. Adds a `<script>` tag into the page with the desired url or content. Returns the added tag when the script's onload
  7073. fires or when the script content was injected into frame.
  7074. Parameters
  7075. ----------
  7076. url : Union[str, None]
  7077. URL of a script to be added.
  7078. path : Union[pathlib.Path, str, None]
  7079. Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
  7080. to the current working directory.
  7081. content : Union[str, None]
  7082. Raw JavaScript content to be injected into frame.
  7083. type : Union[str, None]
  7084. Script type. Use 'module' in order to load a JavaScript ES6 module. See
  7085. [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
  7086. Returns
  7087. -------
  7088. ElementHandle
  7089. """
  7090. return mapping.from_impl(
  7091. await self._impl_obj.add_script_tag(
  7092. url=url, path=path, content=content, type=type
  7093. )
  7094. )
  7095. async def add_style_tag(
  7096. self,
  7097. *,
  7098. url: typing.Optional[str] = None,
  7099. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7100. content: typing.Optional[str] = None,
  7101. ) -> "ElementHandle":
  7102. """Page.add_style_tag
  7103. Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
  7104. content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
  7105. Parameters
  7106. ----------
  7107. url : Union[str, None]
  7108. URL of the `<link>` tag.
  7109. path : Union[pathlib.Path, str, None]
  7110. Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
  7111. current working directory.
  7112. content : Union[str, None]
  7113. Raw CSS content to be injected into frame.
  7114. Returns
  7115. -------
  7116. ElementHandle
  7117. """
  7118. return mapping.from_impl(
  7119. await self._impl_obj.add_style_tag(url=url, path=path, content=content)
  7120. )
  7121. async def expose_function(self, name: str, callback: typing.Callable) -> None:
  7122. """Page.expose_function
  7123. The method adds a function called `name` on the `window` object of every frame in the page. When called, the
  7124. function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  7125. If the `callback` returns a [Promise], it will be awaited.
  7126. See `browser_context.expose_function()` for context-wide exposed function.
  7127. **NOTE** Functions installed via `page.expose_function()` survive navigations.
  7128. **Usage**
  7129. An example of adding a `sha256` function to the page:
  7130. ```py
  7131. import asyncio
  7132. import hashlib
  7133. from playwright.async_api import async_playwright, Playwright
  7134. def sha256(text):
  7135. m = hashlib.sha256()
  7136. m.update(bytes(text, \"utf8\"))
  7137. return m.hexdigest()
  7138. async def run(playwright: Playwright):
  7139. webkit = playwright.webkit
  7140. browser = await webkit.launch(headless=False)
  7141. page = await browser.new_page()
  7142. await page.expose_function(\"sha256\", sha256)
  7143. await page.set_content(\"\"\"
  7144. <script>
  7145. async function onClick() {
  7146. document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  7147. }
  7148. </script>
  7149. <button onclick=\"onClick()\">Click me</button>
  7150. <div></div>
  7151. \"\"\")
  7152. await page.click(\"button\")
  7153. async def main():
  7154. async with async_playwright() as playwright:
  7155. await run(playwright)
  7156. asyncio.run(main())
  7157. ```
  7158. Parameters
  7159. ----------
  7160. name : str
  7161. Name of the function on the window object
  7162. callback : Callable
  7163. Callback function which will be called in Playwright's context.
  7164. """
  7165. return mapping.from_maybe_impl(
  7166. await self._impl_obj.expose_function(
  7167. name=name, callback=self._wrap_handler(callback)
  7168. )
  7169. )
  7170. async def expose_binding(
  7171. self,
  7172. name: str,
  7173. callback: typing.Callable,
  7174. *,
  7175. handle: typing.Optional[bool] = None,
  7176. ) -> None:
  7177. """Page.expose_binding
  7178. The method adds a function called `name` on the `window` object of every frame in this page. When called, the
  7179. function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the
  7180. `callback` returns a [Promise], it will be awaited.
  7181. The first argument of the `callback` function contains information about the caller: `{ browserContext:
  7182. BrowserContext, page: Page, frame: Frame }`.
  7183. See `browser_context.expose_binding()` for the context-wide version.
  7184. **NOTE** Functions installed via `page.expose_binding()` survive navigations.
  7185. **Usage**
  7186. An example of exposing page URL to all frames in a page:
  7187. ```py
  7188. import asyncio
  7189. from playwright.async_api import async_playwright, Playwright
  7190. async def run(playwright: Playwright):
  7191. webkit = playwright.webkit
  7192. browser = await webkit.launch(headless=False)
  7193. context = await browser.new_context()
  7194. page = await context.new_page()
  7195. await page.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
  7196. await page.set_content(\"\"\"
  7197. <script>
  7198. async function onClick() {
  7199. document.querySelector('div').textContent = await window.pageURL();
  7200. }
  7201. </script>
  7202. <button onclick=\"onClick()\">Click me</button>
  7203. <div></div>
  7204. \"\"\")
  7205. await page.click(\"button\")
  7206. async def main():
  7207. async with async_playwright() as playwright:
  7208. await run(playwright)
  7209. asyncio.run(main())
  7210. ```
  7211. Parameters
  7212. ----------
  7213. name : str
  7214. Name of the function on the window object.
  7215. callback : Callable
  7216. Callback function that will be called in the Playwright's context.
  7217. handle : Union[bool, None]
  7218. Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
  7219. supported. When passing by value, multiple arguments are supported.
  7220. Deprecated: This option will be removed in the future.
  7221. """
  7222. return mapping.from_maybe_impl(
  7223. await self._impl_obj.expose_binding(
  7224. name=name, callback=self._wrap_handler(callback), handle=handle
  7225. )
  7226. )
  7227. async def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
  7228. """Page.set_extra_http_headers
  7229. The extra HTTP headers will be sent with every request the page initiates.
  7230. **NOTE** `page.set_extra_http_headers()` does not guarantee the order of headers in the outgoing requests.
  7231. Parameters
  7232. ----------
  7233. headers : Dict[str, str]
  7234. An object containing additional HTTP headers to be sent with every request. All header values must be strings.
  7235. """
  7236. return mapping.from_maybe_impl(
  7237. await self._impl_obj.set_extra_http_headers(
  7238. headers=mapping.to_impl(headers)
  7239. )
  7240. )
  7241. async def content(self) -> str:
  7242. """Page.content
  7243. Gets the full HTML contents of the page, including the doctype.
  7244. Returns
  7245. -------
  7246. str
  7247. """
  7248. return mapping.from_maybe_impl(await self._impl_obj.content())
  7249. async def set_content(
  7250. self,
  7251. html: str,
  7252. *,
  7253. timeout: typing.Optional[float] = None,
  7254. wait_until: typing.Optional[
  7255. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7256. ] = None,
  7257. ) -> None:
  7258. """Page.set_content
  7259. This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
  7260. inheriting all its specific characteristics and behaviors.
  7261. Parameters
  7262. ----------
  7263. html : str
  7264. HTML markup to assign to the page.
  7265. timeout : Union[float, None]
  7266. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7267. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7268. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7269. `page.set_default_timeout()` methods.
  7270. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7271. When to consider operation succeeded, defaults to `load`. Events can be either:
  7272. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7273. - `'load'` - consider operation to be finished when the `load` event is fired.
  7274. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7275. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7276. - `'commit'` - consider operation to be finished when network response is received and the document started
  7277. loading.
  7278. """
  7279. return mapping.from_maybe_impl(
  7280. await self._impl_obj.set_content(
  7281. html=html, timeout=timeout, waitUntil=wait_until
  7282. )
  7283. )
  7284. async def goto(
  7285. self,
  7286. url: str,
  7287. *,
  7288. timeout: typing.Optional[float] = None,
  7289. wait_until: typing.Optional[
  7290. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7291. ] = None,
  7292. referer: typing.Optional[str] = None,
  7293. ) -> typing.Optional["Response"]:
  7294. """Page.goto
  7295. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first
  7296. non-redirect response.
  7297. The method will throw an error if:
  7298. - there's an SSL error (e.g. in case of self-signed certificates).
  7299. - target URL is invalid.
  7300. - the `timeout` is exceeded during navigation.
  7301. - the remote server does not respond or is unreachable.
  7302. - the main resource failed to load.
  7303. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
  7304. \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
  7305. `response.status()`.
  7306. **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
  7307. to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
  7308. **NOTE** Headless mode doesn't support navigation to a PDF document. See the
  7309. [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
  7310. Parameters
  7311. ----------
  7312. url : str
  7313. URL to navigate page to. The url should include scheme, e.g. `https://`. When a `baseURL` via the context options
  7314. was provided and the passed URL is a path, it gets merged via the
  7315. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  7316. timeout : Union[float, None]
  7317. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7318. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7319. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7320. `page.set_default_timeout()` methods.
  7321. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7322. When to consider operation succeeded, defaults to `load`. Events can be either:
  7323. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7324. - `'load'` - consider operation to be finished when the `load` event is fired.
  7325. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7326. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7327. - `'commit'` - consider operation to be finished when network response is received and the document started
  7328. loading.
  7329. referer : Union[str, None]
  7330. Referer header value. If provided it will take preference over the referer header value set by
  7331. `page.set_extra_http_headers()`.
  7332. Returns
  7333. -------
  7334. Union[Response, None]
  7335. """
  7336. return mapping.from_impl_nullable(
  7337. await self._impl_obj.goto(
  7338. url=url, timeout=timeout, waitUntil=wait_until, referer=referer
  7339. )
  7340. )
  7341. async def reload(
  7342. self,
  7343. *,
  7344. timeout: typing.Optional[float] = None,
  7345. wait_until: typing.Optional[
  7346. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7347. ] = None,
  7348. ) -> typing.Optional["Response"]:
  7349. """Page.reload
  7350. This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the
  7351. main resource response. In case of multiple redirects, the navigation will resolve with the response of the last
  7352. redirect.
  7353. Parameters
  7354. ----------
  7355. timeout : Union[float, None]
  7356. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7357. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7358. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7359. `page.set_default_timeout()` methods.
  7360. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7361. When to consider operation succeeded, defaults to `load`. Events can be either:
  7362. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7363. - `'load'` - consider operation to be finished when the `load` event is fired.
  7364. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7365. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7366. - `'commit'` - consider operation to be finished when network response is received and the document started
  7367. loading.
  7368. Returns
  7369. -------
  7370. Union[Response, None]
  7371. """
  7372. return mapping.from_impl_nullable(
  7373. await self._impl_obj.reload(timeout=timeout, waitUntil=wait_until)
  7374. )
  7375. async def wait_for_load_state(
  7376. self,
  7377. state: typing.Optional[
  7378. Literal["domcontentloaded", "load", "networkidle"]
  7379. ] = None,
  7380. *,
  7381. timeout: typing.Optional[float] = None,
  7382. ) -> None:
  7383. """Page.wait_for_load_state
  7384. Returns when the required load state has been reached.
  7385. This resolves when the page reaches a required load state, `load` by default. The navigation must have been
  7386. committed when this method is called. If current document has already reached the required state, resolves
  7387. immediately.
  7388. **NOTE** Most of the time, this method is not needed because Playwright
  7389. [auto-waits before every action](https://playwright.dev/python/docs/actionability).
  7390. **Usage**
  7391. ```py
  7392. await page.get_by_role(\"button\").click() # click triggers navigation.
  7393. await page.wait_for_load_state() # the promise resolves after \"load\" event.
  7394. ```
  7395. ```py
  7396. async with page.expect_popup() as page_info:
  7397. await page.get_by_role(\"button\").click() # click triggers a popup.
  7398. popup = await page_info.value
  7399. # Wait for the \"DOMContentLoaded\" event.
  7400. await popup.wait_for_load_state(\"domcontentloaded\")
  7401. print(await popup.title()) # popup is ready to use.
  7402. ```
  7403. Parameters
  7404. ----------
  7405. state : Union["domcontentloaded", "load", "networkidle", None]
  7406. Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
  7407. document, the method resolves immediately. Can be one of:
  7408. - `'load'` - wait for the `load` event to be fired.
  7409. - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
  7410. - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
  7411. this method for testing, rely on web assertions to assess readiness instead.
  7412. timeout : Union[float, None]
  7413. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7414. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7415. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7416. `page.set_default_timeout()` methods.
  7417. """
  7418. return mapping.from_maybe_impl(
  7419. await self._impl_obj.wait_for_load_state(state=state, timeout=timeout)
  7420. )
  7421. async def wait_for_url(
  7422. self,
  7423. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7424. *,
  7425. wait_until: typing.Optional[
  7426. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7427. ] = None,
  7428. timeout: typing.Optional[float] = None,
  7429. ) -> None:
  7430. """Page.wait_for_url
  7431. Waits for the main frame to navigate to the given URL.
  7432. **Usage**
  7433. ```py
  7434. await page.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
  7435. await page.wait_for_url(\"**/target.html\")
  7436. ```
  7437. Parameters
  7438. ----------
  7439. url : Union[Callable[[str], bool], Pattern[str], str]
  7440. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  7441. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  7442. equal to the string.
  7443. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7444. When to consider operation succeeded, defaults to `load`. Events can be either:
  7445. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7446. - `'load'` - consider operation to be finished when the `load` event is fired.
  7447. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7448. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7449. - `'commit'` - consider operation to be finished when network response is received and the document started
  7450. loading.
  7451. timeout : Union[float, None]
  7452. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7453. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7454. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7455. `page.set_default_timeout()` methods.
  7456. """
  7457. return mapping.from_maybe_impl(
  7458. await self._impl_obj.wait_for_url(
  7459. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  7460. )
  7461. )
  7462. async def wait_for_event(
  7463. self,
  7464. event: str,
  7465. predicate: typing.Optional[typing.Callable] = None,
  7466. *,
  7467. timeout: typing.Optional[float] = None,
  7468. ) -> typing.Any:
  7469. """Page.wait_for_event
  7470. **NOTE** In most cases, you should use `page.expect_event()`.
  7471. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  7472. and waits for `predicate(event)` to return a truthy value. Will throw an error if the page is closed before the
  7473. `event` is fired.
  7474. Parameters
  7475. ----------
  7476. event : str
  7477. Event name, same one typically passed into `*.on(event)`.
  7478. predicate : Union[Callable, None]
  7479. Receives the event data and resolves to truthy value when the waiting should resolve.
  7480. timeout : Union[float, None]
  7481. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  7482. default value can be changed by using the `browser_context.set_default_timeout()`.
  7483. Returns
  7484. -------
  7485. Any
  7486. """
  7487. return mapping.from_maybe_impl(
  7488. await self._impl_obj.wait_for_event(
  7489. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  7490. )
  7491. )
  7492. async def go_back(
  7493. self,
  7494. *,
  7495. timeout: typing.Optional[float] = None,
  7496. wait_until: typing.Optional[
  7497. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7498. ] = None,
  7499. ) -> typing.Optional["Response"]:
  7500. """Page.go_back
  7501. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  7502. the last redirect. If cannot go back, returns `null`.
  7503. Navigate to the previous page in history.
  7504. Parameters
  7505. ----------
  7506. timeout : Union[float, None]
  7507. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7508. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7509. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7510. `page.set_default_timeout()` methods.
  7511. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7512. When to consider operation succeeded, defaults to `load`. Events can be either:
  7513. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7514. - `'load'` - consider operation to be finished when the `load` event is fired.
  7515. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7516. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7517. - `'commit'` - consider operation to be finished when network response is received and the document started
  7518. loading.
  7519. Returns
  7520. -------
  7521. Union[Response, None]
  7522. """
  7523. return mapping.from_impl_nullable(
  7524. await self._impl_obj.go_back(timeout=timeout, waitUntil=wait_until)
  7525. )
  7526. async def go_forward(
  7527. self,
  7528. *,
  7529. timeout: typing.Optional[float] = None,
  7530. wait_until: typing.Optional[
  7531. Literal["commit", "domcontentloaded", "load", "networkidle"]
  7532. ] = None,
  7533. ) -> typing.Optional["Response"]:
  7534. """Page.go_forward
  7535. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
  7536. the last redirect. If cannot go forward, returns `null`.
  7537. Navigate to the next page in history.
  7538. Parameters
  7539. ----------
  7540. timeout : Union[float, None]
  7541. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  7542. be changed by using the `browser_context.set_default_navigation_timeout()`,
  7543. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  7544. `page.set_default_timeout()` methods.
  7545. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  7546. When to consider operation succeeded, defaults to `load`. Events can be either:
  7547. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  7548. - `'load'` - consider operation to be finished when the `load` event is fired.
  7549. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  7550. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  7551. - `'commit'` - consider operation to be finished when network response is received and the document started
  7552. loading.
  7553. Returns
  7554. -------
  7555. Union[Response, None]
  7556. """
  7557. return mapping.from_impl_nullable(
  7558. await self._impl_obj.go_forward(timeout=timeout, waitUntil=wait_until)
  7559. )
  7560. async def request_gc(self) -> None:
  7561. """Page.request_gc
  7562. Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will
  7563. be collected.
  7564. This is useful to help detect memory leaks. For example, if your page has a large object `'suspect'` that might be
  7565. leaked, you can check that it does not leak by using a
  7566. [`WeakRef`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef).
  7567. ```py
  7568. # 1. In your page, save a WeakRef for the \"suspect\".
  7569. await page.evaluate(\"globalThis.suspectWeakRef = new WeakRef(suspect)\")
  7570. # 2. Request garbage collection.
  7571. await page.request_gc()
  7572. # 3. Check that weak ref does not deref to the original object.
  7573. assert await page.evaluate(\"!globalThis.suspectWeakRef.deref()\")
  7574. ```
  7575. """
  7576. return mapping.from_maybe_impl(await self._impl_obj.request_gc())
  7577. async def emulate_media(
  7578. self,
  7579. *,
  7580. media: typing.Optional[Literal["null", "print", "screen"]] = None,
  7581. color_scheme: typing.Optional[
  7582. Literal["dark", "light", "no-preference", "null"]
  7583. ] = None,
  7584. reduced_motion: typing.Optional[
  7585. Literal["no-preference", "null", "reduce"]
  7586. ] = None,
  7587. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  7588. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  7589. ) -> None:
  7590. """Page.emulate_media
  7591. This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media
  7592. feature, using the `colorScheme` argument.
  7593. **Usage**
  7594. ```py
  7595. await page.evaluate(\"matchMedia('screen').matches\")
  7596. # → True
  7597. await page.evaluate(\"matchMedia('print').matches\")
  7598. # → False
  7599. await page.emulate_media(media=\"print\")
  7600. await page.evaluate(\"matchMedia('screen').matches\")
  7601. # → False
  7602. await page.evaluate(\"matchMedia('print').matches\")
  7603. # → True
  7604. await page.emulate_media()
  7605. await page.evaluate(\"matchMedia('screen').matches\")
  7606. # → True
  7607. await page.evaluate(\"matchMedia('print').matches\")
  7608. # → False
  7609. ```
  7610. ```py
  7611. await page.emulate_media(color_scheme=\"dark\")
  7612. await page.evaluate(\"matchMedia('(prefers-color-scheme: dark)').matches\")
  7613. # → True
  7614. await page.evaluate(\"matchMedia('(prefers-color-scheme: light)').matches\")
  7615. # → False
  7616. ```
  7617. Parameters
  7618. ----------
  7619. media : Union["null", "print", "screen", None]
  7620. Changes the CSS media type of the page. The only allowed values are `'Screen'`, `'Print'` and `'Null'`. Passing
  7621. `'Null'` disables CSS media emulation.
  7622. color_scheme : Union["dark", "light", "no-preference", "null", None]
  7623. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  7624. media feature, supported values are `'light'` and `'dark'`. Passing `'Null'` disables color scheme emulation.
  7625. `'no-preference'` is deprecated.
  7626. reduced_motion : Union["no-preference", "null", "reduce", None]
  7627. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. Passing
  7628. `null` disables reduced motion emulation.
  7629. forced_colors : Union["active", "none", "null", None]
  7630. contrast : Union["more", "no-preference", "null", None]
  7631. """
  7632. return mapping.from_maybe_impl(
  7633. await self._impl_obj.emulate_media(
  7634. media=media,
  7635. colorScheme=color_scheme,
  7636. reducedMotion=reduced_motion,
  7637. forcedColors=forced_colors,
  7638. contrast=contrast,
  7639. )
  7640. )
  7641. async def set_viewport_size(self, viewport_size: ViewportSize) -> None:
  7642. """Page.set_viewport_size
  7643. In the case of multiple pages in a single browser, each page can have its own viewport size. However,
  7644. `browser.new_context()` allows to set viewport size (and more) for all pages in the context at once.
  7645. `page.set_viewport_size()` will resize the page. A lot of websites don't expect phones to change size, so you
  7646. should set the viewport size before navigating to the page. `page.set_viewport_size()` will also reset
  7647. `screen` size, use `browser.new_context()` with `screen` and `viewport` parameters if you need better
  7648. control of these properties.
  7649. **Usage**
  7650. ```py
  7651. page = await browser.new_page()
  7652. await page.set_viewport_size({\"width\": 640, \"height\": 480})
  7653. await page.goto(\"https://example.com\")
  7654. ```
  7655. Parameters
  7656. ----------
  7657. viewport_size : {width: int, height: int}
  7658. """
  7659. return mapping.from_maybe_impl(
  7660. await self._impl_obj.set_viewport_size(viewportSize=viewport_size)
  7661. )
  7662. async def bring_to_front(self) -> None:
  7663. """Page.bring_to_front
  7664. Brings page to front (activates tab).
  7665. """
  7666. return mapping.from_maybe_impl(await self._impl_obj.bring_to_front())
  7667. async def add_init_script(
  7668. self,
  7669. script: typing.Optional[str] = None,
  7670. *,
  7671. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7672. ) -> None:
  7673. """Page.add_init_script
  7674. Adds a script which would be evaluated in one of the following scenarios:
  7675. - Whenever the page is navigated.
  7676. - Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the
  7677. newly attached frame.
  7678. The script is evaluated after the document was created but before any of its scripts were run. This is useful to
  7679. amend the JavaScript environment, e.g. to seed `Math.random`.
  7680. **Usage**
  7681. An example of overriding `Math.random` before the page loads:
  7682. ```py
  7683. # in your playwright script, assuming the preload.js file is in same directory
  7684. await page.add_init_script(path=\"./preload.js\")
  7685. ```
  7686. **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
  7687. `page.add_init_script()` is not defined.
  7688. Parameters
  7689. ----------
  7690. script : Union[str, None]
  7691. Script to be evaluated in all pages in the browser context. Optional.
  7692. path : Union[pathlib.Path, str, None]
  7693. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  7694. directory. Optional.
  7695. """
  7696. return mapping.from_maybe_impl(
  7697. await self._impl_obj.add_init_script(script=script, path=path)
  7698. )
  7699. async def route(
  7700. self,
  7701. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7702. handler: typing.Union[
  7703. typing.Callable[["Route"], typing.Any],
  7704. typing.Callable[["Route", "Request"], typing.Any],
  7705. ],
  7706. *,
  7707. times: typing.Optional[int] = None,
  7708. ) -> None:
  7709. """Page.route
  7710. Routing provides the capability to modify network requests that are made by a page.
  7711. Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or
  7712. aborted.
  7713. **NOTE** The handler will only be called for the first url if the response is a redirect.
  7714. **NOTE** `page.route()` will not intercept requests intercepted by Service Worker. See
  7715. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  7716. using request interception by setting `serviceWorkers` to `'block'`.
  7717. **NOTE** `page.route()` will not intercept the first request of a popup page. Use
  7718. `browser_context.route()` instead.
  7719. **Usage**
  7720. An example of a naive handler that aborts all image requests:
  7721. ```py
  7722. page = await browser.new_page()
  7723. await page.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
  7724. await page.goto(\"https://example.com\")
  7725. await browser.close()
  7726. ```
  7727. or the same snippet using a regex pattern instead:
  7728. ```py
  7729. page = await browser.new_page()
  7730. await page.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
  7731. await page.goto(\"https://example.com\")
  7732. await browser.close()
  7733. ```
  7734. It is possible to examine the request to decide the route action. For example, mocking all requests that contain
  7735. some post data, and leaving all other requests as is:
  7736. ```py
  7737. async def handle_route(route: Route):
  7738. if (\"my-string\" in route.request.post_data):
  7739. await route.fulfill(body=\"mocked-data\")
  7740. else:
  7741. await route.continue_()
  7742. await page.route(\"/api/**\", handle_route)
  7743. ```
  7744. Page routes take precedence over browser context routes (set up with `browser_context.route()`) when request
  7745. matches both handlers.
  7746. To remove a route with its handler you can use `page.unroute()`.
  7747. **NOTE** Enabling routing disables http cache.
  7748. Parameters
  7749. ----------
  7750. url : Union[Callable[[str], bool], Pattern[str], str]
  7751. A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
  7752. the context options and the provided URL is a string that does not start with `*`, it is resolved using the
  7753. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  7754. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
  7755. handler function to route the request.
  7756. times : Union[int, None]
  7757. How often a route should be used. By default it will be used every time.
  7758. """
  7759. return mapping.from_maybe_impl(
  7760. await self._impl_obj.route(
  7761. url=self._wrap_handler(url),
  7762. handler=self._wrap_handler(handler),
  7763. times=times,
  7764. )
  7765. )
  7766. async def unroute(
  7767. self,
  7768. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7769. handler: typing.Optional[
  7770. typing.Union[
  7771. typing.Callable[["Route"], typing.Any],
  7772. typing.Callable[["Route", "Request"], typing.Any],
  7773. ]
  7774. ] = None,
  7775. ) -> None:
  7776. """Page.unroute
  7777. Removes a route created with `page.route()`. When `handler` is not specified, removes all routes for the
  7778. `url`.
  7779. Parameters
  7780. ----------
  7781. url : Union[Callable[[str], bool], Pattern[str], str]
  7782. A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
  7783. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
  7784. Optional handler function to route the request.
  7785. """
  7786. return mapping.from_maybe_impl(
  7787. await self._impl_obj.unroute(
  7788. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  7789. )
  7790. )
  7791. async def route_web_socket(
  7792. self,
  7793. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  7794. handler: typing.Callable[["WebSocketRoute"], typing.Any],
  7795. ) -> None:
  7796. """Page.route_web_socket
  7797. This method allows to modify websocket connections that are made by the page.
  7798. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
  7799. method before navigating the page.
  7800. **Usage**
  7801. Below is an example of a simple mock that responds to a single message. See `WebSocketRoute` for more details and
  7802. examples.
  7803. ```py
  7804. def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  7805. if message == \"request\":
  7806. ws.send(\"response\")
  7807. def handler(ws: WebSocketRoute):
  7808. ws.on_message(lambda message: message_handler(ws, message))
  7809. await page.route_web_socket(\"/ws\", handler)
  7810. ```
  7811. Parameters
  7812. ----------
  7813. url : Union[Callable[[str], bool], Pattern[str], str]
  7814. Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
  7815. `baseURL` context option.
  7816. handler : Callable[[WebSocketRoute], Any]
  7817. Handler function to route the WebSocket.
  7818. """
  7819. return mapping.from_maybe_impl(
  7820. await self._impl_obj.route_web_socket(
  7821. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  7822. )
  7823. )
  7824. async def unroute_all(
  7825. self,
  7826. *,
  7827. behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
  7828. ) -> None:
  7829. """Page.unroute_all
  7830. Removes all routes created with `page.route()` and `page.route_from_har()`.
  7831. Parameters
  7832. ----------
  7833. behavior : Union["default", "ignoreErrors", "wait", None]
  7834. Specifies whether to wait for already running handlers and what to do if they throw errors:
  7835. - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
  7836. result in unhandled error
  7837. - `'wait'` - wait for current handler calls (if any) to finish
  7838. - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
  7839. after unrouting are silently caught
  7840. """
  7841. return mapping.from_maybe_impl(
  7842. await self._impl_obj.unroute_all(behavior=behavior)
  7843. )
  7844. async def route_from_har(
  7845. self,
  7846. har: typing.Union[pathlib.Path, str],
  7847. *,
  7848. url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  7849. not_found: typing.Optional[Literal["abort", "fallback"]] = None,
  7850. update: typing.Optional[bool] = None,
  7851. update_content: typing.Optional[Literal["attach", "embed"]] = None,
  7852. update_mode: typing.Optional[Literal["full", "minimal"]] = None,
  7853. ) -> None:
  7854. """Page.route_from_har
  7855. If specified the network requests that are made in the page will be served from the HAR file. Read more about
  7856. [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
  7857. Playwright will not serve requests intercepted by Service Worker from the HAR file. See
  7858. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  7859. using request interception by setting `serviceWorkers` to `'block'`.
  7860. Parameters
  7861. ----------
  7862. har : Union[pathlib.Path, str]
  7863. Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
  7864. relative path, then it is resolved relative to the current working directory.
  7865. url : Union[Pattern[str], str, None]
  7866. A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
  7867. pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
  7868. not_found : Union["abort", "fallback", None]
  7869. - If set to 'abort' any request not found in the HAR file will be aborted.
  7870. - If set to 'fallback' missing requests will be sent to the network.
  7871. Defaults to abort.
  7872. update : Union[bool, None]
  7873. If specified, updates the given HAR with the actual network information instead of serving from file. The file is
  7874. written to disk when `browser_context.close()` is called.
  7875. update_content : Union["attach", "embed", None]
  7876. Optional setting to control resource content management. If `attach` is specified, resources are persisted as
  7877. separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
  7878. update_mode : Union["full", "minimal", None]
  7879. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  7880. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
  7881. `minimal`.
  7882. """
  7883. return mapping.from_maybe_impl(
  7884. await self._impl_obj.route_from_har(
  7885. har=har,
  7886. url=url,
  7887. notFound=not_found,
  7888. update=update,
  7889. updateContent=update_content,
  7890. updateMode=update_mode,
  7891. )
  7892. )
  7893. async def screenshot(
  7894. self,
  7895. *,
  7896. timeout: typing.Optional[float] = None,
  7897. type: typing.Optional[Literal["jpeg", "png"]] = None,
  7898. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  7899. quality: typing.Optional[int] = None,
  7900. omit_background: typing.Optional[bool] = None,
  7901. full_page: typing.Optional[bool] = None,
  7902. clip: typing.Optional[FloatRect] = None,
  7903. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  7904. caret: typing.Optional[Literal["hide", "initial"]] = None,
  7905. scale: typing.Optional[Literal["css", "device"]] = None,
  7906. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  7907. mask_color: typing.Optional[str] = None,
  7908. style: typing.Optional[str] = None,
  7909. ) -> bytes:
  7910. """Page.screenshot
  7911. Returns the buffer with the captured screenshot.
  7912. Parameters
  7913. ----------
  7914. timeout : Union[float, None]
  7915. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  7916. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  7917. type : Union["jpeg", "png", None]
  7918. Specify screenshot type, defaults to `png`.
  7919. path : Union[pathlib.Path, str, None]
  7920. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  7921. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  7922. won't be saved to the disk.
  7923. quality : Union[int, None]
  7924. The quality of the image, between 0-100. Not applicable to `png` images.
  7925. omit_background : Union[bool, None]
  7926. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  7927. Defaults to `false`.
  7928. full_page : Union[bool, None]
  7929. When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to
  7930. `false`.
  7931. clip : Union[{x: float, y: float, width: float, height: float}, None]
  7932. An object which specifies clipping of the resulting image.
  7933. animations : Union["allow", "disabled", None]
  7934. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  7935. treatment depending on their duration:
  7936. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  7937. - infinite animations are canceled to initial state, and then played over after the screenshot.
  7938. Defaults to `"allow"` that leaves animations untouched.
  7939. caret : Union["hide", "initial", None]
  7940. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  7941. changed. Defaults to `"hide"`.
  7942. scale : Union["css", "device", None]
  7943. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  7944. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  7945. screenshots of high-dpi devices will be twice as large or even larger.
  7946. Defaults to `"device"`.
  7947. mask : Union[Sequence[Locator], None]
  7948. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  7949. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  7950. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  7951. that.
  7952. mask_color : Union[str, None]
  7953. Specify the color of the overlay box for masked elements, in
  7954. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  7955. style : Union[str, None]
  7956. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  7957. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  7958. the Shadow DOM and applies to the inner frames.
  7959. Returns
  7960. -------
  7961. bytes
  7962. """
  7963. return mapping.from_maybe_impl(
  7964. await self._impl_obj.screenshot(
  7965. timeout=timeout,
  7966. type=type,
  7967. path=path,
  7968. quality=quality,
  7969. omitBackground=omit_background,
  7970. fullPage=full_page,
  7971. clip=clip,
  7972. animations=animations,
  7973. caret=caret,
  7974. scale=scale,
  7975. mask=mapping.to_impl(mask),
  7976. maskColor=mask_color,
  7977. style=style,
  7978. )
  7979. )
  7980. async def title(self) -> str:
  7981. """Page.title
  7982. Returns the page's title.
  7983. Returns
  7984. -------
  7985. str
  7986. """
  7987. return mapping.from_maybe_impl(await self._impl_obj.title())
  7988. async def close(
  7989. self,
  7990. *,
  7991. run_before_unload: typing.Optional[bool] = None,
  7992. reason: typing.Optional[str] = None,
  7993. ) -> None:
  7994. """Page.close
  7995. If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If
  7996. `runBeforeUnload` is `true` the method will run unload handlers, but will **not** wait for the page to close.
  7997. By default, `page.close()` **does not** run `beforeunload` handlers.
  7998. **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned and should be handled
  7999. manually via `page.on('dialog')` event.
  8000. Parameters
  8001. ----------
  8002. run_before_unload : Union[bool, None]
  8003. Defaults to `false`. Whether to run the
  8004. [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) page handlers.
  8005. reason : Union[str, None]
  8006. The reason to be reported to the operations interrupted by the page closure.
  8007. """
  8008. return mapping.from_maybe_impl(
  8009. await self._impl_obj.close(runBeforeUnload=run_before_unload, reason=reason)
  8010. )
  8011. def is_closed(self) -> bool:
  8012. """Page.is_closed
  8013. Indicates that the page has been closed.
  8014. Returns
  8015. -------
  8016. bool
  8017. """
  8018. return mapping.from_maybe_impl(self._impl_obj.is_closed())
  8019. async def click(
  8020. self,
  8021. selector: str,
  8022. *,
  8023. modifiers: typing.Optional[
  8024. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8025. ] = None,
  8026. position: typing.Optional[Position] = None,
  8027. delay: typing.Optional[float] = None,
  8028. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  8029. click_count: typing.Optional[int] = None,
  8030. timeout: typing.Optional[float] = None,
  8031. force: typing.Optional[bool] = None,
  8032. no_wait_after: typing.Optional[bool] = None,
  8033. trial: typing.Optional[bool] = None,
  8034. strict: typing.Optional[bool] = None,
  8035. ) -> None:
  8036. """Page.click
  8037. This method clicks an element matching `selector` by performing the following steps:
  8038. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8039. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8040. the element is detached during the checks, the whole action is retried.
  8041. 1. Scroll the element into view if needed.
  8042. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  8043. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  8044. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8045. Passing zero timeout disables this.
  8046. Parameters
  8047. ----------
  8048. selector : str
  8049. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8050. used.
  8051. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8052. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8053. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8054. "Control" on Windows and Linux and to "Meta" on macOS.
  8055. position : Union[{x: float, y: float}, None]
  8056. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8057. the element.
  8058. delay : Union[float, None]
  8059. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  8060. button : Union["left", "middle", "right", None]
  8061. Defaults to `left`.
  8062. click_count : Union[int, None]
  8063. defaults to 1. See [UIEvent.detail].
  8064. timeout : Union[float, None]
  8065. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8066. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8067. force : Union[bool, None]
  8068. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8069. no_wait_after : Union[bool, None]
  8070. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  8071. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  8072. navigating to inaccessible pages. Defaults to `false`.
  8073. Deprecated: This option will default to `true` in the future.
  8074. trial : Union[bool, None]
  8075. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8076. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8077. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8078. are pressed.
  8079. strict : Union[bool, None]
  8080. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8081. element, the call throws an exception.
  8082. """
  8083. return mapping.from_maybe_impl(
  8084. await self._impl_obj.click(
  8085. selector=selector,
  8086. modifiers=mapping.to_impl(modifiers),
  8087. position=position,
  8088. delay=delay,
  8089. button=button,
  8090. clickCount=click_count,
  8091. timeout=timeout,
  8092. force=force,
  8093. noWaitAfter=no_wait_after,
  8094. trial=trial,
  8095. strict=strict,
  8096. )
  8097. )
  8098. async def dblclick(
  8099. self,
  8100. selector: str,
  8101. *,
  8102. modifiers: typing.Optional[
  8103. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8104. ] = None,
  8105. position: typing.Optional[Position] = None,
  8106. delay: typing.Optional[float] = None,
  8107. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  8108. timeout: typing.Optional[float] = None,
  8109. force: typing.Optional[bool] = None,
  8110. no_wait_after: typing.Optional[bool] = None,
  8111. strict: typing.Optional[bool] = None,
  8112. trial: typing.Optional[bool] = None,
  8113. ) -> None:
  8114. """Page.dblclick
  8115. This method double clicks an element matching `selector` by performing the following steps:
  8116. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8117. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8118. the element is detached during the checks, the whole action is retried.
  8119. 1. Scroll the element into view if needed.
  8120. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  8121. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8122. Passing zero timeout disables this.
  8123. **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
  8124. Parameters
  8125. ----------
  8126. selector : str
  8127. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8128. used.
  8129. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8130. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8131. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8132. "Control" on Windows and Linux and to "Meta" on macOS.
  8133. position : Union[{x: float, y: float}, None]
  8134. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8135. the element.
  8136. delay : Union[float, None]
  8137. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  8138. button : Union["left", "middle", "right", None]
  8139. Defaults to `left`.
  8140. timeout : Union[float, None]
  8141. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8142. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8143. force : Union[bool, None]
  8144. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8145. no_wait_after : Union[bool, None]
  8146. This option has no effect.
  8147. Deprecated: This option has no effect.
  8148. strict : Union[bool, None]
  8149. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8150. element, the call throws an exception.
  8151. trial : Union[bool, None]
  8152. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8153. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8154. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8155. are pressed.
  8156. """
  8157. return mapping.from_maybe_impl(
  8158. await self._impl_obj.dblclick(
  8159. selector=selector,
  8160. modifiers=mapping.to_impl(modifiers),
  8161. position=position,
  8162. delay=delay,
  8163. button=button,
  8164. timeout=timeout,
  8165. force=force,
  8166. noWaitAfter=no_wait_after,
  8167. strict=strict,
  8168. trial=trial,
  8169. )
  8170. )
  8171. async def tap(
  8172. self,
  8173. selector: str,
  8174. *,
  8175. modifiers: typing.Optional[
  8176. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8177. ] = None,
  8178. position: typing.Optional[Position] = None,
  8179. timeout: typing.Optional[float] = None,
  8180. force: typing.Optional[bool] = None,
  8181. no_wait_after: typing.Optional[bool] = None,
  8182. strict: typing.Optional[bool] = None,
  8183. trial: typing.Optional[bool] = None,
  8184. ) -> None:
  8185. """Page.tap
  8186. This method taps an element matching `selector` by performing the following steps:
  8187. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8188. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8189. the element is detached during the checks, the whole action is retried.
  8190. 1. Scroll the element into view if needed.
  8191. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  8192. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8193. Passing zero timeout disables this.
  8194. **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
  8195. Parameters
  8196. ----------
  8197. selector : str
  8198. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8199. used.
  8200. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8201. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8202. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8203. "Control" on Windows and Linux and to "Meta" on macOS.
  8204. position : Union[{x: float, y: float}, None]
  8205. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8206. the element.
  8207. timeout : Union[float, None]
  8208. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8209. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8210. force : Union[bool, None]
  8211. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8212. no_wait_after : Union[bool, None]
  8213. This option has no effect.
  8214. Deprecated: This option has no effect.
  8215. strict : Union[bool, None]
  8216. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8217. element, the call throws an exception.
  8218. trial : Union[bool, None]
  8219. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8220. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8221. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8222. are pressed.
  8223. """
  8224. return mapping.from_maybe_impl(
  8225. await self._impl_obj.tap(
  8226. selector=selector,
  8227. modifiers=mapping.to_impl(modifiers),
  8228. position=position,
  8229. timeout=timeout,
  8230. force=force,
  8231. noWaitAfter=no_wait_after,
  8232. strict=strict,
  8233. trial=trial,
  8234. )
  8235. )
  8236. async def fill(
  8237. self,
  8238. selector: str,
  8239. value: str,
  8240. *,
  8241. timeout: typing.Optional[float] = None,
  8242. no_wait_after: typing.Optional[bool] = None,
  8243. strict: typing.Optional[bool] = None,
  8244. force: typing.Optional[bool] = None,
  8245. ) -> None:
  8246. """Page.fill
  8247. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
  8248. focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
  8249. to clear the input field.
  8250. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  8251. error. However, if the element is inside the `<label>` element that has an associated
  8252. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  8253. instead.
  8254. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  8255. Parameters
  8256. ----------
  8257. selector : str
  8258. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8259. used.
  8260. value : str
  8261. Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
  8262. timeout : Union[float, None]
  8263. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8264. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8265. no_wait_after : Union[bool, None]
  8266. This option has no effect.
  8267. Deprecated: This option has no effect.
  8268. strict : Union[bool, None]
  8269. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8270. element, the call throws an exception.
  8271. force : Union[bool, None]
  8272. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8273. """
  8274. return mapping.from_maybe_impl(
  8275. await self._impl_obj.fill(
  8276. selector=selector,
  8277. value=value,
  8278. timeout=timeout,
  8279. noWaitAfter=no_wait_after,
  8280. strict=strict,
  8281. force=force,
  8282. )
  8283. )
  8284. def locator(
  8285. self,
  8286. selector: str,
  8287. *,
  8288. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8289. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8290. has: typing.Optional["Locator"] = None,
  8291. has_not: typing.Optional["Locator"] = None,
  8292. ) -> "Locator":
  8293. """Page.locator
  8294. The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
  8295. to the element immediately before performing an action, so a series of actions on the same locator can in fact be
  8296. performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
  8297. [Learn more about locators](https://playwright.dev/python/docs/locators).
  8298. Parameters
  8299. ----------
  8300. selector : str
  8301. A selector to use when resolving DOM element.
  8302. has_text : Union[Pattern[str], str, None]
  8303. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  8304. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  8305. `<article><div>Playwright</div></article>`.
  8306. has_not_text : Union[Pattern[str], str, None]
  8307. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  8308. When passed a [string], matching is case-insensitive and searches for a substring.
  8309. has : Union[Locator, None]
  8310. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  8311. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  8312. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  8313. the document root. For example, you can find `content` that has `div` in
  8314. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  8315. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  8316. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  8317. has_not : Union[Locator, None]
  8318. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  8319. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  8320. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  8321. Returns
  8322. -------
  8323. Locator
  8324. """
  8325. return mapping.from_impl(
  8326. self._impl_obj.locator(
  8327. selector=selector,
  8328. hasText=has_text,
  8329. hasNotText=has_not_text,
  8330. has=has._impl_obj if has else None,
  8331. hasNot=has_not._impl_obj if has_not else None,
  8332. )
  8333. )
  8334. def get_by_alt_text(
  8335. self,
  8336. text: typing.Union[str, typing.Pattern[str]],
  8337. *,
  8338. exact: typing.Optional[bool] = None,
  8339. ) -> "Locator":
  8340. """Page.get_by_alt_text
  8341. Allows locating elements by their alt text.
  8342. **Usage**
  8343. For example, this method will find the image by alt text \"Playwright logo\":
  8344. ```html
  8345. <img alt='Playwright logo'>
  8346. ```
  8347. ```py
  8348. await page.get_by_alt_text(\"Playwright logo\").click()
  8349. ```
  8350. Parameters
  8351. ----------
  8352. text : Union[Pattern[str], str]
  8353. Text to locate the element for.
  8354. exact : Union[bool, None]
  8355. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8356. regular expression. Note that exact match still trims whitespace.
  8357. Returns
  8358. -------
  8359. Locator
  8360. """
  8361. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  8362. def get_by_label(
  8363. self,
  8364. text: typing.Union[str, typing.Pattern[str]],
  8365. *,
  8366. exact: typing.Optional[bool] = None,
  8367. ) -> "Locator":
  8368. """Page.get_by_label
  8369. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  8370. `aria-label` attribute.
  8371. **Usage**
  8372. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  8373. ```html
  8374. <input aria-label=\"Username\">
  8375. <label for=\"password-input\">Password:</label>
  8376. <input id=\"password-input\">
  8377. ```
  8378. ```py
  8379. await page.get_by_label(\"Username\").fill(\"john\")
  8380. await page.get_by_label(\"Password\").fill(\"secret\")
  8381. ```
  8382. Parameters
  8383. ----------
  8384. text : Union[Pattern[str], str]
  8385. Text to locate the element for.
  8386. exact : Union[bool, None]
  8387. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8388. regular expression. Note that exact match still trims whitespace.
  8389. Returns
  8390. -------
  8391. Locator
  8392. """
  8393. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  8394. def get_by_placeholder(
  8395. self,
  8396. text: typing.Union[str, typing.Pattern[str]],
  8397. *,
  8398. exact: typing.Optional[bool] = None,
  8399. ) -> "Locator":
  8400. """Page.get_by_placeholder
  8401. Allows locating input elements by the placeholder text.
  8402. **Usage**
  8403. For example, consider the following DOM structure.
  8404. ```html
  8405. <input type=\"email\" placeholder=\"name@example.com\" />
  8406. ```
  8407. You can fill the input after locating it by the placeholder text:
  8408. ```py
  8409. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  8410. ```
  8411. Parameters
  8412. ----------
  8413. text : Union[Pattern[str], str]
  8414. Text to locate the element for.
  8415. exact : Union[bool, None]
  8416. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8417. regular expression. Note that exact match still trims whitespace.
  8418. Returns
  8419. -------
  8420. Locator
  8421. """
  8422. return mapping.from_impl(
  8423. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  8424. )
  8425. def get_by_role(
  8426. self,
  8427. role: Literal[
  8428. "alert",
  8429. "alertdialog",
  8430. "application",
  8431. "article",
  8432. "banner",
  8433. "blockquote",
  8434. "button",
  8435. "caption",
  8436. "cell",
  8437. "checkbox",
  8438. "code",
  8439. "columnheader",
  8440. "combobox",
  8441. "complementary",
  8442. "contentinfo",
  8443. "definition",
  8444. "deletion",
  8445. "dialog",
  8446. "directory",
  8447. "document",
  8448. "emphasis",
  8449. "feed",
  8450. "figure",
  8451. "form",
  8452. "generic",
  8453. "grid",
  8454. "gridcell",
  8455. "group",
  8456. "heading",
  8457. "img",
  8458. "insertion",
  8459. "link",
  8460. "list",
  8461. "listbox",
  8462. "listitem",
  8463. "log",
  8464. "main",
  8465. "marquee",
  8466. "math",
  8467. "menu",
  8468. "menubar",
  8469. "menuitem",
  8470. "menuitemcheckbox",
  8471. "menuitemradio",
  8472. "meter",
  8473. "navigation",
  8474. "none",
  8475. "note",
  8476. "option",
  8477. "paragraph",
  8478. "presentation",
  8479. "progressbar",
  8480. "radio",
  8481. "radiogroup",
  8482. "region",
  8483. "row",
  8484. "rowgroup",
  8485. "rowheader",
  8486. "scrollbar",
  8487. "search",
  8488. "searchbox",
  8489. "separator",
  8490. "slider",
  8491. "spinbutton",
  8492. "status",
  8493. "strong",
  8494. "subscript",
  8495. "superscript",
  8496. "switch",
  8497. "tab",
  8498. "table",
  8499. "tablist",
  8500. "tabpanel",
  8501. "term",
  8502. "textbox",
  8503. "time",
  8504. "timer",
  8505. "toolbar",
  8506. "tooltip",
  8507. "tree",
  8508. "treegrid",
  8509. "treeitem",
  8510. ],
  8511. *,
  8512. checked: typing.Optional[bool] = None,
  8513. disabled: typing.Optional[bool] = None,
  8514. expanded: typing.Optional[bool] = None,
  8515. include_hidden: typing.Optional[bool] = None,
  8516. level: typing.Optional[int] = None,
  8517. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  8518. pressed: typing.Optional[bool] = None,
  8519. selected: typing.Optional[bool] = None,
  8520. exact: typing.Optional[bool] = None,
  8521. ) -> "Locator":
  8522. """Page.get_by_role
  8523. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  8524. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  8525. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  8526. **Usage**
  8527. Consider the following DOM structure.
  8528. ```html
  8529. <h3>Sign up</h3>
  8530. <label>
  8531. <input type=\"checkbox\" /> Subscribe
  8532. </label>
  8533. <br/>
  8534. <button>Submit</button>
  8535. ```
  8536. You can locate each element by it's implicit role:
  8537. ```py
  8538. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  8539. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  8540. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  8541. ```
  8542. **Details**
  8543. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  8544. about the ARIA guidelines.
  8545. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  8546. that is recognized by the role selector. You can find all the
  8547. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  8548. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  8549. Parameters
  8550. ----------
  8551. 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"]
  8552. Required aria role.
  8553. checked : Union[bool, None]
  8554. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  8555. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  8556. disabled : Union[bool, None]
  8557. An attribute that is usually set by `aria-disabled` or `disabled`.
  8558. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  8559. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  8560. expanded : Union[bool, None]
  8561. An attribute that is usually set by `aria-expanded`.
  8562. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  8563. include_hidden : Union[bool, None]
  8564. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  8565. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  8566. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  8567. level : Union[int, None]
  8568. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  8569. for `<h1>-<h6>` elements.
  8570. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  8571. name : Union[Pattern[str], str, None]
  8572. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  8573. case-insensitive and searches for a substring, use `exact` to control this behavior.
  8574. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  8575. pressed : Union[bool, None]
  8576. An attribute that is usually set by `aria-pressed`.
  8577. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  8578. selected : Union[bool, None]
  8579. An attribute that is usually set by `aria-selected`.
  8580. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  8581. exact : Union[bool, None]
  8582. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  8583. regular expression. Note that exact match still trims whitespace.
  8584. Returns
  8585. -------
  8586. Locator
  8587. """
  8588. return mapping.from_impl(
  8589. self._impl_obj.get_by_role(
  8590. role=role,
  8591. checked=checked,
  8592. disabled=disabled,
  8593. expanded=expanded,
  8594. includeHidden=include_hidden,
  8595. level=level,
  8596. name=name,
  8597. pressed=pressed,
  8598. selected=selected,
  8599. exact=exact,
  8600. )
  8601. )
  8602. def get_by_test_id(
  8603. self, test_id: typing.Union[str, typing.Pattern[str]]
  8604. ) -> "Locator":
  8605. """Page.get_by_test_id
  8606. Locate element by the test id.
  8607. **Usage**
  8608. Consider the following DOM structure.
  8609. ```html
  8610. <button data-testid=\"directions\">Itinéraire</button>
  8611. ```
  8612. You can locate the element by it's test id:
  8613. ```py
  8614. await page.get_by_test_id(\"directions\").click()
  8615. ```
  8616. **Details**
  8617. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  8618. configure a different test id attribute if necessary.
  8619. Parameters
  8620. ----------
  8621. test_id : Union[Pattern[str], str]
  8622. Id to locate the element by.
  8623. Returns
  8624. -------
  8625. Locator
  8626. """
  8627. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  8628. def get_by_text(
  8629. self,
  8630. text: typing.Union[str, typing.Pattern[str]],
  8631. *,
  8632. exact: typing.Optional[bool] = None,
  8633. ) -> "Locator":
  8634. """Page.get_by_text
  8635. Allows locating elements that contain given text.
  8636. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  8637. filter by the text content.
  8638. **Usage**
  8639. Consider the following DOM structure:
  8640. ```html
  8641. <div>Hello <span>world</span></div>
  8642. <div>Hello</div>
  8643. ```
  8644. You can locate by text substring, exact string, or a regular expression:
  8645. ```py
  8646. # Matches <span>
  8647. page.get_by_text(\"world\")
  8648. # Matches first <div>
  8649. page.get_by_text(\"Hello world\")
  8650. # Matches second <div>
  8651. page.get_by_text(\"Hello\", exact=True)
  8652. # Matches both <div>s
  8653. page.get_by_text(re.compile(\"Hello\"))
  8654. # Matches second <div>
  8655. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  8656. ```
  8657. **Details**
  8658. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  8659. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  8660. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  8661. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  8662. Parameters
  8663. ----------
  8664. text : Union[Pattern[str], str]
  8665. Text to locate the element for.
  8666. exact : Union[bool, None]
  8667. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8668. regular expression. Note that exact match still trims whitespace.
  8669. Returns
  8670. -------
  8671. Locator
  8672. """
  8673. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  8674. def get_by_title(
  8675. self,
  8676. text: typing.Union[str, typing.Pattern[str]],
  8677. *,
  8678. exact: typing.Optional[bool] = None,
  8679. ) -> "Locator":
  8680. """Page.get_by_title
  8681. Allows locating elements by their title attribute.
  8682. **Usage**
  8683. Consider the following DOM structure.
  8684. ```html
  8685. <span title='Issues count'>25 issues</span>
  8686. ```
  8687. You can check the issues count after locating it by the title text:
  8688. ```py
  8689. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  8690. ```
  8691. Parameters
  8692. ----------
  8693. text : Union[Pattern[str], str]
  8694. Text to locate the element for.
  8695. exact : Union[bool, None]
  8696. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  8697. regular expression. Note that exact match still trims whitespace.
  8698. Returns
  8699. -------
  8700. Locator
  8701. """
  8702. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  8703. def frame_locator(self, selector: str) -> "FrameLocator":
  8704. """Page.frame_locator
  8705. When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
  8706. in that iframe.
  8707. **Usage**
  8708. Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
  8709. id=\"my-frame\">`:
  8710. ```py
  8711. locator = page.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
  8712. await locator.click()
  8713. ```
  8714. Parameters
  8715. ----------
  8716. selector : str
  8717. A selector to use when resolving DOM element.
  8718. Returns
  8719. -------
  8720. FrameLocator
  8721. """
  8722. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  8723. async def focus(
  8724. self,
  8725. selector: str,
  8726. *,
  8727. strict: typing.Optional[bool] = None,
  8728. timeout: typing.Optional[float] = None,
  8729. ) -> None:
  8730. """Page.focus
  8731. This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
  8732. method waits until a matching element appears in the DOM.
  8733. Parameters
  8734. ----------
  8735. selector : str
  8736. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8737. used.
  8738. strict : Union[bool, None]
  8739. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8740. element, the call throws an exception.
  8741. timeout : Union[float, None]
  8742. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8743. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8744. """
  8745. return mapping.from_maybe_impl(
  8746. await self._impl_obj.focus(
  8747. selector=selector, strict=strict, timeout=timeout
  8748. )
  8749. )
  8750. async def text_content(
  8751. self,
  8752. selector: str,
  8753. *,
  8754. strict: typing.Optional[bool] = None,
  8755. timeout: typing.Optional[float] = None,
  8756. ) -> typing.Optional[str]:
  8757. """Page.text_content
  8758. Returns `element.textContent`.
  8759. Parameters
  8760. ----------
  8761. selector : str
  8762. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8763. used.
  8764. strict : Union[bool, None]
  8765. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8766. element, the call throws an exception.
  8767. timeout : Union[float, None]
  8768. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8769. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8770. Returns
  8771. -------
  8772. Union[str, None]
  8773. """
  8774. return mapping.from_maybe_impl(
  8775. await self._impl_obj.text_content(
  8776. selector=selector, strict=strict, timeout=timeout
  8777. )
  8778. )
  8779. async def inner_text(
  8780. self,
  8781. selector: str,
  8782. *,
  8783. strict: typing.Optional[bool] = None,
  8784. timeout: typing.Optional[float] = None,
  8785. ) -> str:
  8786. """Page.inner_text
  8787. Returns `element.innerText`.
  8788. Parameters
  8789. ----------
  8790. selector : str
  8791. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8792. used.
  8793. strict : Union[bool, None]
  8794. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8795. element, the call throws an exception.
  8796. timeout : Union[float, None]
  8797. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8798. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8799. Returns
  8800. -------
  8801. str
  8802. """
  8803. return mapping.from_maybe_impl(
  8804. await self._impl_obj.inner_text(
  8805. selector=selector, strict=strict, timeout=timeout
  8806. )
  8807. )
  8808. async def inner_html(
  8809. self,
  8810. selector: str,
  8811. *,
  8812. strict: typing.Optional[bool] = None,
  8813. timeout: typing.Optional[float] = None,
  8814. ) -> str:
  8815. """Page.inner_html
  8816. Returns `element.innerHTML`.
  8817. Parameters
  8818. ----------
  8819. selector : str
  8820. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8821. used.
  8822. strict : Union[bool, None]
  8823. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8824. element, the call throws an exception.
  8825. timeout : Union[float, None]
  8826. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8827. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8828. Returns
  8829. -------
  8830. str
  8831. """
  8832. return mapping.from_maybe_impl(
  8833. await self._impl_obj.inner_html(
  8834. selector=selector, strict=strict, timeout=timeout
  8835. )
  8836. )
  8837. async def get_attribute(
  8838. self,
  8839. selector: str,
  8840. name: str,
  8841. *,
  8842. strict: typing.Optional[bool] = None,
  8843. timeout: typing.Optional[float] = None,
  8844. ) -> typing.Optional[str]:
  8845. """Page.get_attribute
  8846. Returns element attribute value.
  8847. Parameters
  8848. ----------
  8849. selector : str
  8850. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8851. used.
  8852. name : str
  8853. Attribute name to get the value for.
  8854. strict : Union[bool, None]
  8855. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8856. element, the call throws an exception.
  8857. timeout : Union[float, None]
  8858. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8859. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8860. Returns
  8861. -------
  8862. Union[str, None]
  8863. """
  8864. return mapping.from_maybe_impl(
  8865. await self._impl_obj.get_attribute(
  8866. selector=selector, name=name, strict=strict, timeout=timeout
  8867. )
  8868. )
  8869. async def hover(
  8870. self,
  8871. selector: str,
  8872. *,
  8873. modifiers: typing.Optional[
  8874. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  8875. ] = None,
  8876. position: typing.Optional[Position] = None,
  8877. timeout: typing.Optional[float] = None,
  8878. no_wait_after: typing.Optional[bool] = None,
  8879. force: typing.Optional[bool] = None,
  8880. strict: typing.Optional[bool] = None,
  8881. trial: typing.Optional[bool] = None,
  8882. ) -> None:
  8883. """Page.hover
  8884. This method hovers over an element matching `selector` by performing the following steps:
  8885. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  8886. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  8887. the element is detached during the checks, the whole action is retried.
  8888. 1. Scroll the element into view if needed.
  8889. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  8890. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  8891. Passing zero timeout disables this.
  8892. Parameters
  8893. ----------
  8894. selector : str
  8895. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  8896. used.
  8897. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  8898. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  8899. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  8900. "Control" on Windows and Linux and to "Meta" on macOS.
  8901. position : Union[{x: float, y: float}, None]
  8902. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  8903. the element.
  8904. timeout : Union[float, None]
  8905. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8906. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8907. no_wait_after : Union[bool, None]
  8908. This option has no effect.
  8909. Deprecated: This option has no effect.
  8910. force : Union[bool, None]
  8911. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8912. strict : Union[bool, None]
  8913. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8914. element, the call throws an exception.
  8915. trial : Union[bool, None]
  8916. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8917. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  8918. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  8919. are pressed.
  8920. """
  8921. return mapping.from_maybe_impl(
  8922. await self._impl_obj.hover(
  8923. selector=selector,
  8924. modifiers=mapping.to_impl(modifiers),
  8925. position=position,
  8926. timeout=timeout,
  8927. noWaitAfter=no_wait_after,
  8928. force=force,
  8929. strict=strict,
  8930. trial=trial,
  8931. )
  8932. )
  8933. async def drag_and_drop(
  8934. self,
  8935. source: str,
  8936. target: str,
  8937. *,
  8938. source_position: typing.Optional[Position] = None,
  8939. target_position: typing.Optional[Position] = None,
  8940. force: typing.Optional[bool] = None,
  8941. no_wait_after: typing.Optional[bool] = None,
  8942. timeout: typing.Optional[float] = None,
  8943. strict: typing.Optional[bool] = None,
  8944. trial: typing.Optional[bool] = None,
  8945. steps: typing.Optional[int] = None,
  8946. ) -> None:
  8947. """Page.drag_and_drop
  8948. This method drags the source element to the target element. It will first move to the source element, perform a
  8949. `mousedown`, then move to the target element and perform a `mouseup`.
  8950. **Usage**
  8951. ```py
  8952. await page.drag_and_drop(\"#source\", \"#target\")
  8953. # or specify exact positions relative to the top-left corners of the elements:
  8954. await page.drag_and_drop(
  8955. \"#source\",
  8956. \"#target\",
  8957. source_position={\"x\": 34, \"y\": 7},
  8958. target_position={\"x\": 10, \"y\": 20}
  8959. )
  8960. ```
  8961. Parameters
  8962. ----------
  8963. source : str
  8964. A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
  8965. be used.
  8966. target : str
  8967. A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
  8968. will be used.
  8969. source_position : Union[{x: float, y: float}, None]
  8970. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  8971. specified, some visible point of the element is used.
  8972. target_position : Union[{x: float, y: float}, None]
  8973. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  8974. specified, some visible point of the element is used.
  8975. force : Union[bool, None]
  8976. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  8977. no_wait_after : Union[bool, None]
  8978. This option has no effect.
  8979. Deprecated: This option has no effect.
  8980. timeout : Union[float, None]
  8981. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  8982. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  8983. strict : Union[bool, None]
  8984. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  8985. element, the call throws an exception.
  8986. trial : Union[bool, None]
  8987. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  8988. to `false`. Useful to wait until the element is ready for the action without performing it.
  8989. steps : Union[int, None]
  8990. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  8991. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  8992. """
  8993. return mapping.from_maybe_impl(
  8994. await self._impl_obj.drag_and_drop(
  8995. source=source,
  8996. target=target,
  8997. sourcePosition=source_position,
  8998. targetPosition=target_position,
  8999. force=force,
  9000. noWaitAfter=no_wait_after,
  9001. timeout=timeout,
  9002. strict=strict,
  9003. trial=trial,
  9004. steps=steps,
  9005. )
  9006. )
  9007. async def select_option(
  9008. self,
  9009. selector: str,
  9010. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  9011. *,
  9012. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  9013. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  9014. element: typing.Optional[
  9015. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  9016. ] = None,
  9017. timeout: typing.Optional[float] = None,
  9018. no_wait_after: typing.Optional[bool] = None,
  9019. force: typing.Optional[bool] = None,
  9020. strict: typing.Optional[bool] = None,
  9021. ) -> typing.List[str]:
  9022. """Page.select_option
  9023. This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
  9024. until all specified options are present in the `<select>` element and selects these options.
  9025. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  9026. the `<label>` element that has an associated
  9027. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  9028. instead.
  9029. Returns the array of option values that have been successfully selected.
  9030. Triggers a `change` and `input` event once all the provided options have been selected.
  9031. **Usage**
  9032. ```py
  9033. # Single selection matching the value or label
  9034. await page.select_option(\"select#colors\", \"blue\")
  9035. # single selection matching the label
  9036. await page.select_option(\"select#colors\", label=\"blue\")
  9037. # multiple selection
  9038. await page.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
  9039. ```
  9040. Parameters
  9041. ----------
  9042. selector : str
  9043. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9044. used.
  9045. value : Union[Sequence[str], str, None]
  9046. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  9047. otherwise only the first option matching one of the passed options is selected. Optional.
  9048. index : Union[Sequence[int], int, None]
  9049. Options to select by index. Optional.
  9050. label : Union[Sequence[str], str, None]
  9051. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  9052. otherwise only the first option matching one of the passed options is selected. Optional.
  9053. element : Union[ElementHandle, Sequence[ElementHandle], None]
  9054. Option elements to select. Optional.
  9055. timeout : Union[float, None]
  9056. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9057. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9058. no_wait_after : Union[bool, None]
  9059. This option has no effect.
  9060. Deprecated: This option has no effect.
  9061. force : Union[bool, None]
  9062. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9063. strict : Union[bool, None]
  9064. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9065. element, the call throws an exception.
  9066. Returns
  9067. -------
  9068. List[str]
  9069. """
  9070. return mapping.from_maybe_impl(
  9071. await self._impl_obj.select_option(
  9072. selector=selector,
  9073. value=mapping.to_impl(value),
  9074. index=mapping.to_impl(index),
  9075. label=mapping.to_impl(label),
  9076. element=mapping.to_impl(element),
  9077. timeout=timeout,
  9078. noWaitAfter=no_wait_after,
  9079. force=force,
  9080. strict=strict,
  9081. )
  9082. )
  9083. async def input_value(
  9084. self,
  9085. selector: str,
  9086. *,
  9087. strict: typing.Optional[bool] = None,
  9088. timeout: typing.Optional[float] = None,
  9089. ) -> str:
  9090. """Page.input_value
  9091. Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
  9092. Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
  9093. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  9094. control.
  9095. Parameters
  9096. ----------
  9097. selector : str
  9098. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9099. used.
  9100. strict : Union[bool, None]
  9101. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9102. element, the call throws an exception.
  9103. timeout : Union[float, None]
  9104. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9105. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9106. Returns
  9107. -------
  9108. str
  9109. """
  9110. return mapping.from_maybe_impl(
  9111. await self._impl_obj.input_value(
  9112. selector=selector, strict=strict, timeout=timeout
  9113. )
  9114. )
  9115. async def set_input_files(
  9116. self,
  9117. selector: str,
  9118. files: typing.Union[
  9119. str,
  9120. pathlib.Path,
  9121. FilePayload,
  9122. typing.Sequence[typing.Union[str, pathlib.Path]],
  9123. typing.Sequence[FilePayload],
  9124. ],
  9125. *,
  9126. timeout: typing.Optional[float] = None,
  9127. strict: typing.Optional[bool] = None,
  9128. no_wait_after: typing.Optional[bool] = None,
  9129. ) -> None:
  9130. """Page.set_input_files
  9131. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  9132. they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
  9133. with a `[webkitdirectory]` attribute, only a single directory path is supported.
  9134. This method expects `selector` to point to an
  9135. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  9136. the `<label>` element that has an associated
  9137. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  9138. Parameters
  9139. ----------
  9140. selector : str
  9141. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9142. used.
  9143. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  9144. timeout : Union[float, None]
  9145. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9146. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9147. strict : Union[bool, None]
  9148. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9149. element, the call throws an exception.
  9150. no_wait_after : Union[bool, None]
  9151. This option has no effect.
  9152. Deprecated: This option has no effect.
  9153. """
  9154. return mapping.from_maybe_impl(
  9155. await self._impl_obj.set_input_files(
  9156. selector=selector,
  9157. files=mapping.to_impl(files),
  9158. timeout=timeout,
  9159. strict=strict,
  9160. noWaitAfter=no_wait_after,
  9161. )
  9162. )
  9163. async def type(
  9164. self,
  9165. selector: str,
  9166. text: str,
  9167. *,
  9168. delay: typing.Optional[float] = None,
  9169. timeout: typing.Optional[float] = None,
  9170. no_wait_after: typing.Optional[bool] = None,
  9171. strict: typing.Optional[bool] = None,
  9172. ) -> None:
  9173. """Page.type
  9174. Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to
  9175. send fine-grained keyboard events. To fill values in form fields, use `page.fill()`.
  9176. To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
  9177. **Usage**
  9178. Parameters
  9179. ----------
  9180. selector : str
  9181. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9182. used.
  9183. text : str
  9184. A text to type into a focused element.
  9185. delay : Union[float, None]
  9186. Time to wait between key presses in milliseconds. Defaults to 0.
  9187. timeout : Union[float, None]
  9188. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9189. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9190. no_wait_after : Union[bool, None]
  9191. This option has no effect.
  9192. Deprecated: This option has no effect.
  9193. strict : Union[bool, None]
  9194. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9195. element, the call throws an exception.
  9196. """
  9197. return mapping.from_maybe_impl(
  9198. await self._impl_obj.type(
  9199. selector=selector,
  9200. text=text,
  9201. delay=delay,
  9202. timeout=timeout,
  9203. noWaitAfter=no_wait_after,
  9204. strict=strict,
  9205. )
  9206. )
  9207. async def press(
  9208. self,
  9209. selector: str,
  9210. key: str,
  9211. *,
  9212. delay: typing.Optional[float] = None,
  9213. timeout: typing.Optional[float] = None,
  9214. no_wait_after: typing.Optional[bool] = None,
  9215. strict: typing.Optional[bool] = None,
  9216. ) -> None:
  9217. """Page.press
  9218. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  9219. `key` can specify the intended
  9220. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  9221. to generate the text for. A superset of the `key` values can be found
  9222. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  9223. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  9224. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  9225. etc.
  9226. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  9227. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  9228. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  9229. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  9230. texts.
  9231. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  9232. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  9233. **Usage**
  9234. ```py
  9235. page = await browser.new_page()
  9236. await page.goto(\"https://keycode.info\")
  9237. await page.press(\"body\", \"A\")
  9238. await page.screenshot(path=\"a.png\")
  9239. await page.press(\"body\", \"ArrowLeft\")
  9240. await page.screenshot(path=\"arrow_left.png\")
  9241. await page.press(\"body\", \"Shift+O\")
  9242. await page.screenshot(path=\"o.png\")
  9243. await browser.close()
  9244. ```
  9245. Parameters
  9246. ----------
  9247. selector : str
  9248. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9249. used.
  9250. key : str
  9251. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  9252. delay : Union[float, None]
  9253. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  9254. timeout : Union[float, None]
  9255. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9256. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9257. no_wait_after : Union[bool, None]
  9258. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  9259. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  9260. navigating to inaccessible pages. Defaults to `false`.
  9261. Deprecated: This option will default to `true` in the future.
  9262. strict : Union[bool, None]
  9263. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9264. element, the call throws an exception.
  9265. """
  9266. return mapping.from_maybe_impl(
  9267. await self._impl_obj.press(
  9268. selector=selector,
  9269. key=key,
  9270. delay=delay,
  9271. timeout=timeout,
  9272. noWaitAfter=no_wait_after,
  9273. strict=strict,
  9274. )
  9275. )
  9276. async def check(
  9277. self,
  9278. selector: str,
  9279. *,
  9280. position: typing.Optional[Position] = None,
  9281. timeout: typing.Optional[float] = None,
  9282. force: typing.Optional[bool] = None,
  9283. no_wait_after: typing.Optional[bool] = None,
  9284. strict: typing.Optional[bool] = None,
  9285. trial: typing.Optional[bool] = None,
  9286. ) -> None:
  9287. """Page.check
  9288. This method checks an element matching `selector` by performing the following steps:
  9289. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9290. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  9291. already checked, this method returns immediately.
  9292. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9293. the element is detached during the checks, the whole action is retried.
  9294. 1. Scroll the element into view if needed.
  9295. 1. Use `page.mouse` to click in the center of the element.
  9296. 1. Ensure that the element is now checked. If not, this method throws.
  9297. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9298. Passing zero timeout disables this.
  9299. Parameters
  9300. ----------
  9301. selector : str
  9302. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9303. used.
  9304. position : Union[{x: float, y: float}, None]
  9305. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9306. the element.
  9307. timeout : Union[float, None]
  9308. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9309. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9310. force : Union[bool, None]
  9311. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9312. no_wait_after : Union[bool, None]
  9313. This option has no effect.
  9314. Deprecated: This option has no effect.
  9315. strict : Union[bool, None]
  9316. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9317. element, the call throws an exception.
  9318. trial : Union[bool, None]
  9319. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9320. to `false`. Useful to wait until the element is ready for the action without performing it.
  9321. """
  9322. return mapping.from_maybe_impl(
  9323. await self._impl_obj.check(
  9324. selector=selector,
  9325. position=position,
  9326. timeout=timeout,
  9327. force=force,
  9328. noWaitAfter=no_wait_after,
  9329. strict=strict,
  9330. trial=trial,
  9331. )
  9332. )
  9333. async def uncheck(
  9334. self,
  9335. selector: str,
  9336. *,
  9337. position: typing.Optional[Position] = None,
  9338. timeout: typing.Optional[float] = None,
  9339. force: typing.Optional[bool] = None,
  9340. no_wait_after: typing.Optional[bool] = None,
  9341. strict: typing.Optional[bool] = None,
  9342. trial: typing.Optional[bool] = None,
  9343. ) -> None:
  9344. """Page.uncheck
  9345. This method unchecks an element matching `selector` by performing the following steps:
  9346. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9347. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
  9348. already unchecked, this method returns immediately.
  9349. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9350. the element is detached during the checks, the whole action is retried.
  9351. 1. Scroll the element into view if needed.
  9352. 1. Use `page.mouse` to click in the center of the element.
  9353. 1. Ensure that the element is now unchecked. If not, this method throws.
  9354. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9355. Passing zero timeout disables this.
  9356. Parameters
  9357. ----------
  9358. selector : str
  9359. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9360. used.
  9361. position : Union[{x: float, y: float}, None]
  9362. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9363. the element.
  9364. timeout : Union[float, None]
  9365. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9366. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9367. force : Union[bool, None]
  9368. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9369. no_wait_after : Union[bool, None]
  9370. This option has no effect.
  9371. Deprecated: This option has no effect.
  9372. strict : Union[bool, None]
  9373. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9374. element, the call throws an exception.
  9375. trial : Union[bool, None]
  9376. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9377. to `false`. Useful to wait until the element is ready for the action without performing it.
  9378. """
  9379. return mapping.from_maybe_impl(
  9380. await self._impl_obj.uncheck(
  9381. selector=selector,
  9382. position=position,
  9383. timeout=timeout,
  9384. force=force,
  9385. noWaitAfter=no_wait_after,
  9386. strict=strict,
  9387. trial=trial,
  9388. )
  9389. )
  9390. async def wait_for_timeout(self, timeout: float) -> None:
  9391. """Page.wait_for_timeout
  9392. Waits for the given `timeout` in milliseconds.
  9393. Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
  9394. to be flaky. Use signals such as network events, selectors becoming visible and others instead.
  9395. **Usage**
  9396. ```py
  9397. # wait for 1 second
  9398. await page.wait_for_timeout(1000)
  9399. ```
  9400. Parameters
  9401. ----------
  9402. timeout : float
  9403. A timeout to wait for
  9404. """
  9405. return mapping.from_maybe_impl(
  9406. await self._impl_obj.wait_for_timeout(timeout=timeout)
  9407. )
  9408. async def wait_for_function(
  9409. self,
  9410. expression: str,
  9411. *,
  9412. arg: typing.Optional[typing.Any] = None,
  9413. timeout: typing.Optional[float] = None,
  9414. polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
  9415. ) -> "JSHandle":
  9416. """Page.wait_for_function
  9417. Returns when the `expression` returns a truthy value. It resolves to a JSHandle of the truthy value.
  9418. **Usage**
  9419. The `page.wait_for_function()` can be used to observe viewport size change:
  9420. ```py
  9421. import asyncio
  9422. from playwright.async_api import async_playwright, Playwright
  9423. async def run(playwright: Playwright):
  9424. webkit = playwright.webkit
  9425. browser = await webkit.launch()
  9426. page = await browser.new_page()
  9427. await page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
  9428. await page.wait_for_function(\"() => window.x > 0\")
  9429. await browser.close()
  9430. async def main():
  9431. async with async_playwright() as playwright:
  9432. await run(playwright)
  9433. asyncio.run(main())
  9434. ```
  9435. To pass an argument to the predicate of `page.wait_for_function()` function:
  9436. ```py
  9437. selector = \".foo\"
  9438. await page.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
  9439. ```
  9440. Parameters
  9441. ----------
  9442. expression : str
  9443. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  9444. function is automatically invoked.
  9445. arg : Union[Any, None]
  9446. Optional argument to pass to `expression`.
  9447. timeout : Union[float, None]
  9448. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9449. default value can be changed by using the `browser_context.set_default_timeout()` or
  9450. `page.set_default_timeout()` methods.
  9451. polling : Union["raf", float, None]
  9452. If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
  9453. is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
  9454. `raf`.
  9455. Returns
  9456. -------
  9457. JSHandle
  9458. """
  9459. return mapping.from_impl(
  9460. await self._impl_obj.wait_for_function(
  9461. expression=expression,
  9462. arg=mapping.to_impl(arg),
  9463. timeout=timeout,
  9464. polling=polling,
  9465. )
  9466. )
  9467. async def pause(self) -> None:
  9468. """Page.pause
  9469. Pauses script execution. Playwright will stop executing the script and wait for the user to either press the
  9470. 'Resume' button in the page overlay or to call `playwright.resume()` in the DevTools console.
  9471. User can inspect selectors or perform manual steps while paused. Resume will continue running the original script
  9472. from the place it was paused.
  9473. **NOTE** This method requires Playwright to be started in a headed mode, with a falsy `headless` option.
  9474. """
  9475. return mapping.from_maybe_impl(await self._impl_obj.pause())
  9476. async def pdf(
  9477. self,
  9478. *,
  9479. scale: typing.Optional[float] = None,
  9480. display_header_footer: typing.Optional[bool] = None,
  9481. header_template: typing.Optional[str] = None,
  9482. footer_template: typing.Optional[str] = None,
  9483. print_background: typing.Optional[bool] = None,
  9484. landscape: typing.Optional[bool] = None,
  9485. page_ranges: typing.Optional[str] = None,
  9486. format: typing.Optional[str] = None,
  9487. width: typing.Optional[typing.Union[str, float]] = None,
  9488. height: typing.Optional[typing.Union[str, float]] = None,
  9489. prefer_css_page_size: typing.Optional[bool] = None,
  9490. margin: typing.Optional[PdfMargins] = None,
  9491. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  9492. outline: typing.Optional[bool] = None,
  9493. tagged: typing.Optional[bool] = None,
  9494. ) -> bytes:
  9495. """Page.pdf
  9496. Returns the PDF buffer.
  9497. `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
  9498. `page.emulate_media()` before calling `page.pdf()`:
  9499. **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
  9500. [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust)
  9501. property to force rendering of exact colors.
  9502. **Usage**
  9503. ```py
  9504. # generates a pdf with \"screen\" media type.
  9505. await page.emulate_media(media=\"screen\")
  9506. await page.pdf(path=\"page.pdf\")
  9507. ```
  9508. The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as
  9509. pixels.
  9510. A few examples:
  9511. - `page.pdf({width: 100})` - prints with width set to 100 pixels
  9512. - `page.pdf({width: '100px'})` - prints with width set to 100 pixels
  9513. - `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
  9514. All possible units are:
  9515. - `px` - pixel
  9516. - `in` - inch
  9517. - `cm` - centimeter
  9518. - `mm` - millimeter
  9519. The `format` options are:
  9520. - `Letter`: 8.5in x 11in
  9521. - `Legal`: 8.5in x 14in
  9522. - `Tabloid`: 11in x 17in
  9523. - `Ledger`: 17in x 11in
  9524. - `A0`: 33.1in x 46.8in
  9525. - `A1`: 23.4in x 33.1in
  9526. - `A2`: 16.54in x 23.4in
  9527. - `A3`: 11.7in x 16.54in
  9528. - `A4`: 8.27in x 11.7in
  9529. - `A5`: 5.83in x 8.27in
  9530. - `A6`: 4.13in x 5.83in
  9531. **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations: > 1. Script tags inside
  9532. templates are not evaluated. > 2. Page styles are not visible inside templates.
  9533. Parameters
  9534. ----------
  9535. scale : Union[float, None]
  9536. Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
  9537. display_header_footer : Union[bool, None]
  9538. Display header and footer. Defaults to `false`.
  9539. header_template : Union[str, None]
  9540. HTML template for the print header. Should be valid HTML markup with following classes used to inject printing
  9541. values into them:
  9542. - `'date'` formatted print date
  9543. - `'title'` document title
  9544. - `'url'` document location
  9545. - `'pageNumber'` current page number
  9546. - `'totalPages'` total pages in the document
  9547. footer_template : Union[str, None]
  9548. HTML template for the print footer. Should use the same format as the `headerTemplate`.
  9549. print_background : Union[bool, None]
  9550. Print background graphics. Defaults to `false`.
  9551. landscape : Union[bool, None]
  9552. Paper orientation. Defaults to `false`.
  9553. page_ranges : Union[str, None]
  9554. Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
  9555. format : Union[str, None]
  9556. Paper format. If set, takes priority over `width` or `height` options. Defaults to 'Letter'.
  9557. width : Union[float, str, None]
  9558. Paper width, accepts values labeled with units.
  9559. height : Union[float, str, None]
  9560. Paper height, accepts values labeled with units.
  9561. prefer_css_page_size : Union[bool, None]
  9562. Give any CSS `@page` size declared in the page priority over what is declared in `width` and `height` or `format`
  9563. options. Defaults to `false`, which will scale the content to fit the paper size.
  9564. margin : Union[{top: Union[float, str, None], right: Union[float, str, None], bottom: Union[float, str, None], left: Union[float, str, None]}, None]
  9565. Paper margins, defaults to none.
  9566. path : Union[pathlib.Path, str, None]
  9567. The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to the current working
  9568. directory. If no path is provided, the PDF won't be saved to the disk.
  9569. outline : Union[bool, None]
  9570. Whether or not to embed the document outline into the PDF. Defaults to `false`.
  9571. tagged : Union[bool, None]
  9572. Whether or not to generate tagged (accessible) PDF. Defaults to `false`.
  9573. Returns
  9574. -------
  9575. bytes
  9576. """
  9577. return mapping.from_maybe_impl(
  9578. await self._impl_obj.pdf(
  9579. scale=scale,
  9580. displayHeaderFooter=display_header_footer,
  9581. headerTemplate=header_template,
  9582. footerTemplate=footer_template,
  9583. printBackground=print_background,
  9584. landscape=landscape,
  9585. pageRanges=page_ranges,
  9586. format=format,
  9587. width=width,
  9588. height=height,
  9589. preferCSSPageSize=prefer_css_page_size,
  9590. margin=margin,
  9591. path=path,
  9592. outline=outline,
  9593. tagged=tagged,
  9594. )
  9595. )
  9596. def expect_event(
  9597. self,
  9598. event: str,
  9599. predicate: typing.Optional[typing.Callable] = None,
  9600. *,
  9601. timeout: typing.Optional[float] = None,
  9602. ) -> AsyncEventContextManager:
  9603. """Page.expect_event
  9604. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  9605. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
  9606. **Usage**
  9607. ```py
  9608. async with page.expect_event(\"framenavigated\") as event_info:
  9609. await page.get_by_role(\"button\")
  9610. frame = await event_info.value
  9611. ```
  9612. Parameters
  9613. ----------
  9614. event : str
  9615. Event name, same one typically passed into `*.on(event)`.
  9616. predicate : Union[Callable, None]
  9617. Receives the event data and resolves to truthy value when the waiting should resolve.
  9618. timeout : Union[float, None]
  9619. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9620. default value can be changed by using the `browser_context.set_default_timeout()`.
  9621. Returns
  9622. -------
  9623. EventContextManager
  9624. """
  9625. return AsyncEventContextManager(
  9626. self._impl_obj.expect_event(
  9627. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  9628. ).future
  9629. )
  9630. def expect_console_message(
  9631. self,
  9632. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  9633. *,
  9634. timeout: typing.Optional[float] = None,
  9635. ) -> AsyncEventContextManager["ConsoleMessage"]:
  9636. """Page.expect_console_message
  9637. Performs action and waits for a `ConsoleMessage` to be logged by in the page. If predicate is provided, it passes
  9638. `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to return a truthy value.
  9639. Will throw an error if the page is closed before the `page.on('console')` event is fired.
  9640. Parameters
  9641. ----------
  9642. predicate : Union[Callable[[ConsoleMessage], bool], None]
  9643. Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
  9644. timeout : Union[float, None]
  9645. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9646. default value can be changed by using the `browser_context.set_default_timeout()`.
  9647. Returns
  9648. -------
  9649. EventContextManager[ConsoleMessage]
  9650. """
  9651. return AsyncEventContextManager(
  9652. self._impl_obj.expect_console_message(
  9653. predicate=self._wrap_handler(predicate), timeout=timeout
  9654. ).future
  9655. )
  9656. def expect_download(
  9657. self,
  9658. predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
  9659. *,
  9660. timeout: typing.Optional[float] = None,
  9661. ) -> AsyncEventContextManager["Download"]:
  9662. """Page.expect_download
  9663. Performs action and waits for a new `Download`. If predicate is provided, it passes `Download` value into the
  9664. `predicate` function and waits for `predicate(download)` to return a truthy value. Will throw an error if the page
  9665. is closed before the download event is fired.
  9666. Parameters
  9667. ----------
  9668. predicate : Union[Callable[[Download], bool], None]
  9669. Receives the `Download` object and resolves to truthy value when the waiting should resolve.
  9670. timeout : Union[float, None]
  9671. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9672. default value can be changed by using the `browser_context.set_default_timeout()`.
  9673. Returns
  9674. -------
  9675. EventContextManager[Download]
  9676. """
  9677. return AsyncEventContextManager(
  9678. self._impl_obj.expect_download(
  9679. predicate=self._wrap_handler(predicate), timeout=timeout
  9680. ).future
  9681. )
  9682. def expect_file_chooser(
  9683. self,
  9684. predicate: typing.Optional[typing.Callable[["FileChooser"], bool]] = None,
  9685. *,
  9686. timeout: typing.Optional[float] = None,
  9687. ) -> AsyncEventContextManager["FileChooser"]:
  9688. """Page.expect_file_chooser
  9689. Performs action and waits for a new `FileChooser` to be created. If predicate is provided, it passes `FileChooser`
  9690. value into the `predicate` function and waits for `predicate(fileChooser)` to return a truthy value. Will throw an
  9691. error if the page is closed before the file chooser is opened.
  9692. Parameters
  9693. ----------
  9694. predicate : Union[Callable[[FileChooser], bool], None]
  9695. Receives the `FileChooser` object and resolves to truthy value when the waiting should resolve.
  9696. timeout : Union[float, None]
  9697. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9698. default value can be changed by using the `browser_context.set_default_timeout()`.
  9699. Returns
  9700. -------
  9701. EventContextManager[FileChooser]
  9702. """
  9703. return AsyncEventContextManager(
  9704. self._impl_obj.expect_file_chooser(
  9705. predicate=self._wrap_handler(predicate), timeout=timeout
  9706. ).future
  9707. )
  9708. def expect_navigation(
  9709. self,
  9710. *,
  9711. url: typing.Optional[
  9712. typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
  9713. ] = None,
  9714. wait_until: typing.Optional[
  9715. Literal["commit", "domcontentloaded", "load", "networkidle"]
  9716. ] = None,
  9717. timeout: typing.Optional[float] = None,
  9718. ) -> AsyncEventContextManager["Response"]:
  9719. """Page.expect_navigation
  9720. Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the
  9721. navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
  9722. navigation due to History API usage, the navigation will resolve with `null`.
  9723. **Usage**
  9724. This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will
  9725. indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from
  9726. a `setTimeout`. Consider this example:
  9727. ```py
  9728. async with page.expect_navigation():
  9729. # This action triggers the navigation after a timeout.
  9730. await page.get_by_text(\"Navigate after timeout\").click()
  9731. # Resolves after navigation has finished
  9732. ```
  9733. **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
  9734. is considered a navigation.
  9735. Parameters
  9736. ----------
  9737. url : Union[Callable[[str], bool], Pattern[str], str, None]
  9738. A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
  9739. the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
  9740. equal to the string.
  9741. wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
  9742. When to consider operation succeeded, defaults to `load`. Events can be either:
  9743. - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
  9744. - `'load'` - consider operation to be finished when the `load` event is fired.
  9745. - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
  9746. at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  9747. - `'commit'` - consider operation to be finished when network response is received and the document started
  9748. loading.
  9749. timeout : Union[float, None]
  9750. Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
  9751. be changed by using the `browser_context.set_default_navigation_timeout()`,
  9752. `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
  9753. `page.set_default_timeout()` methods.
  9754. Returns
  9755. -------
  9756. EventContextManager[Response]
  9757. """
  9758. return AsyncEventContextManager(
  9759. self._impl_obj.expect_navigation(
  9760. url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
  9761. ).future
  9762. )
  9763. def expect_popup(
  9764. self,
  9765. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  9766. *,
  9767. timeout: typing.Optional[float] = None,
  9768. ) -> AsyncEventContextManager["Page"]:
  9769. """Page.expect_popup
  9770. Performs action and waits for a popup `Page`. If predicate is provided, it passes [Popup] value into the
  9771. `predicate` function and waits for `predicate(page)` to return a truthy value. Will throw an error if the page is
  9772. closed before the popup event is fired.
  9773. Parameters
  9774. ----------
  9775. predicate : Union[Callable[[Page], bool], None]
  9776. Receives the `Page` object and resolves to truthy value when the waiting should resolve.
  9777. timeout : Union[float, None]
  9778. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9779. default value can be changed by using the `browser_context.set_default_timeout()`.
  9780. Returns
  9781. -------
  9782. EventContextManager[Page]
  9783. """
  9784. return AsyncEventContextManager(
  9785. self._impl_obj.expect_popup(
  9786. predicate=self._wrap_handler(predicate), timeout=timeout
  9787. ).future
  9788. )
  9789. def expect_request(
  9790. self,
  9791. url_or_predicate: typing.Union[
  9792. str, typing.Pattern[str], typing.Callable[["Request"], bool]
  9793. ],
  9794. *,
  9795. timeout: typing.Optional[float] = None,
  9796. ) -> AsyncEventContextManager["Request"]:
  9797. """Page.expect_request
  9798. Waits for the matching request and returns it. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more
  9799. details about events.
  9800. **Usage**
  9801. ```py
  9802. async with page.expect_request(\"http://example.com/resource\") as first:
  9803. await page.get_by_text(\"trigger request\").click()
  9804. first_request = await first.value
  9805. # or with a lambda
  9806. async with page.expect_request(lambda request: request.url == \"http://example.com\" and request.method == \"get\") as second:
  9807. await page.get_by_text(\"trigger request\").click()
  9808. second_request = await second.value
  9809. ```
  9810. Parameters
  9811. ----------
  9812. url_or_predicate : Union[Callable[[Request], bool], Pattern[str], str]
  9813. Request URL string, regex or predicate receiving `Request` object. When a `baseURL` via the context options was
  9814. provided and the passed URL is a path, it gets merged via the
  9815. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  9816. timeout : Union[float, None]
  9817. Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
  9818. be changed by using the `page.set_default_timeout()` method.
  9819. Returns
  9820. -------
  9821. EventContextManager[Request]
  9822. """
  9823. return AsyncEventContextManager(
  9824. self._impl_obj.expect_request(
  9825. urlOrPredicate=self._wrap_handler(url_or_predicate), timeout=timeout
  9826. ).future
  9827. )
  9828. def expect_request_finished(
  9829. self,
  9830. predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
  9831. *,
  9832. timeout: typing.Optional[float] = None,
  9833. ) -> AsyncEventContextManager["Request"]:
  9834. """Page.expect_request_finished
  9835. Performs action and waits for a `Request` to finish loading. If predicate is provided, it passes `Request` value
  9836. into the `predicate` function and waits for `predicate(request)` to return a truthy value. Will throw an error if
  9837. the page is closed before the `page.on('request_finished')` event is fired.
  9838. Parameters
  9839. ----------
  9840. predicate : Union[Callable[[Request], bool], None]
  9841. Receives the `Request` object and resolves to truthy value when the waiting should resolve.
  9842. timeout : Union[float, None]
  9843. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9844. default value can be changed by using the `browser_context.set_default_timeout()`.
  9845. Returns
  9846. -------
  9847. EventContextManager[Request]
  9848. """
  9849. return AsyncEventContextManager(
  9850. self._impl_obj.expect_request_finished(
  9851. predicate=self._wrap_handler(predicate), timeout=timeout
  9852. ).future
  9853. )
  9854. def expect_response(
  9855. self,
  9856. url_or_predicate: typing.Union[
  9857. str, typing.Pattern[str], typing.Callable[["Response"], bool]
  9858. ],
  9859. *,
  9860. timeout: typing.Optional[float] = None,
  9861. ) -> AsyncEventContextManager["Response"]:
  9862. """Page.expect_response
  9863. Returns the matched response. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more details about
  9864. events.
  9865. **Usage**
  9866. ```py
  9867. async with page.expect_response(\"https://example.com/resource\") as response_info:
  9868. await page.get_by_text(\"trigger response\").click()
  9869. response = await response_info.value
  9870. return response.ok
  9871. # or with a lambda
  9872. async with page.expect_response(lambda response: response.url == \"https://example.com\" and response.status == 200 and response.request.method == \"get\") as response_info:
  9873. await page.get_by_text(\"trigger response\").click()
  9874. response = await response_info.value
  9875. return response.ok
  9876. ```
  9877. Parameters
  9878. ----------
  9879. url_or_predicate : Union[Callable[[Response], bool], Pattern[str], str]
  9880. Request URL string, regex or predicate receiving `Response` object. When a `baseURL` via the context options was
  9881. provided and the passed URL is a path, it gets merged via the
  9882. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  9883. timeout : Union[float, None]
  9884. Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
  9885. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9886. Returns
  9887. -------
  9888. EventContextManager[Response]
  9889. """
  9890. return AsyncEventContextManager(
  9891. self._impl_obj.expect_response(
  9892. urlOrPredicate=self._wrap_handler(url_or_predicate), timeout=timeout
  9893. ).future
  9894. )
  9895. def expect_websocket(
  9896. self,
  9897. predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
  9898. *,
  9899. timeout: typing.Optional[float] = None,
  9900. ) -> AsyncEventContextManager["WebSocket"]:
  9901. """Page.expect_websocket
  9902. Performs action and waits for a new `WebSocket`. If predicate is provided, it passes `WebSocket` value into the
  9903. `predicate` function and waits for `predicate(webSocket)` to return a truthy value. Will throw an error if the page
  9904. is closed before the WebSocket event is fired.
  9905. Parameters
  9906. ----------
  9907. predicate : Union[Callable[[WebSocket], bool], None]
  9908. Receives the `WebSocket` object and resolves to truthy value when the waiting should resolve.
  9909. timeout : Union[float, None]
  9910. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9911. default value can be changed by using the `browser_context.set_default_timeout()`.
  9912. Returns
  9913. -------
  9914. EventContextManager[WebSocket]
  9915. """
  9916. return AsyncEventContextManager(
  9917. self._impl_obj.expect_websocket(
  9918. predicate=self._wrap_handler(predicate), timeout=timeout
  9919. ).future
  9920. )
  9921. def expect_worker(
  9922. self,
  9923. predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
  9924. *,
  9925. timeout: typing.Optional[float] = None,
  9926. ) -> AsyncEventContextManager["Worker"]:
  9927. """Page.expect_worker
  9928. Performs action and waits for a new `Worker`. If predicate is provided, it passes `Worker` value into the
  9929. `predicate` function and waits for `predicate(worker)` to return a truthy value. Will throw an error if the page is
  9930. closed before the worker event is fired.
  9931. Parameters
  9932. ----------
  9933. predicate : Union[Callable[[Worker], bool], None]
  9934. Receives the `Worker` object and resolves to truthy value when the waiting should resolve.
  9935. timeout : Union[float, None]
  9936. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  9937. default value can be changed by using the `browser_context.set_default_timeout()`.
  9938. Returns
  9939. -------
  9940. EventContextManager[Worker]
  9941. """
  9942. return AsyncEventContextManager(
  9943. self._impl_obj.expect_worker(
  9944. predicate=self._wrap_handler(predicate), timeout=timeout
  9945. ).future
  9946. )
  9947. async def set_checked(
  9948. self,
  9949. selector: str,
  9950. checked: bool,
  9951. *,
  9952. position: typing.Optional[Position] = None,
  9953. timeout: typing.Optional[float] = None,
  9954. force: typing.Optional[bool] = None,
  9955. no_wait_after: typing.Optional[bool] = None,
  9956. strict: typing.Optional[bool] = None,
  9957. trial: typing.Optional[bool] = None,
  9958. ) -> None:
  9959. """Page.set_checked
  9960. This method checks or unchecks an element matching `selector` by performing the following steps:
  9961. 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
  9962. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  9963. 1. If the element already has the right checked state, this method returns immediately.
  9964. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  9965. the element is detached during the checks, the whole action is retried.
  9966. 1. Scroll the element into view if needed.
  9967. 1. Use `page.mouse` to click in the center of the element.
  9968. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  9969. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  9970. Passing zero timeout disables this.
  9971. Parameters
  9972. ----------
  9973. selector : str
  9974. A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
  9975. used.
  9976. checked : bool
  9977. Whether to check or uncheck the checkbox.
  9978. position : Union[{x: float, y: float}, None]
  9979. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  9980. the element.
  9981. timeout : Union[float, None]
  9982. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  9983. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  9984. force : Union[bool, None]
  9985. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  9986. no_wait_after : Union[bool, None]
  9987. This option has no effect.
  9988. Deprecated: This option has no effect.
  9989. strict : Union[bool, None]
  9990. When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
  9991. element, the call throws an exception.
  9992. trial : Union[bool, None]
  9993. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  9994. to `false`. Useful to wait until the element is ready for the action without performing it.
  9995. """
  9996. return mapping.from_maybe_impl(
  9997. await self._impl_obj.set_checked(
  9998. selector=selector,
  9999. checked=checked,
  10000. position=position,
  10001. timeout=timeout,
  10002. force=force,
  10003. noWaitAfter=no_wait_after,
  10004. strict=strict,
  10005. trial=trial,
  10006. )
  10007. )
  10008. async def add_locator_handler(
  10009. self,
  10010. locator: "Locator",
  10011. handler: typing.Union[
  10012. typing.Callable[["Locator"], typing.Any], typing.Callable[[], typing.Any]
  10013. ],
  10014. *,
  10015. no_wait_after: typing.Optional[bool] = None,
  10016. times: typing.Optional[int] = None,
  10017. ) -> None:
  10018. """Page.add_locator_handler
  10019. When testing a web page, sometimes unexpected overlays like a \"Sign up\" dialog appear and block actions you want to
  10020. automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making
  10021. them tricky to handle in automated tests.
  10022. This method lets you set up a special function, called a handler, that activates when it detects that overlay is
  10023. visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
  10024. Things to keep in mind:
  10025. - When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as
  10026. a part of your normal test flow, instead of using `page.add_locator_handler()`.
  10027. - Playwright checks for the overlay every time before executing or retrying an action that requires an
  10028. [actionability check](https://playwright.dev/python/docs/actionability), or before performing an auto-waiting assertion check. When overlay
  10029. is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the
  10030. handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't
  10031. perform any actions, the handler will not be triggered.
  10032. - After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible
  10033. anymore. You can opt-out of this behavior with `noWaitAfter`.
  10034. - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler.
  10035. If your handler takes too long, it might cause timeouts.
  10036. - You can register multiple handlers. However, only a single handler will be running at a time. Make sure the
  10037. actions within a handler don't depend on another handler.
  10038. **NOTE** Running the handler will alter your page state mid-test. For example it will change the currently focused
  10039. element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on
  10040. the focus and mouse state being unchanged.
  10041. For example, consider a test that calls `locator.focus()` followed by `keyboard.press()`. If your
  10042. handler clicks a button between these two actions, the focused element most likely will be wrong, and key press
  10043. will happen on the unexpected element. Use `locator.press()` instead to avoid this problem.
  10044. Another example is a series of mouse actions, where `mouse.move()` is followed by `mouse.down()`.
  10045. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down.
  10046. Prefer self-contained actions like `locator.click()` that do not rely on the state being unchanged by a
  10047. handler.
  10048. **Usage**
  10049. An example that closes a \"Sign up to the newsletter\" dialog when it appears:
  10050. ```py
  10051. # Setup the handler.
  10052. def handler():
  10053. page.get_by_role(\"button\", name=\"No thanks\").click()
  10054. page.add_locator_handler(page.get_by_text(\"Sign up to the newsletter\"), handler)
  10055. # Write the test as usual.
  10056. page.goto(\"https://example.com\")
  10057. page.get_by_role(\"button\", name=\"Start here\").click()
  10058. ```
  10059. An example that skips the \"Confirm your security details\" page when it is shown:
  10060. ```py
  10061. # Setup the handler.
  10062. def handler():
  10063. page.get_by_role(\"button\", name=\"Remind me later\").click()
  10064. page.add_locator_handler(page.get_by_text(\"Confirm your security details\"), handler)
  10065. # Write the test as usual.
  10066. page.goto(\"https://example.com\")
  10067. page.get_by_role(\"button\", name=\"Start here\").click()
  10068. ```
  10069. An example with a custom callback on every actionability check. It uses a `<body>` locator that is always visible,
  10070. so the handler is called before every actionability check. It is important to specify `noWaitAfter`, because the
  10071. handler does not hide the `<body>` element.
  10072. ```py
  10073. # Setup the handler.
  10074. def handler():
  10075. page.evaluate(\"window.removeObstructionsForTestIfNeeded()\")
  10076. page.add_locator_handler(page.locator(\"body\"), handler, no_wait_after=True)
  10077. # Write the test as usual.
  10078. page.goto(\"https://example.com\")
  10079. page.get_by_role(\"button\", name=\"Start here\").click()
  10080. ```
  10081. Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
  10082. invocations by setting `times`:
  10083. ```py
  10084. def handler(locator):
  10085. locator.click()
  10086. page.add_locator_handler(page.get_by_label(\"Close\"), handler, times=1)
  10087. ```
  10088. Parameters
  10089. ----------
  10090. locator : Locator
  10091. Locator that triggers the handler.
  10092. handler : Union[Callable[[Locator], Any], Callable[[], Any]]
  10093. Function that should be run once `locator` appears. This function should get rid of the element that blocks actions
  10094. like click.
  10095. no_wait_after : Union[bool, None]
  10096. By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then
  10097. Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of
  10098. this behavior, so that overlay can stay visible after the handler has run.
  10099. times : Union[int, None]
  10100. Specifies the maximum number of times this handler should be called. Unlimited by default.
  10101. """
  10102. return mapping.from_maybe_impl(
  10103. await self._impl_obj.add_locator_handler(
  10104. locator=locator._impl_obj,
  10105. handler=self._wrap_handler(handler),
  10106. noWaitAfter=no_wait_after,
  10107. times=times,
  10108. )
  10109. )
  10110. async def remove_locator_handler(self, locator: "Locator") -> None:
  10111. """Page.remove_locator_handler
  10112. Removes all locator handlers added by `page.add_locator_handler()` for a specific locator.
  10113. Parameters
  10114. ----------
  10115. locator : Locator
  10116. Locator passed to `page.add_locator_handler()`.
  10117. """
  10118. return mapping.from_maybe_impl(
  10119. await self._impl_obj.remove_locator_handler(locator=locator._impl_obj)
  10120. )
  10121. async def requests(self) -> typing.List["Request"]:
  10122. """Page.requests
  10123. Returns up to (currently) 100 last network request from this page. See `page.on('request')` for more details.
  10124. Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory
  10125. growth as new requests come in. Once collected, retrieving most information about the request is impossible.
  10126. Note that requests reported through the `page.on('request')` request are not collected, so there is a trade off
  10127. between efficient memory usage with `page.requests()` and the amount of available information reported
  10128. through `page.on('request')`.
  10129. Returns
  10130. -------
  10131. List[Request]
  10132. """
  10133. return mapping.from_impl_list(await self._impl_obj.requests())
  10134. async def console_messages(self) -> typing.List["ConsoleMessage"]:
  10135. """Page.console_messages
  10136. Returns up to (currently) 200 last console messages from this page. See `page.on('console')` for more details.
  10137. Returns
  10138. -------
  10139. List[ConsoleMessage]
  10140. """
  10141. return mapping.from_impl_list(await self._impl_obj.console_messages())
  10142. async def page_errors(self) -> typing.List["Error"]:
  10143. """Page.page_errors
  10144. Returns up to (currently) 200 last page errors from this page. See `page.on('page_error')` for more details.
  10145. Returns
  10146. -------
  10147. List[Error]
  10148. """
  10149. return mapping.from_impl_list(await self._impl_obj.page_errors())
  10150. mapping.register(PageImpl, Page)
  10151. class WebError(AsyncBase):
  10152. @property
  10153. def page(self) -> typing.Optional["Page"]:
  10154. """WebError.page
  10155. The page that produced this unhandled exception, if any.
  10156. Returns
  10157. -------
  10158. Union[Page, None]
  10159. """
  10160. return mapping.from_impl_nullable(self._impl_obj.page)
  10161. @property
  10162. def error(self) -> "Error":
  10163. """WebError.error
  10164. Unhandled error that was thrown.
  10165. Returns
  10166. -------
  10167. Error
  10168. """
  10169. return mapping.from_impl(self._impl_obj.error)
  10170. mapping.register(WebErrorImpl, WebError)
  10171. class BrowserContext(AsyncContextManager):
  10172. @typing.overload
  10173. def on(
  10174. self,
  10175. event: Literal["backgroundpage"],
  10176. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  10177. ) -> None:
  10178. """
  10179. This event is not emitted."""
  10180. @typing.overload
  10181. def on(
  10182. self,
  10183. event: Literal["close"],
  10184. f: typing.Callable[
  10185. ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]"
  10186. ],
  10187. ) -> None:
  10188. """
  10189. Emitted when Browser context gets closed. This might happen because of one of the following:
  10190. - Browser context is closed.
  10191. - Browser application is closed or crashed.
  10192. - The `browser.close()` method was called."""
  10193. @typing.overload
  10194. def on(
  10195. self,
  10196. event: Literal["console"],
  10197. f: typing.Callable[
  10198. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  10199. ],
  10200. ) -> None:
  10201. """
  10202. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  10203. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
  10204. **Usage**
  10205. ```py
  10206. async def print_args(msg):
  10207. values = []
  10208. for arg in msg.args:
  10209. values.append(await arg.json_value())
  10210. print(values)
  10211. context.on(\"console\", print_args)
  10212. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  10213. ```"""
  10214. @typing.overload
  10215. def on(
  10216. self,
  10217. event: Literal["dialog"],
  10218. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  10219. ) -> None:
  10220. """
  10221. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  10222. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  10223. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  10224. and actions like click will never finish.
  10225. **Usage**
  10226. ```python
  10227. context.on(\"dialog\", lambda dialog: dialog.accept())
  10228. ```
  10229. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  10230. automatically dismissed."""
  10231. @typing.overload
  10232. def on(
  10233. self,
  10234. event: Literal["page"],
  10235. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  10236. ) -> None:
  10237. """
  10238. The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
  10239. will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
  10240. specific page.
  10241. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  10242. popup with `window.open('http://example.com')`, this event will fire when the network request to
  10243. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  10244. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  10245. instead of similar methods on the `Page`.
  10246. ```py
  10247. async with context.expect_page() as page_info:
  10248. await page.get_by_text(\"open new page\").click(),
  10249. page = await page_info.value
  10250. print(await page.evaluate(\"location.href\"))
  10251. ```
  10252. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  10253. need it in most cases)."""
  10254. @typing.overload
  10255. def on(
  10256. self,
  10257. event: Literal["weberror"],
  10258. f: typing.Callable[["WebError"], "typing.Union[typing.Awaitable[None], None]"],
  10259. ) -> None:
  10260. """
  10261. Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
  10262. page, use `page.on('page_error')` instead."""
  10263. @typing.overload
  10264. def on(
  10265. self,
  10266. event: Literal["request"],
  10267. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  10268. ) -> None:
  10269. """
  10270. Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
  10271. only listen for requests from a particular page, use `page.on('request')`.
  10272. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
  10273. """
  10274. @typing.overload
  10275. def on(
  10276. self,
  10277. event: Literal["requestfailed"],
  10278. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  10279. ) -> None:
  10280. """
  10281. Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
  10282. use `page.on('request_failed')`.
  10283. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  10284. will complete with `browser_context.on('request_finished')` event and not with
  10285. `browser_context.on('request_failed')`."""
  10286. @typing.overload
  10287. def on(
  10288. self,
  10289. event: Literal["requestfinished"],
  10290. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  10291. ) -> None:
  10292. """
  10293. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  10294. sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
  10295. particular page, use `page.on('request_finished')`."""
  10296. @typing.overload
  10297. def on(
  10298. self,
  10299. event: Literal["response"],
  10300. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  10301. ) -> None:
  10302. """
  10303. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  10304. events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
  10305. `page.on('response')`."""
  10306. @typing.overload
  10307. def on(
  10308. self,
  10309. event: Literal["serviceworker"],
  10310. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  10311. ) -> None:
  10312. """
  10313. **NOTE** Service workers are only supported on Chromium-based browsers.
  10314. Emitted when new service worker is created in the context."""
  10315. def on(
  10316. self,
  10317. event: str,
  10318. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  10319. ) -> None:
  10320. return super().on(event=event, f=f)
  10321. @typing.overload
  10322. def once(
  10323. self,
  10324. event: Literal["backgroundpage"],
  10325. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  10326. ) -> None:
  10327. """
  10328. This event is not emitted."""
  10329. @typing.overload
  10330. def once(
  10331. self,
  10332. event: Literal["close"],
  10333. f: typing.Callable[
  10334. ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]"
  10335. ],
  10336. ) -> None:
  10337. """
  10338. Emitted when Browser context gets closed. This might happen because of one of the following:
  10339. - Browser context is closed.
  10340. - Browser application is closed or crashed.
  10341. - The `browser.close()` method was called."""
  10342. @typing.overload
  10343. def once(
  10344. self,
  10345. event: Literal["console"],
  10346. f: typing.Callable[
  10347. ["ConsoleMessage"], "typing.Union[typing.Awaitable[None], None]"
  10348. ],
  10349. ) -> None:
  10350. """
  10351. Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
  10352. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
  10353. **Usage**
  10354. ```py
  10355. async def print_args(msg):
  10356. values = []
  10357. for arg in msg.args:
  10358. values.append(await arg.json_value())
  10359. print(values)
  10360. context.on(\"console\", print_args)
  10361. await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
  10362. ```"""
  10363. @typing.overload
  10364. def once(
  10365. self,
  10366. event: Literal["dialog"],
  10367. f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], None]"],
  10368. ) -> None:
  10369. """
  10370. Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
  10371. either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
  10372. [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
  10373. and actions like click will never finish.
  10374. **Usage**
  10375. ```python
  10376. context.on(\"dialog\", lambda dialog: dialog.accept())
  10377. ```
  10378. **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
  10379. automatically dismissed."""
  10380. @typing.overload
  10381. def once(
  10382. self,
  10383. event: Literal["page"],
  10384. f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"],
  10385. ) -> None:
  10386. """
  10387. The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
  10388. will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
  10389. specific page.
  10390. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
  10391. popup with `window.open('http://example.com')`, this event will fire when the network request to
  10392. \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
  10393. to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
  10394. instead of similar methods on the `Page`.
  10395. ```py
  10396. async with context.expect_page() as page_info:
  10397. await page.get_by_text(\"open new page\").click(),
  10398. page = await page_info.value
  10399. print(await page.evaluate(\"location.href\"))
  10400. ```
  10401. **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
  10402. need it in most cases)."""
  10403. @typing.overload
  10404. def once(
  10405. self,
  10406. event: Literal["weberror"],
  10407. f: typing.Callable[["WebError"], "typing.Union[typing.Awaitable[None], None]"],
  10408. ) -> None:
  10409. """
  10410. Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
  10411. page, use `page.on('page_error')` instead."""
  10412. @typing.overload
  10413. def once(
  10414. self,
  10415. event: Literal["request"],
  10416. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  10417. ) -> None:
  10418. """
  10419. Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
  10420. only listen for requests from a particular page, use `page.on('request')`.
  10421. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
  10422. """
  10423. @typing.overload
  10424. def once(
  10425. self,
  10426. event: Literal["requestfailed"],
  10427. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  10428. ) -> None:
  10429. """
  10430. Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
  10431. use `page.on('request_failed')`.
  10432. **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
  10433. will complete with `browser_context.on('request_finished')` event and not with
  10434. `browser_context.on('request_failed')`."""
  10435. @typing.overload
  10436. def once(
  10437. self,
  10438. event: Literal["requestfinished"],
  10439. f: typing.Callable[["Request"], "typing.Union[typing.Awaitable[None], None]"],
  10440. ) -> None:
  10441. """
  10442. Emitted when a request finishes successfully after downloading the response body. For a successful response, the
  10443. sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
  10444. particular page, use `page.on('request_finished')`."""
  10445. @typing.overload
  10446. def once(
  10447. self,
  10448. event: Literal["response"],
  10449. f: typing.Callable[["Response"], "typing.Union[typing.Awaitable[None], None]"],
  10450. ) -> None:
  10451. """
  10452. Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
  10453. events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
  10454. `page.on('response')`."""
  10455. @typing.overload
  10456. def once(
  10457. self,
  10458. event: Literal["serviceworker"],
  10459. f: typing.Callable[["Worker"], "typing.Union[typing.Awaitable[None], None]"],
  10460. ) -> None:
  10461. """
  10462. **NOTE** Service workers are only supported on Chromium-based browsers.
  10463. Emitted when new service worker is created in the context."""
  10464. def once(
  10465. self,
  10466. event: str,
  10467. f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]],
  10468. ) -> None:
  10469. return super().once(event=event, f=f)
  10470. @property
  10471. def pages(self) -> typing.List["Page"]:
  10472. """BrowserContext.pages
  10473. Returns all open pages in the context.
  10474. Returns
  10475. -------
  10476. List[Page]
  10477. """
  10478. return mapping.from_impl_list(self._impl_obj.pages)
  10479. @property
  10480. def browser(self) -> typing.Optional["Browser"]:
  10481. """BrowserContext.browser
  10482. Gets the browser instance that owns the context. Returns `null` if the context is created outside of normal
  10483. browser, e.g. Android or Electron.
  10484. Returns
  10485. -------
  10486. Union[Browser, None]
  10487. """
  10488. return mapping.from_impl_nullable(self._impl_obj.browser)
  10489. @property
  10490. def background_pages(self) -> typing.List["Page"]:
  10491. """BrowserContext.background_pages
  10492. Returns an empty list.
  10493. Returns
  10494. -------
  10495. List[Page]
  10496. """
  10497. return mapping.from_impl_list(self._impl_obj.background_pages)
  10498. @property
  10499. def service_workers(self) -> typing.List["Worker"]:
  10500. """BrowserContext.service_workers
  10501. **NOTE** Service workers are only supported on Chromium-based browsers.
  10502. All existing service workers in the context.
  10503. Returns
  10504. -------
  10505. List[Worker]
  10506. """
  10507. return mapping.from_impl_list(self._impl_obj.service_workers)
  10508. @property
  10509. def tracing(self) -> "Tracing":
  10510. """BrowserContext.tracing
  10511. Returns
  10512. -------
  10513. Tracing
  10514. """
  10515. return mapping.from_impl(self._impl_obj.tracing)
  10516. @property
  10517. def request(self) -> "APIRequestContext":
  10518. """BrowserContext.request
  10519. API testing helper associated with this context. Requests made with this API will use context cookies.
  10520. Returns
  10521. -------
  10522. APIRequestContext
  10523. """
  10524. return mapping.from_impl(self._impl_obj.request)
  10525. @property
  10526. def clock(self) -> "Clock":
  10527. """BrowserContext.clock
  10528. Playwright has ability to mock clock and passage of time.
  10529. Returns
  10530. -------
  10531. Clock
  10532. """
  10533. return mapping.from_impl(self._impl_obj.clock)
  10534. def set_default_navigation_timeout(self, timeout: float) -> None:
  10535. """BrowserContext.set_default_navigation_timeout
  10536. This setting will change the default maximum navigation time for the following methods and related shortcuts:
  10537. - `page.go_back()`
  10538. - `page.go_forward()`
  10539. - `page.goto()`
  10540. - `page.reload()`
  10541. - `page.set_content()`
  10542. - `page.expect_navigation()`
  10543. **NOTE** `page.set_default_navigation_timeout()` and `page.set_default_timeout()` take priority over
  10544. `browser_context.set_default_navigation_timeout()`.
  10545. Parameters
  10546. ----------
  10547. timeout : float
  10548. Maximum navigation time in milliseconds
  10549. """
  10550. return mapping.from_maybe_impl(
  10551. self._impl_obj.set_default_navigation_timeout(timeout=timeout)
  10552. )
  10553. def set_default_timeout(self, timeout: float) -> None:
  10554. """BrowserContext.set_default_timeout
  10555. This setting will change the default maximum time for all the methods accepting `timeout` option.
  10556. **NOTE** `page.set_default_navigation_timeout()`, `page.set_default_timeout()` and
  10557. `browser_context.set_default_navigation_timeout()` take priority over
  10558. `browser_context.set_default_timeout()`.
  10559. Parameters
  10560. ----------
  10561. timeout : float
  10562. Maximum time in milliseconds. Pass `0` to disable timeout.
  10563. """
  10564. return mapping.from_maybe_impl(
  10565. self._impl_obj.set_default_timeout(timeout=timeout)
  10566. )
  10567. async def new_page(self) -> "Page":
  10568. """BrowserContext.new_page
  10569. Creates a new page in the browser context.
  10570. Returns
  10571. -------
  10572. Page
  10573. """
  10574. return mapping.from_impl(await self._impl_obj.new_page())
  10575. async def cookies(
  10576. self, urls: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None
  10577. ) -> typing.List[Cookie]:
  10578. """BrowserContext.cookies
  10579. If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
  10580. URLs are returned.
  10581. Parameters
  10582. ----------
  10583. urls : Union[Sequence[str], str, None]
  10584. Optional list of URLs.
  10585. Returns
  10586. -------
  10587. List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}]
  10588. """
  10589. return mapping.from_impl_list(
  10590. await self._impl_obj.cookies(urls=mapping.to_impl(urls))
  10591. )
  10592. async def add_cookies(self, cookies: typing.Sequence[SetCookieParam]) -> None:
  10593. """BrowserContext.add_cookies
  10594. Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies
  10595. can be obtained via `browser_context.cookies()`.
  10596. **Usage**
  10597. ```py
  10598. await browser_context.add_cookies([cookie_object1, cookie_object2])
  10599. ```
  10600. Parameters
  10601. ----------
  10602. 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]}]
  10603. """
  10604. return mapping.from_maybe_impl(
  10605. await self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies))
  10606. )
  10607. async def clear_cookies(
  10608. self,
  10609. *,
  10610. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  10611. domain: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  10612. path: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  10613. ) -> None:
  10614. """BrowserContext.clear_cookies
  10615. Removes cookies from context. Accepts optional filter.
  10616. **Usage**
  10617. ```py
  10618. await context.clear_cookies()
  10619. await context.clear_cookies(name=\"session-id\")
  10620. await context.clear_cookies(domain=\"my-origin.com\")
  10621. await context.clear_cookies(path=\"/api/v1\")
  10622. await context.clear_cookies(name=\"session-id\", domain=\"my-origin.com\")
  10623. ```
  10624. Parameters
  10625. ----------
  10626. name : Union[Pattern[str], str, None]
  10627. Only removes cookies with the given name.
  10628. domain : Union[Pattern[str], str, None]
  10629. Only removes cookies with the given domain.
  10630. path : Union[Pattern[str], str, None]
  10631. Only removes cookies with the given path.
  10632. """
  10633. return mapping.from_maybe_impl(
  10634. await self._impl_obj.clear_cookies(name=name, domain=domain, path=path)
  10635. )
  10636. async def grant_permissions(
  10637. self, permissions: typing.Sequence[str], *, origin: typing.Optional[str] = None
  10638. ) -> None:
  10639. """BrowserContext.grant_permissions
  10640. Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
  10641. specified.
  10642. Parameters
  10643. ----------
  10644. permissions : Sequence[str]
  10645. A list of permissions to grant.
  10646. **NOTE** Supported permissions differ between browsers, and even between different versions of the same browser.
  10647. Any permission may stop working after an update.
  10648. Here are some permissions that may be supported by some browsers:
  10649. - `'accelerometer'`
  10650. - `'ambient-light-sensor'`
  10651. - `'background-sync'`
  10652. - `'camera'`
  10653. - `'clipboard-read'`
  10654. - `'clipboard-write'`
  10655. - `'geolocation'`
  10656. - `'gyroscope'`
  10657. - `'local-fonts'`
  10658. - `'local-network-access'`
  10659. - `'magnetometer'`
  10660. - `'microphone'`
  10661. - `'midi-sysex'` (system-exclusive midi)
  10662. - `'midi'`
  10663. - `'notifications'`
  10664. - `'payment-handler'`
  10665. - `'storage-access'`
  10666. origin : Union[str, None]
  10667. The [origin] to grant permissions to, e.g. "https://example.com".
  10668. """
  10669. return mapping.from_maybe_impl(
  10670. await self._impl_obj.grant_permissions(
  10671. permissions=mapping.to_impl(permissions), origin=origin
  10672. )
  10673. )
  10674. async def clear_permissions(self) -> None:
  10675. """BrowserContext.clear_permissions
  10676. Clears all permission overrides for the browser context.
  10677. **Usage**
  10678. ```py
  10679. context = await browser.new_context()
  10680. await context.grant_permissions([\"clipboard-read\"])
  10681. # do stuff ..
  10682. context.clear_permissions()
  10683. ```
  10684. """
  10685. return mapping.from_maybe_impl(await self._impl_obj.clear_permissions())
  10686. async def set_geolocation(
  10687. self, geolocation: typing.Optional[Geolocation] = None
  10688. ) -> None:
  10689. """BrowserContext.set_geolocation
  10690. Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
  10691. **Usage**
  10692. ```py
  10693. await browser_context.set_geolocation({\"latitude\": 59.95, \"longitude\": 30.31667})
  10694. ```
  10695. **NOTE** Consider using `browser_context.grant_permissions()` to grant permissions for the browser context
  10696. pages to read its geolocation.
  10697. Parameters
  10698. ----------
  10699. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  10700. """
  10701. return mapping.from_maybe_impl(
  10702. await self._impl_obj.set_geolocation(geolocation=geolocation)
  10703. )
  10704. async def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
  10705. """BrowserContext.set_extra_http_headers
  10706. The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are
  10707. merged with page-specific extra HTTP headers set with `page.set_extra_http_headers()`. If page overrides a
  10708. particular header, page-specific header value will be used instead of the browser context header value.
  10709. **NOTE** `browser_context.set_extra_http_headers()` does not guarantee the order of headers in the outgoing
  10710. requests.
  10711. Parameters
  10712. ----------
  10713. headers : Dict[str, str]
  10714. An object containing additional HTTP headers to be sent with every request. All header values must be strings.
  10715. """
  10716. return mapping.from_maybe_impl(
  10717. await self._impl_obj.set_extra_http_headers(
  10718. headers=mapping.to_impl(headers)
  10719. )
  10720. )
  10721. async def set_offline(self, offline: bool) -> None:
  10722. """BrowserContext.set_offline
  10723. Parameters
  10724. ----------
  10725. offline : bool
  10726. Whether to emulate network being offline for the browser context.
  10727. """
  10728. return mapping.from_maybe_impl(
  10729. await self._impl_obj.set_offline(offline=offline)
  10730. )
  10731. async def add_init_script(
  10732. self,
  10733. script: typing.Optional[str] = None,
  10734. *,
  10735. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  10736. ) -> None:
  10737. """BrowserContext.add_init_script
  10738. Adds a script which would be evaluated in one of the following scenarios:
  10739. - Whenever a page is created in the browser context or is navigated.
  10740. - Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is
  10741. evaluated in the context of the newly attached frame.
  10742. The script is evaluated after the document was created but before any of its scripts were run. This is useful to
  10743. amend the JavaScript environment, e.g. to seed `Math.random`.
  10744. **Usage**
  10745. An example of overriding `Math.random` before the page loads:
  10746. ```py
  10747. # in your playwright script, assuming the preload.js file is in same directory.
  10748. await browser_context.add_init_script(path=\"preload.js\")
  10749. ```
  10750. **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
  10751. `page.add_init_script()` is not defined.
  10752. Parameters
  10753. ----------
  10754. script : Union[str, None]
  10755. Script to be evaluated in all pages in the browser context. Optional.
  10756. path : Union[pathlib.Path, str, None]
  10757. Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
  10758. directory. Optional.
  10759. """
  10760. return mapping.from_maybe_impl(
  10761. await self._impl_obj.add_init_script(script=script, path=path)
  10762. )
  10763. async def expose_binding(
  10764. self,
  10765. name: str,
  10766. callback: typing.Callable,
  10767. *,
  10768. handle: typing.Optional[bool] = None,
  10769. ) -> None:
  10770. """BrowserContext.expose_binding
  10771. The method adds a function called `name` on the `window` object of every frame in every page in the context. When
  10772. called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  10773. If the `callback` returns a [Promise], it will be awaited.
  10774. The first argument of the `callback` function contains information about the caller: `{ browserContext:
  10775. BrowserContext, page: Page, frame: Frame }`.
  10776. See `page.expose_binding()` for page-only version.
  10777. **Usage**
  10778. An example of exposing page URL to all frames in all pages in the context:
  10779. ```py
  10780. import asyncio
  10781. from playwright.async_api import async_playwright, Playwright
  10782. async def run(playwright: Playwright):
  10783. webkit = playwright.webkit
  10784. browser = await webkit.launch(headless=False)
  10785. context = await browser.new_context()
  10786. await context.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
  10787. page = await context.new_page()
  10788. await page.set_content(\"\"\"
  10789. <script>
  10790. async function onClick() {
  10791. document.querySelector('div').textContent = await window.pageURL();
  10792. }
  10793. </script>
  10794. <button onclick=\"onClick()\">Click me</button>
  10795. <div></div>
  10796. \"\"\")
  10797. await page.get_by_role(\"button\").click()
  10798. async def main():
  10799. async with async_playwright() as playwright:
  10800. await run(playwright)
  10801. asyncio.run(main())
  10802. ```
  10803. Parameters
  10804. ----------
  10805. name : str
  10806. Name of the function on the window object.
  10807. callback : Callable
  10808. Callback function that will be called in the Playwright's context.
  10809. handle : Union[bool, None]
  10810. Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
  10811. supported. When passing by value, multiple arguments are supported.
  10812. Deprecated: This option will be removed in the future.
  10813. """
  10814. return mapping.from_maybe_impl(
  10815. await self._impl_obj.expose_binding(
  10816. name=name, callback=self._wrap_handler(callback), handle=handle
  10817. )
  10818. )
  10819. async def expose_function(self, name: str, callback: typing.Callable) -> None:
  10820. """BrowserContext.expose_function
  10821. The method adds a function called `name` on the `window` object of every frame in every page in the context. When
  10822. called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
  10823. If the `callback` returns a [Promise], it will be awaited.
  10824. See `page.expose_function()` for page-only version.
  10825. **Usage**
  10826. An example of adding a `sha256` function to all pages in the context:
  10827. ```py
  10828. import asyncio
  10829. import hashlib
  10830. from playwright.async_api import async_playwright, Playwright
  10831. def sha256(text: str) -> str:
  10832. m = hashlib.sha256()
  10833. m.update(bytes(text, \"utf8\"))
  10834. return m.hexdigest()
  10835. async def run(playwright: Playwright):
  10836. webkit = playwright.webkit
  10837. browser = await webkit.launch(headless=False)
  10838. context = await browser.new_context()
  10839. await context.expose_function(\"sha256\", sha256)
  10840. page = await context.new_page()
  10841. await page.set_content(\"\"\"
  10842. <script>
  10843. async function onClick() {
  10844. document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  10845. }
  10846. </script>
  10847. <button onclick=\"onClick()\">Click me</button>
  10848. <div></div>
  10849. \"\"\")
  10850. await page.get_by_role(\"button\").click()
  10851. async def main():
  10852. async with async_playwright() as playwright:
  10853. await run(playwright)
  10854. asyncio.run(main())
  10855. ```
  10856. Parameters
  10857. ----------
  10858. name : str
  10859. Name of the function on the window object.
  10860. callback : Callable
  10861. Callback function that will be called in the Playwright's context.
  10862. """
  10863. return mapping.from_maybe_impl(
  10864. await self._impl_obj.expose_function(
  10865. name=name, callback=self._wrap_handler(callback)
  10866. )
  10867. )
  10868. async def route(
  10869. self,
  10870. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  10871. handler: typing.Union[
  10872. typing.Callable[["Route"], typing.Any],
  10873. typing.Callable[["Route", "Request"], typing.Any],
  10874. ],
  10875. *,
  10876. times: typing.Optional[int] = None,
  10877. ) -> None:
  10878. """BrowserContext.route
  10879. Routing provides the capability to modify network requests that are made by any page in the browser context. Once
  10880. route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
  10881. **NOTE** `browser_context.route()` will not intercept requests intercepted by Service Worker. See
  10882. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  10883. using request interception by setting `serviceWorkers` to `'block'`.
  10884. **Usage**
  10885. An example of a naive handler that aborts all image requests:
  10886. ```py
  10887. context = await browser.new_context()
  10888. page = await context.new_page()
  10889. await context.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
  10890. await page.goto(\"https://example.com\")
  10891. await browser.close()
  10892. ```
  10893. or the same snippet using a regex pattern instead:
  10894. ```py
  10895. context = await browser.new_context()
  10896. page = await context.new_page()
  10897. await context.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
  10898. page = await context.new_page()
  10899. await page.goto(\"https://example.com\")
  10900. await browser.close()
  10901. ```
  10902. It is possible to examine the request to decide the route action. For example, mocking all requests that contain
  10903. some post data, and leaving all other requests as is:
  10904. ```py
  10905. async def handle_route(route: Route):
  10906. if (\"my-string\" in route.request.post_data):
  10907. await route.fulfill(body=\"mocked-data\")
  10908. else:
  10909. await route.continue_()
  10910. await context.route(\"/api/**\", handle_route)
  10911. ```
  10912. Page routes (set up with `page.route()`) take precedence over browser context routes when request matches
  10913. both handlers.
  10914. To remove a route with its handler you can use `browser_context.unroute()`.
  10915. **NOTE** Enabling routing disables http cache.
  10916. Parameters
  10917. ----------
  10918. url : Union[Callable[[str], bool], Pattern[str], str]
  10919. A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
  10920. the context options and the provided URL is a string that does not start with `*`, it is resolved using the
  10921. [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
  10922. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
  10923. handler function to route the request.
  10924. times : Union[int, None]
  10925. How often a route should be used. By default it will be used every time.
  10926. """
  10927. return mapping.from_maybe_impl(
  10928. await self._impl_obj.route(
  10929. url=self._wrap_handler(url),
  10930. handler=self._wrap_handler(handler),
  10931. times=times,
  10932. )
  10933. )
  10934. async def unroute(
  10935. self,
  10936. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  10937. handler: typing.Optional[
  10938. typing.Union[
  10939. typing.Callable[["Route"], typing.Any],
  10940. typing.Callable[["Route", "Request"], typing.Any],
  10941. ]
  10942. ] = None,
  10943. ) -> None:
  10944. """BrowserContext.unroute
  10945. Removes a route created with `browser_context.route()`. When `handler` is not specified, removes all routes
  10946. for the `url`.
  10947. Parameters
  10948. ----------
  10949. url : Union[Callable[[str], bool], Pattern[str], str]
  10950. A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
  10951. `browser_context.route()`.
  10952. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
  10953. Optional handler function used to register a routing with `browser_context.route()`.
  10954. """
  10955. return mapping.from_maybe_impl(
  10956. await self._impl_obj.unroute(
  10957. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  10958. )
  10959. )
  10960. async def route_web_socket(
  10961. self,
  10962. url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
  10963. handler: typing.Callable[["WebSocketRoute"], typing.Any],
  10964. ) -> None:
  10965. """BrowserContext.route_web_socket
  10966. This method allows to modify websocket connections that are made by any page in the browser context.
  10967. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
  10968. method before creating any pages.
  10969. **Usage**
  10970. Below is an example of a simple handler that blocks some websocket messages. See `WebSocketRoute` for more details
  10971. and examples.
  10972. ```py
  10973. def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  10974. if message == \"to-be-blocked\":
  10975. return
  10976. ws.send(message)
  10977. async def handler(ws: WebSocketRoute):
  10978. ws.route_send(lambda message: message_handler(ws, message))
  10979. await ws.connect()
  10980. await context.route_web_socket(\"/ws\", handler)
  10981. ```
  10982. Parameters
  10983. ----------
  10984. url : Union[Callable[[str], bool], Pattern[str], str]
  10985. Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
  10986. `baseURL` context option.
  10987. handler : Callable[[WebSocketRoute], Any]
  10988. Handler function to route the WebSocket.
  10989. """
  10990. return mapping.from_maybe_impl(
  10991. await self._impl_obj.route_web_socket(
  10992. url=self._wrap_handler(url), handler=self._wrap_handler(handler)
  10993. )
  10994. )
  10995. async def unroute_all(
  10996. self,
  10997. *,
  10998. behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
  10999. ) -> None:
  11000. """BrowserContext.unroute_all
  11001. Removes all routes created with `browser_context.route()` and `browser_context.route_from_har()`.
  11002. Parameters
  11003. ----------
  11004. behavior : Union["default", "ignoreErrors", "wait", None]
  11005. Specifies whether to wait for already running handlers and what to do if they throw errors:
  11006. - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
  11007. result in unhandled error
  11008. - `'wait'` - wait for current handler calls (if any) to finish
  11009. - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
  11010. after unrouting are silently caught
  11011. """
  11012. return mapping.from_maybe_impl(
  11013. await self._impl_obj.unroute_all(behavior=behavior)
  11014. )
  11015. async def route_from_har(
  11016. self,
  11017. har: typing.Union[pathlib.Path, str],
  11018. *,
  11019. url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  11020. not_found: typing.Optional[Literal["abort", "fallback"]] = None,
  11021. update: typing.Optional[bool] = None,
  11022. update_content: typing.Optional[Literal["attach", "embed"]] = None,
  11023. update_mode: typing.Optional[Literal["full", "minimal"]] = None,
  11024. ) -> None:
  11025. """BrowserContext.route_from_har
  11026. If specified the network requests that are made in the context will be served from the HAR file. Read more about
  11027. [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
  11028. Playwright will not serve requests intercepted by Service Worker from the HAR file. See
  11029. [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
  11030. using request interception by setting `serviceWorkers` to `'block'`.
  11031. Parameters
  11032. ----------
  11033. har : Union[pathlib.Path, str]
  11034. Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
  11035. relative path, then it is resolved relative to the current working directory.
  11036. url : Union[Pattern[str], str, None]
  11037. A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
  11038. pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
  11039. not_found : Union["abort", "fallback", None]
  11040. - If set to 'abort' any request not found in the HAR file will be aborted.
  11041. - If set to 'fallback' falls through to the next route handler in the handler chain.
  11042. Defaults to abort.
  11043. update : Union[bool, None]
  11044. If specified, updates the given HAR with the actual network information instead of serving from file. The file is
  11045. written to disk when `browser_context.close()` is called.
  11046. update_content : Union["attach", "embed", None]
  11047. Optional setting to control resource content management. If `attach` is specified, resources are persisted as
  11048. separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
  11049. update_mode : Union["full", "minimal", None]
  11050. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  11051. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
  11052. `minimal`.
  11053. """
  11054. return mapping.from_maybe_impl(
  11055. await self._impl_obj.route_from_har(
  11056. har=har,
  11057. url=url,
  11058. notFound=not_found,
  11059. update=update,
  11060. updateContent=update_content,
  11061. updateMode=update_mode,
  11062. )
  11063. )
  11064. def expect_event(
  11065. self,
  11066. event: str,
  11067. predicate: typing.Optional[typing.Callable] = None,
  11068. *,
  11069. timeout: typing.Optional[float] = None,
  11070. ) -> AsyncEventContextManager:
  11071. """BrowserContext.expect_event
  11072. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
  11073. value. Will throw an error if the context closes before the event is fired. Returns the event data value.
  11074. **Usage**
  11075. ```py
  11076. async with context.expect_event(\"page\") as event_info:
  11077. await page.get_by_role(\"button\").click()
  11078. page = await event_info.value
  11079. ```
  11080. Parameters
  11081. ----------
  11082. event : str
  11083. Event name, same one would pass into `browserContext.on(event)`.
  11084. predicate : Union[Callable, None]
  11085. Receives the event data and resolves to truthy value when the waiting should resolve.
  11086. timeout : Union[float, None]
  11087. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11088. default value can be changed by using the `browser_context.set_default_timeout()`.
  11089. Returns
  11090. -------
  11091. EventContextManager
  11092. """
  11093. return AsyncEventContextManager(
  11094. self._impl_obj.expect_event(
  11095. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  11096. ).future
  11097. )
  11098. async def close(self, *, reason: typing.Optional[str] = None) -> None:
  11099. """BrowserContext.close
  11100. Closes the browser context. All the pages that belong to the browser context will be closed.
  11101. **NOTE** The default browser context cannot be closed.
  11102. Parameters
  11103. ----------
  11104. reason : Union[str, None]
  11105. The reason to be reported to the operations interrupted by the context closure.
  11106. """
  11107. return mapping.from_maybe_impl(await self._impl_obj.close(reason=reason))
  11108. async def storage_state(
  11109. self,
  11110. *,
  11111. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11112. indexed_db: typing.Optional[bool] = None,
  11113. ) -> StorageState:
  11114. """BrowserContext.storage_state
  11115. Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB
  11116. snapshot.
  11117. Parameters
  11118. ----------
  11119. path : Union[pathlib.Path, str, None]
  11120. The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
  11121. working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
  11122. indexed_db : Union[bool, None]
  11123. Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage
  11124. state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication,
  11125. enable this.
  11126. Returns
  11127. -------
  11128. {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}]}]}
  11129. """
  11130. return mapping.from_impl(
  11131. await self._impl_obj.storage_state(path=path, indexedDB=indexed_db)
  11132. )
  11133. async def wait_for_event(
  11134. self,
  11135. event: str,
  11136. predicate: typing.Optional[typing.Callable] = None,
  11137. *,
  11138. timeout: typing.Optional[float] = None,
  11139. ) -> typing.Any:
  11140. """BrowserContext.wait_for_event
  11141. **NOTE** In most cases, you should use `browser_context.expect_event()`.
  11142. Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
  11143. and waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed
  11144. before the `event` is fired.
  11145. Parameters
  11146. ----------
  11147. event : str
  11148. Event name, same one typically passed into `*.on(event)`.
  11149. predicate : Union[Callable, None]
  11150. Receives the event data and resolves to truthy value when the waiting should resolve.
  11151. timeout : Union[float, None]
  11152. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11153. default value can be changed by using the `browser_context.set_default_timeout()`.
  11154. Returns
  11155. -------
  11156. Any
  11157. """
  11158. return mapping.from_maybe_impl(
  11159. await self._impl_obj.wait_for_event(
  11160. event=event, predicate=self._wrap_handler(predicate), timeout=timeout
  11161. )
  11162. )
  11163. def expect_console_message(
  11164. self,
  11165. predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
  11166. *,
  11167. timeout: typing.Optional[float] = None,
  11168. ) -> AsyncEventContextManager["ConsoleMessage"]:
  11169. """BrowserContext.expect_console_message
  11170. Performs action and waits for a `ConsoleMessage` to be logged by in the pages in the context. If predicate is
  11171. provided, it passes `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to
  11172. return a truthy value. Will throw an error if the page is closed before the `browser_context.on('console')` event
  11173. is fired.
  11174. Parameters
  11175. ----------
  11176. predicate : Union[Callable[[ConsoleMessage], bool], None]
  11177. Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
  11178. timeout : Union[float, None]
  11179. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11180. default value can be changed by using the `browser_context.set_default_timeout()`.
  11181. Returns
  11182. -------
  11183. EventContextManager[ConsoleMessage]
  11184. """
  11185. return AsyncEventContextManager(
  11186. self._impl_obj.expect_console_message(
  11187. predicate=self._wrap_handler(predicate), timeout=timeout
  11188. ).future
  11189. )
  11190. def expect_page(
  11191. self,
  11192. predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
  11193. *,
  11194. timeout: typing.Optional[float] = None,
  11195. ) -> AsyncEventContextManager["Page"]:
  11196. """BrowserContext.expect_page
  11197. Performs action and waits for a new `Page` to be created in the context. If predicate is provided, it passes `Page`
  11198. value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error
  11199. if the context closes before new `Page` is created.
  11200. Parameters
  11201. ----------
  11202. predicate : Union[Callable[[Page], bool], None]
  11203. Receives the `Page` object and resolves to truthy value when the waiting should resolve.
  11204. timeout : Union[float, None]
  11205. Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
  11206. default value can be changed by using the `browser_context.set_default_timeout()`.
  11207. Returns
  11208. -------
  11209. EventContextManager[Page]
  11210. """
  11211. return AsyncEventContextManager(
  11212. self._impl_obj.expect_page(
  11213. predicate=self._wrap_handler(predicate), timeout=timeout
  11214. ).future
  11215. )
  11216. async def new_cdp_session(
  11217. self, page: typing.Union["Page", "Frame"]
  11218. ) -> "CDPSession":
  11219. """BrowserContext.new_cdp_session
  11220. **NOTE** CDP sessions are only supported on Chromium-based browsers.
  11221. Returns the newly created session.
  11222. Parameters
  11223. ----------
  11224. page : Union[Frame, Page]
  11225. Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a
  11226. `Page` or `Frame` type.
  11227. Returns
  11228. -------
  11229. CDPSession
  11230. """
  11231. return mapping.from_impl(await self._impl_obj.new_cdp_session(page=page))
  11232. mapping.register(BrowserContextImpl, BrowserContext)
  11233. class CDPSession(AsyncBase):
  11234. async def send(
  11235. self, method: str, params: typing.Optional[typing.Dict] = None
  11236. ) -> typing.Dict:
  11237. """CDPSession.send
  11238. Parameters
  11239. ----------
  11240. method : str
  11241. Protocol method name.
  11242. params : Union[Dict, None]
  11243. Optional method parameters.
  11244. Returns
  11245. -------
  11246. Dict
  11247. """
  11248. return mapping.from_maybe_impl(
  11249. await self._impl_obj.send(method=method, params=mapping.to_impl(params))
  11250. )
  11251. async def detach(self) -> None:
  11252. """CDPSession.detach
  11253. Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
  11254. used to send messages.
  11255. """
  11256. return mapping.from_maybe_impl(await self._impl_obj.detach())
  11257. mapping.register(CDPSessionImpl, CDPSession)
  11258. class Browser(AsyncContextManager):
  11259. def on(
  11260. self,
  11261. event: Literal["disconnected"],
  11262. f: typing.Callable[["Browser"], "typing.Union[typing.Awaitable[None], None]"],
  11263. ) -> None:
  11264. """
  11265. Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
  11266. following:
  11267. - Browser application is closed or crashed.
  11268. - The `browser.close()` method was called."""
  11269. return super().on(event=event, f=f)
  11270. def once(
  11271. self,
  11272. event: Literal["disconnected"],
  11273. f: typing.Callable[["Browser"], "typing.Union[typing.Awaitable[None], None]"],
  11274. ) -> None:
  11275. """
  11276. Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
  11277. following:
  11278. - Browser application is closed or crashed.
  11279. - The `browser.close()` method was called."""
  11280. return super().once(event=event, f=f)
  11281. @property
  11282. def contexts(self) -> typing.List["BrowserContext"]:
  11283. """Browser.contexts
  11284. Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
  11285. **Usage**
  11286. ```py
  11287. browser = await pw.webkit.launch()
  11288. print(len(browser.contexts)) # prints `0`
  11289. context = await browser.new_context()
  11290. print(len(browser.contexts)) # prints `1`
  11291. ```
  11292. Returns
  11293. -------
  11294. List[BrowserContext]
  11295. """
  11296. return mapping.from_impl_list(self._impl_obj.contexts)
  11297. @property
  11298. def browser_type(self) -> "BrowserType":
  11299. """Browser.browser_type
  11300. Get the browser type (chromium, firefox or webkit) that the browser belongs to.
  11301. Returns
  11302. -------
  11303. BrowserType
  11304. """
  11305. return mapping.from_impl(self._impl_obj.browser_type)
  11306. @property
  11307. def version(self) -> str:
  11308. """Browser.version
  11309. Returns the browser version.
  11310. Returns
  11311. -------
  11312. str
  11313. """
  11314. return mapping.from_maybe_impl(self._impl_obj.version)
  11315. def is_connected(self) -> bool:
  11316. """Browser.is_connected
  11317. Indicates that the browser is connected.
  11318. Returns
  11319. -------
  11320. bool
  11321. """
  11322. return mapping.from_maybe_impl(self._impl_obj.is_connected())
  11323. async def new_context(
  11324. self,
  11325. *,
  11326. viewport: typing.Optional[ViewportSize] = None,
  11327. screen: typing.Optional[ViewportSize] = None,
  11328. no_viewport: typing.Optional[bool] = None,
  11329. ignore_https_errors: typing.Optional[bool] = None,
  11330. java_script_enabled: typing.Optional[bool] = None,
  11331. bypass_csp: typing.Optional[bool] = None,
  11332. user_agent: typing.Optional[str] = None,
  11333. locale: typing.Optional[str] = None,
  11334. timezone_id: typing.Optional[str] = None,
  11335. geolocation: typing.Optional[Geolocation] = None,
  11336. permissions: typing.Optional[typing.Sequence[str]] = None,
  11337. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  11338. offline: typing.Optional[bool] = None,
  11339. http_credentials: typing.Optional[HttpCredentials] = None,
  11340. device_scale_factor: typing.Optional[float] = None,
  11341. is_mobile: typing.Optional[bool] = None,
  11342. has_touch: typing.Optional[bool] = None,
  11343. color_scheme: typing.Optional[
  11344. Literal["dark", "light", "no-preference", "null"]
  11345. ] = None,
  11346. reduced_motion: typing.Optional[
  11347. Literal["no-preference", "null", "reduce"]
  11348. ] = None,
  11349. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  11350. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  11351. accept_downloads: typing.Optional[bool] = None,
  11352. default_browser_type: typing.Optional[str] = None,
  11353. proxy: typing.Optional[ProxySettings] = None,
  11354. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11355. record_har_omit_content: typing.Optional[bool] = None,
  11356. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11357. record_video_size: typing.Optional[ViewportSize] = None,
  11358. storage_state: typing.Optional[
  11359. typing.Union[StorageState, str, pathlib.Path]
  11360. ] = None,
  11361. base_url: typing.Optional[str] = None,
  11362. strict_selectors: typing.Optional[bool] = None,
  11363. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  11364. record_har_url_filter: typing.Optional[
  11365. typing.Union[typing.Pattern[str], str]
  11366. ] = None,
  11367. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  11368. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  11369. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  11370. ) -> "BrowserContext":
  11371. """Browser.new_context
  11372. Creates a new browser context. It won't share cookies/cache with other browser contexts.
  11373. **NOTE** If directly using this method to create `BrowserContext`s, it is best practice to explicitly close the
  11374. returned context via `browser_context.close()` when your code is done with the `BrowserContext`, and before
  11375. calling `browser.close()`. This will ensure the `context` is closed gracefully and any artifacts—like HARs
  11376. and videos—are fully flushed and saved.
  11377. **Usage**
  11378. ```py
  11379. browser = await playwright.firefox.launch() # or \"chromium\" or \"webkit\".
  11380. # create a new incognito browser context.
  11381. context = await browser.new_context()
  11382. # create a new page in a pristine context.
  11383. page = await context.new_page()
  11384. await page.goto(\"https://example.com\")
  11385. # gracefully close up everything
  11386. await context.close()
  11387. await browser.close()
  11388. ```
  11389. Parameters
  11390. ----------
  11391. viewport : Union[{width: int, height: int}, None]
  11392. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  11393. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  11394. screen : Union[{width: int, height: int}, None]
  11395. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  11396. `viewport` is set.
  11397. no_viewport : Union[bool, None]
  11398. Does not enforce fixed viewport, allows resizing window in the headed mode.
  11399. ignore_https_errors : Union[bool, None]
  11400. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  11401. java_script_enabled : Union[bool, None]
  11402. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  11403. [disabling JavaScript](../emulation.md#javascript-enabled).
  11404. bypass_csp : Union[bool, None]
  11405. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  11406. user_agent : Union[str, None]
  11407. Specific user agent to use in this context.
  11408. locale : Union[str, None]
  11409. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  11410. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  11411. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  11412. timezone_id : Union[str, None]
  11413. Changes the timezone of the context. See
  11414. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  11415. for a list of supported timezone IDs. Defaults to the system timezone.
  11416. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  11417. permissions : Union[Sequence[str], None]
  11418. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  11419. more details. Defaults to none.
  11420. extra_http_headers : Union[Dict[str, str], None]
  11421. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  11422. offline : Union[bool, None]
  11423. Whether to emulate network being offline. Defaults to `false`. Learn more about
  11424. [network emulation](../emulation.md#offline).
  11425. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  11426. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  11427. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  11428. device_scale_factor : Union[float, None]
  11429. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  11430. [emulating devices with device scale factor](../emulation.md#devices).
  11431. is_mobile : Union[bool, None]
  11432. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  11433. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  11434. about [mobile emulation](../emulation.md#ismobile).
  11435. has_touch : Union[bool, None]
  11436. Specifies if viewport supports touch events. Defaults to false. Learn more about
  11437. [mobile emulation](../emulation.md#devices).
  11438. color_scheme : Union["dark", "light", "no-preference", "null", None]
  11439. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  11440. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  11441. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  11442. reduced_motion : Union["no-preference", "null", "reduce", None]
  11443. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  11444. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11445. `'no-preference'`.
  11446. forced_colors : Union["active", "none", "null", None]
  11447. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  11448. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11449. `'none'`.
  11450. contrast : Union["more", "no-preference", "null", None]
  11451. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  11452. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11453. `'no-preference'`.
  11454. accept_downloads : Union[bool, None]
  11455. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  11456. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  11457. Network proxy settings to use with this context. Defaults to none.
  11458. record_har_path : Union[pathlib.Path, str, None]
  11459. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  11460. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  11461. for the HAR to be saved.
  11462. record_har_omit_content : Union[bool, None]
  11463. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  11464. record_video_dir : Union[pathlib.Path, str, None]
  11465. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  11466. sure to call `browser_context.close()` for videos to be saved.
  11467. record_video_size : Union[{width: int, height: int}, None]
  11468. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  11469. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  11470. will be scaled down if necessary to fit the specified size.
  11471. 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]
  11472. Learn more about [storage state and auth](../auth.md).
  11473. Populates context with given storage state. This option can be used to initialize context with logged-in
  11474. information obtained via `browser_context.storage_state()`.
  11475. base_url : Union[str, None]
  11476. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  11477. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  11478. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  11479. corresponding URL. Unset by default. Examples:
  11480. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  11481. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  11482. `http://localhost:3000/foo/bar.html`
  11483. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  11484. `http://localhost:3000/bar.html`
  11485. strict_selectors : Union[bool, None]
  11486. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  11487. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  11488. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  11489. more about the strict mode.
  11490. service_workers : Union["allow", "block", None]
  11491. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  11492. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  11493. registered.
  11494. - `'block'`: Playwright will block all registration of Service Workers.
  11495. record_har_url_filter : Union[Pattern[str], str, None]
  11496. record_har_mode : Union["full", "minimal", None]
  11497. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  11498. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  11499. record_har_content : Union["attach", "embed", "omit", None]
  11500. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  11501. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  11502. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  11503. 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]
  11504. TLS Client Authentication allows the server to request a client certificate and verify it.
  11505. **Details**
  11506. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  11507. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  11508. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  11509. with an exact match to the request origin that the certificate is valid for.
  11510. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  11511. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  11512. does not match any of the domains you plan to visit.
  11513. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  11514. work by replacing `localhost` with `local.playwright`.
  11515. Returns
  11516. -------
  11517. BrowserContext
  11518. """
  11519. return mapping.from_impl(
  11520. await self._impl_obj.new_context(
  11521. viewport=viewport,
  11522. screen=screen,
  11523. noViewport=no_viewport,
  11524. ignoreHTTPSErrors=ignore_https_errors,
  11525. javaScriptEnabled=java_script_enabled,
  11526. bypassCSP=bypass_csp,
  11527. userAgent=user_agent,
  11528. locale=locale,
  11529. timezoneId=timezone_id,
  11530. geolocation=geolocation,
  11531. permissions=mapping.to_impl(permissions),
  11532. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  11533. offline=offline,
  11534. httpCredentials=http_credentials,
  11535. deviceScaleFactor=device_scale_factor,
  11536. isMobile=is_mobile,
  11537. hasTouch=has_touch,
  11538. colorScheme=color_scheme,
  11539. reducedMotion=reduced_motion,
  11540. forcedColors=forced_colors,
  11541. contrast=contrast,
  11542. acceptDownloads=accept_downloads,
  11543. defaultBrowserType=default_browser_type,
  11544. proxy=proxy,
  11545. recordHarPath=record_har_path,
  11546. recordHarOmitContent=record_har_omit_content,
  11547. recordVideoDir=record_video_dir,
  11548. recordVideoSize=record_video_size,
  11549. storageState=storage_state,
  11550. baseURL=base_url,
  11551. strictSelectors=strict_selectors,
  11552. serviceWorkers=service_workers,
  11553. recordHarUrlFilter=record_har_url_filter,
  11554. recordHarMode=record_har_mode,
  11555. recordHarContent=record_har_content,
  11556. clientCertificates=client_certificates,
  11557. )
  11558. )
  11559. async def new_page(
  11560. self,
  11561. *,
  11562. viewport: typing.Optional[ViewportSize] = None,
  11563. screen: typing.Optional[ViewportSize] = None,
  11564. no_viewport: typing.Optional[bool] = None,
  11565. ignore_https_errors: typing.Optional[bool] = None,
  11566. java_script_enabled: typing.Optional[bool] = None,
  11567. bypass_csp: typing.Optional[bool] = None,
  11568. user_agent: typing.Optional[str] = None,
  11569. locale: typing.Optional[str] = None,
  11570. timezone_id: typing.Optional[str] = None,
  11571. geolocation: typing.Optional[Geolocation] = None,
  11572. permissions: typing.Optional[typing.Sequence[str]] = None,
  11573. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  11574. offline: typing.Optional[bool] = None,
  11575. http_credentials: typing.Optional[HttpCredentials] = None,
  11576. device_scale_factor: typing.Optional[float] = None,
  11577. is_mobile: typing.Optional[bool] = None,
  11578. has_touch: typing.Optional[bool] = None,
  11579. color_scheme: typing.Optional[
  11580. Literal["dark", "light", "no-preference", "null"]
  11581. ] = None,
  11582. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  11583. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  11584. reduced_motion: typing.Optional[
  11585. Literal["no-preference", "null", "reduce"]
  11586. ] = None,
  11587. accept_downloads: typing.Optional[bool] = None,
  11588. default_browser_type: typing.Optional[str] = None,
  11589. proxy: typing.Optional[ProxySettings] = None,
  11590. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11591. record_har_omit_content: typing.Optional[bool] = None,
  11592. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11593. record_video_size: typing.Optional[ViewportSize] = None,
  11594. storage_state: typing.Optional[
  11595. typing.Union[StorageState, str, pathlib.Path]
  11596. ] = None,
  11597. base_url: typing.Optional[str] = None,
  11598. strict_selectors: typing.Optional[bool] = None,
  11599. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  11600. record_har_url_filter: typing.Optional[
  11601. typing.Union[typing.Pattern[str], str]
  11602. ] = None,
  11603. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  11604. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  11605. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  11606. ) -> "Page":
  11607. """Browser.new_page
  11608. Creates a new page in a new browser context. Closing this page will close the context as well.
  11609. This is a convenience API that should only be used for the single-page scenarios and short snippets. Production
  11610. code and testing frameworks should explicitly create `browser.new_context()` followed by the
  11611. `browser_context.new_page()` to control their exact life times.
  11612. Parameters
  11613. ----------
  11614. viewport : Union[{width: int, height: int}, None]
  11615. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  11616. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  11617. screen : Union[{width: int, height: int}, None]
  11618. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  11619. `viewport` is set.
  11620. no_viewport : Union[bool, None]
  11621. Does not enforce fixed viewport, allows resizing window in the headed mode.
  11622. ignore_https_errors : Union[bool, None]
  11623. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  11624. java_script_enabled : Union[bool, None]
  11625. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  11626. [disabling JavaScript](../emulation.md#javascript-enabled).
  11627. bypass_csp : Union[bool, None]
  11628. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  11629. user_agent : Union[str, None]
  11630. Specific user agent to use in this context.
  11631. locale : Union[str, None]
  11632. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  11633. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  11634. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  11635. timezone_id : Union[str, None]
  11636. Changes the timezone of the context. See
  11637. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  11638. for a list of supported timezone IDs. Defaults to the system timezone.
  11639. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  11640. permissions : Union[Sequence[str], None]
  11641. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  11642. more details. Defaults to none.
  11643. extra_http_headers : Union[Dict[str, str], None]
  11644. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  11645. offline : Union[bool, None]
  11646. Whether to emulate network being offline. Defaults to `false`. Learn more about
  11647. [network emulation](../emulation.md#offline).
  11648. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  11649. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  11650. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  11651. device_scale_factor : Union[float, None]
  11652. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  11653. [emulating devices with device scale factor](../emulation.md#devices).
  11654. is_mobile : Union[bool, None]
  11655. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  11656. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  11657. about [mobile emulation](../emulation.md#ismobile).
  11658. has_touch : Union[bool, None]
  11659. Specifies if viewport supports touch events. Defaults to false. Learn more about
  11660. [mobile emulation](../emulation.md#devices).
  11661. color_scheme : Union["dark", "light", "no-preference", "null", None]
  11662. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  11663. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  11664. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  11665. forced_colors : Union["active", "none", "null", None]
  11666. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  11667. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11668. `'none'`.
  11669. contrast : Union["more", "no-preference", "null", None]
  11670. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  11671. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11672. `'no-preference'`.
  11673. reduced_motion : Union["no-preference", "null", "reduce", None]
  11674. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  11675. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  11676. `'no-preference'`.
  11677. accept_downloads : Union[bool, None]
  11678. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  11679. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  11680. Network proxy settings to use with this context. Defaults to none.
  11681. record_har_path : Union[pathlib.Path, str, None]
  11682. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  11683. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  11684. for the HAR to be saved.
  11685. record_har_omit_content : Union[bool, None]
  11686. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  11687. record_video_dir : Union[pathlib.Path, str, None]
  11688. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  11689. sure to call `browser_context.close()` for videos to be saved.
  11690. record_video_size : Union[{width: int, height: int}, None]
  11691. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  11692. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  11693. will be scaled down if necessary to fit the specified size.
  11694. 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]
  11695. Learn more about [storage state and auth](../auth.md).
  11696. Populates context with given storage state. This option can be used to initialize context with logged-in
  11697. information obtained via `browser_context.storage_state()`.
  11698. base_url : Union[str, None]
  11699. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  11700. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  11701. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  11702. corresponding URL. Unset by default. Examples:
  11703. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  11704. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  11705. `http://localhost:3000/foo/bar.html`
  11706. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  11707. `http://localhost:3000/bar.html`
  11708. strict_selectors : Union[bool, None]
  11709. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  11710. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  11711. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  11712. more about the strict mode.
  11713. service_workers : Union["allow", "block", None]
  11714. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  11715. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  11716. registered.
  11717. - `'block'`: Playwright will block all registration of Service Workers.
  11718. record_har_url_filter : Union[Pattern[str], str, None]
  11719. record_har_mode : Union["full", "minimal", None]
  11720. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  11721. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  11722. record_har_content : Union["attach", "embed", "omit", None]
  11723. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  11724. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  11725. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  11726. 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]
  11727. TLS Client Authentication allows the server to request a client certificate and verify it.
  11728. **Details**
  11729. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  11730. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  11731. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  11732. with an exact match to the request origin that the certificate is valid for.
  11733. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  11734. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  11735. does not match any of the domains you plan to visit.
  11736. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  11737. work by replacing `localhost` with `local.playwright`.
  11738. Returns
  11739. -------
  11740. Page
  11741. """
  11742. return mapping.from_impl(
  11743. await self._impl_obj.new_page(
  11744. viewport=viewport,
  11745. screen=screen,
  11746. noViewport=no_viewport,
  11747. ignoreHTTPSErrors=ignore_https_errors,
  11748. javaScriptEnabled=java_script_enabled,
  11749. bypassCSP=bypass_csp,
  11750. userAgent=user_agent,
  11751. locale=locale,
  11752. timezoneId=timezone_id,
  11753. geolocation=geolocation,
  11754. permissions=mapping.to_impl(permissions),
  11755. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  11756. offline=offline,
  11757. httpCredentials=http_credentials,
  11758. deviceScaleFactor=device_scale_factor,
  11759. isMobile=is_mobile,
  11760. hasTouch=has_touch,
  11761. colorScheme=color_scheme,
  11762. forcedColors=forced_colors,
  11763. contrast=contrast,
  11764. reducedMotion=reduced_motion,
  11765. acceptDownloads=accept_downloads,
  11766. defaultBrowserType=default_browser_type,
  11767. proxy=proxy,
  11768. recordHarPath=record_har_path,
  11769. recordHarOmitContent=record_har_omit_content,
  11770. recordVideoDir=record_video_dir,
  11771. recordVideoSize=record_video_size,
  11772. storageState=storage_state,
  11773. baseURL=base_url,
  11774. strictSelectors=strict_selectors,
  11775. serviceWorkers=service_workers,
  11776. recordHarUrlFilter=record_har_url_filter,
  11777. recordHarMode=record_har_mode,
  11778. recordHarContent=record_har_content,
  11779. clientCertificates=client_certificates,
  11780. )
  11781. )
  11782. async def close(self, *, reason: typing.Optional[str] = None) -> None:
  11783. """Browser.close
  11784. In case this browser is obtained using `browser_type.launch()`, closes the browser and all of its pages (if
  11785. any were opened).
  11786. In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from
  11787. the browser server.
  11788. **NOTE** This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close
  11789. events, call `browser_context.close()` on any `BrowserContext` instances you explicitly created earlier
  11790. using `browser.new_context()` **before** calling `browser.close()`.
  11791. The `Browser` object itself is considered to be disposed and cannot be used anymore.
  11792. Parameters
  11793. ----------
  11794. reason : Union[str, None]
  11795. The reason to be reported to the operations interrupted by the browser closure.
  11796. """
  11797. return mapping.from_maybe_impl(await self._impl_obj.close(reason=reason))
  11798. async def new_browser_cdp_session(self) -> "CDPSession":
  11799. """Browser.new_browser_cdp_session
  11800. **NOTE** CDP Sessions are only supported on Chromium-based browsers.
  11801. Returns the newly created browser session.
  11802. Returns
  11803. -------
  11804. CDPSession
  11805. """
  11806. return mapping.from_impl(await self._impl_obj.new_browser_cdp_session())
  11807. async def start_tracing(
  11808. self,
  11809. *,
  11810. page: typing.Optional["Page"] = None,
  11811. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11812. screenshots: typing.Optional[bool] = None,
  11813. categories: typing.Optional[typing.Sequence[str]] = None,
  11814. ) -> None:
  11815. """Browser.start_tracing
  11816. **NOTE** This API controls
  11817. [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
  11818. chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
  11819. [here](https://playwright.dev/python/docs/api/class-tracing).
  11820. You can use `browser.start_tracing()` and `browser.stop_tracing()` to create a trace file that can be
  11821. opened in Chrome DevTools performance panel.
  11822. **Usage**
  11823. ```py
  11824. await browser.start_tracing(page, path=\"trace.json\")
  11825. await page.goto(\"https://www.google.com\")
  11826. await browser.stop_tracing()
  11827. ```
  11828. Parameters
  11829. ----------
  11830. page : Union[Page, None]
  11831. Optional, if specified, tracing includes screenshots of the given page.
  11832. path : Union[pathlib.Path, str, None]
  11833. A path to write the trace file to.
  11834. screenshots : Union[bool, None]
  11835. captures screenshots in the trace.
  11836. categories : Union[Sequence[str], None]
  11837. specify custom categories to use instead of default.
  11838. """
  11839. return mapping.from_maybe_impl(
  11840. await self._impl_obj.start_tracing(
  11841. page=page._impl_obj if page else None,
  11842. path=path,
  11843. screenshots=screenshots,
  11844. categories=mapping.to_impl(categories),
  11845. )
  11846. )
  11847. async def stop_tracing(self) -> bytes:
  11848. """Browser.stop_tracing
  11849. **NOTE** This API controls
  11850. [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
  11851. chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
  11852. [here](https://playwright.dev/python/docs/api/class-tracing).
  11853. Returns the buffer with trace data.
  11854. Returns
  11855. -------
  11856. bytes
  11857. """
  11858. return mapping.from_maybe_impl(await self._impl_obj.stop_tracing())
  11859. mapping.register(BrowserImpl, Browser)
  11860. class BrowserType(AsyncBase):
  11861. @property
  11862. def name(self) -> str:
  11863. """BrowserType.name
  11864. Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
  11865. Returns
  11866. -------
  11867. str
  11868. """
  11869. return mapping.from_maybe_impl(self._impl_obj.name)
  11870. @property
  11871. def executable_path(self) -> str:
  11872. """BrowserType.executable_path
  11873. A path where Playwright expects to find a bundled browser executable.
  11874. Returns
  11875. -------
  11876. str
  11877. """
  11878. return mapping.from_maybe_impl(self._impl_obj.executable_path)
  11879. async def launch(
  11880. self,
  11881. *,
  11882. executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11883. channel: typing.Optional[str] = None,
  11884. args: typing.Optional[typing.Sequence[str]] = None,
  11885. ignore_default_args: typing.Optional[
  11886. typing.Union[bool, typing.Sequence[str]]
  11887. ] = None,
  11888. handle_sigint: typing.Optional[bool] = None,
  11889. handle_sigterm: typing.Optional[bool] = None,
  11890. handle_sighup: typing.Optional[bool] = None,
  11891. timeout: typing.Optional[float] = None,
  11892. env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  11893. headless: typing.Optional[bool] = None,
  11894. proxy: typing.Optional[ProxySettings] = None,
  11895. downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11896. slow_mo: typing.Optional[float] = None,
  11897. traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  11898. chromium_sandbox: typing.Optional[bool] = None,
  11899. firefox_user_prefs: typing.Optional[
  11900. typing.Dict[str, typing.Union[str, float, bool]]
  11901. ] = None,
  11902. ) -> "Browser":
  11903. """BrowserType.launch
  11904. Returns the browser instance.
  11905. **Usage**
  11906. You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
  11907. ```py
  11908. browser = await playwright.chromium.launch( # or \"firefox\" or \"webkit\".
  11909. ignore_default_args=[\"--mute-audio\"]
  11910. )
  11911. ```
  11912. > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it
  11913. works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other
  11914. version. Use `executablePath` option with extreme caution.
  11915. >
  11916. > If Google Chrome (rather than Chromium) is preferred, a
  11917. [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
  11918. [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
  11919. >
  11920. > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs
  11921. for video playback. See
  11922. [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
  11923. other differences between Chromium and Chrome.
  11924. [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
  11925. describes some differences for Linux users.
  11926. Parameters
  11927. ----------
  11928. executable_path : Union[pathlib.Path, str, None]
  11929. Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
  11930. resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
  11931. Firefox or WebKit, use at your own risk.
  11932. channel : Union[str, None]
  11933. Browser distribution channel.
  11934. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
  11935. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
  11936. "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
  11937. args : Union[Sequence[str], None]
  11938. **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
  11939. Additional arguments to pass to the browser instance. The list of Chromium flags can be found
  11940. [here](https://peter.sh/experiments/chromium-command-line-switches/).
  11941. ignore_default_args : Union[Sequence[str], bool, None]
  11942. If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
  11943. given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
  11944. handle_sigint : Union[bool, None]
  11945. Close the browser process on Ctrl-C. Defaults to `true`.
  11946. handle_sigterm : Union[bool, None]
  11947. Close the browser process on SIGTERM. Defaults to `true`.
  11948. handle_sighup : Union[bool, None]
  11949. Close the browser process on SIGHUP. Defaults to `true`.
  11950. timeout : Union[float, None]
  11951. Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
  11952. to disable timeout.
  11953. env : Union[Dict[str, Union[bool, float, str]], None]
  11954. Specify environment variables that will be visible to the browser. Defaults to `process.env`.
  11955. headless : Union[bool, None]
  11956. Whether to run browser in headless mode. More details for
  11957. [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
  11958. [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
  11959. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  11960. Network proxy settings.
  11961. downloads_path : Union[pathlib.Path, str, None]
  11962. If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
  11963. is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
  11964. created in is closed.
  11965. slow_mo : Union[float, None]
  11966. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  11967. on.
  11968. traces_dir : Union[pathlib.Path, str, None]
  11969. If specified, traces are saved into this directory.
  11970. chromium_sandbox : Union[bool, None]
  11971. Enable Chromium sandboxing. Defaults to `false`.
  11972. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
  11973. Firefox user preferences. Learn more about the Firefox user preferences at
  11974. [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
  11975. You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
  11976. `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
  11977. Returns
  11978. -------
  11979. Browser
  11980. """
  11981. return mapping.from_impl(
  11982. await self._impl_obj.launch(
  11983. executablePath=executable_path,
  11984. channel=channel,
  11985. args=mapping.to_impl(args),
  11986. ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
  11987. handleSIGINT=handle_sigint,
  11988. handleSIGTERM=handle_sigterm,
  11989. handleSIGHUP=handle_sighup,
  11990. timeout=timeout,
  11991. env=mapping.to_impl(env),
  11992. headless=headless,
  11993. proxy=proxy,
  11994. downloadsPath=downloads_path,
  11995. slowMo=slow_mo,
  11996. tracesDir=traces_dir,
  11997. chromiumSandbox=chromium_sandbox,
  11998. firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
  11999. )
  12000. )
  12001. async def launch_persistent_context(
  12002. self,
  12003. user_data_dir: typing.Union[str, pathlib.Path],
  12004. *,
  12005. channel: typing.Optional[str] = None,
  12006. executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12007. args: typing.Optional[typing.Sequence[str]] = None,
  12008. ignore_default_args: typing.Optional[
  12009. typing.Union[bool, typing.Sequence[str]]
  12010. ] = None,
  12011. handle_sigint: typing.Optional[bool] = None,
  12012. handle_sigterm: typing.Optional[bool] = None,
  12013. handle_sighup: typing.Optional[bool] = None,
  12014. timeout: typing.Optional[float] = None,
  12015. env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  12016. headless: typing.Optional[bool] = None,
  12017. proxy: typing.Optional[ProxySettings] = None,
  12018. downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12019. slow_mo: typing.Optional[float] = None,
  12020. viewport: typing.Optional[ViewportSize] = None,
  12021. screen: typing.Optional[ViewportSize] = None,
  12022. no_viewport: typing.Optional[bool] = None,
  12023. ignore_https_errors: typing.Optional[bool] = None,
  12024. java_script_enabled: typing.Optional[bool] = None,
  12025. bypass_csp: typing.Optional[bool] = None,
  12026. user_agent: typing.Optional[str] = None,
  12027. locale: typing.Optional[str] = None,
  12028. timezone_id: typing.Optional[str] = None,
  12029. geolocation: typing.Optional[Geolocation] = None,
  12030. permissions: typing.Optional[typing.Sequence[str]] = None,
  12031. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  12032. offline: typing.Optional[bool] = None,
  12033. http_credentials: typing.Optional[HttpCredentials] = None,
  12034. device_scale_factor: typing.Optional[float] = None,
  12035. is_mobile: typing.Optional[bool] = None,
  12036. has_touch: typing.Optional[bool] = None,
  12037. color_scheme: typing.Optional[
  12038. Literal["dark", "light", "no-preference", "null"]
  12039. ] = None,
  12040. reduced_motion: typing.Optional[
  12041. Literal["no-preference", "null", "reduce"]
  12042. ] = None,
  12043. forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
  12044. contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
  12045. accept_downloads: typing.Optional[bool] = None,
  12046. traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12047. chromium_sandbox: typing.Optional[bool] = None,
  12048. firefox_user_prefs: typing.Optional[
  12049. typing.Dict[str, typing.Union[str, float, bool]]
  12050. ] = None,
  12051. record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12052. record_har_omit_content: typing.Optional[bool] = None,
  12053. record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  12054. record_video_size: typing.Optional[ViewportSize] = None,
  12055. base_url: typing.Optional[str] = None,
  12056. strict_selectors: typing.Optional[bool] = None,
  12057. service_workers: typing.Optional[Literal["allow", "block"]] = None,
  12058. record_har_url_filter: typing.Optional[
  12059. typing.Union[typing.Pattern[str], str]
  12060. ] = None,
  12061. record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
  12062. record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
  12063. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  12064. ) -> "BrowserContext":
  12065. """BrowserType.launch_persistent_context
  12066. Returns the persistent browser context instance.
  12067. Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
  12068. context will automatically close the browser.
  12069. Parameters
  12070. ----------
  12071. user_data_dir : Union[pathlib.Path, str]
  12072. Path to a User Data Directory, which stores browser session data like cookies and local storage. Pass an empty
  12073. string to create a temporary directory.
  12074. More details for
  12075. [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
  12076. [Firefox](https://wiki.mozilla.org/Firefox/CommandLineOptions#User_profile). Chromium's user data directory is the
  12077. **parent** directory of the "Profile Path" seen at `chrome://version`.
  12078. Note that browsers do not allow launching multiple instances with the same User Data Directory.
  12079. **NOTE** Chromium/Chrome: Due to recent Chrome policy changes, automating the default Chrome user profile is not
  12080. supported. Pointing `userDataDir` to Chrome's main "User Data" directory (the profile used for your regular
  12081. browsing) may result in pages not loading or the browser exiting. Create and use a separate directory (for example,
  12082. an empty folder) as your automation profile instead. See https://developer.chrome.com/blog/remote-debugging-port
  12083. for details.
  12084. channel : Union[str, None]
  12085. Browser distribution channel.
  12086. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
  12087. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
  12088. "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
  12089. executable_path : Union[pathlib.Path, str, None]
  12090. Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
  12091. resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
  12092. Firefox or WebKit, use at your own risk.
  12093. args : Union[Sequence[str], None]
  12094. **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
  12095. Additional arguments to pass to the browser instance. The list of Chromium flags can be found
  12096. [here](https://peter.sh/experiments/chromium-command-line-switches/).
  12097. ignore_default_args : Union[Sequence[str], bool, None]
  12098. If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
  12099. given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
  12100. handle_sigint : Union[bool, None]
  12101. Close the browser process on Ctrl-C. Defaults to `true`.
  12102. handle_sigterm : Union[bool, None]
  12103. Close the browser process on SIGTERM. Defaults to `true`.
  12104. handle_sighup : Union[bool, None]
  12105. Close the browser process on SIGHUP. Defaults to `true`.
  12106. timeout : Union[float, None]
  12107. Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
  12108. to disable timeout.
  12109. env : Union[Dict[str, Union[bool, float, str]], None]
  12110. Specify environment variables that will be visible to the browser. Defaults to `process.env`.
  12111. headless : Union[bool, None]
  12112. Whether to run browser in headless mode. More details for
  12113. [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
  12114. [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
  12115. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  12116. Network proxy settings.
  12117. downloads_path : Union[pathlib.Path, str, None]
  12118. If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
  12119. is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
  12120. created in is closed.
  12121. slow_mo : Union[float, None]
  12122. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12123. on.
  12124. viewport : Union[{width: int, height: int}, None]
  12125. Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
  12126. viewport. Learn more about [viewport emulation](../emulation.md#viewport).
  12127. screen : Union[{width: int, height: int}, None]
  12128. Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
  12129. `viewport` is set.
  12130. no_viewport : Union[bool, None]
  12131. Does not enforce fixed viewport, allows resizing window in the headed mode.
  12132. ignore_https_errors : Union[bool, None]
  12133. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  12134. java_script_enabled : Union[bool, None]
  12135. Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
  12136. [disabling JavaScript](../emulation.md#javascript-enabled).
  12137. bypass_csp : Union[bool, None]
  12138. Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
  12139. user_agent : Union[str, None]
  12140. Specific user agent to use in this context.
  12141. locale : Union[str, None]
  12142. Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
  12143. `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
  12144. locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
  12145. timezone_id : Union[str, None]
  12146. Changes the timezone of the context. See
  12147. [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
  12148. for a list of supported timezone IDs. Defaults to the system timezone.
  12149. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
  12150. permissions : Union[Sequence[str], None]
  12151. A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
  12152. more details. Defaults to none.
  12153. extra_http_headers : Union[Dict[str, str], None]
  12154. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  12155. offline : Union[bool, None]
  12156. Whether to emulate network being offline. Defaults to `false`. Learn more about
  12157. [network emulation](../emulation.md#offline).
  12158. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  12159. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  12160. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  12161. device_scale_factor : Union[float, None]
  12162. Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
  12163. [emulating devices with device scale factor](../emulation.md#devices).
  12164. is_mobile : Union[bool, None]
  12165. Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
  12166. so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
  12167. about [mobile emulation](../emulation.md#ismobile).
  12168. has_touch : Union[bool, None]
  12169. Specifies if viewport supports touch events. Defaults to false. Learn more about
  12170. [mobile emulation](../emulation.md#devices).
  12171. color_scheme : Union["dark", "light", "no-preference", "null", None]
  12172. Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  12173. media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
  12174. Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
  12175. reduced_motion : Union["no-preference", "null", "reduce", None]
  12176. Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
  12177. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12178. `'no-preference'`.
  12179. forced_colors : Union["active", "none", "null", None]
  12180. Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
  12181. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12182. `'none'`.
  12183. contrast : Union["more", "no-preference", "null", None]
  12184. Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
  12185. `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
  12186. `'no-preference'`.
  12187. accept_downloads : Union[bool, None]
  12188. Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
  12189. traces_dir : Union[pathlib.Path, str, None]
  12190. If specified, traces are saved into this directory.
  12191. chromium_sandbox : Union[bool, None]
  12192. Enable Chromium sandboxing. Defaults to `false`.
  12193. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
  12194. Firefox user preferences. Learn more about the Firefox user preferences at
  12195. [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
  12196. You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
  12197. `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
  12198. record_har_path : Union[pathlib.Path, str, None]
  12199. Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
  12200. on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
  12201. for the HAR to be saved.
  12202. record_har_omit_content : Union[bool, None]
  12203. Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
  12204. record_video_dir : Union[pathlib.Path, str, None]
  12205. Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
  12206. sure to call `browser_context.close()` for videos to be saved.
  12207. record_video_size : Union[{width: int, height: int}, None]
  12208. Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
  12209. 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
  12210. will be scaled down if necessary to fit the specified size.
  12211. base_url : Union[str, None]
  12212. When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
  12213. `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
  12214. using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
  12215. corresponding URL. Unset by default. Examples:
  12216. - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
  12217. - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
  12218. `http://localhost:3000/foo/bar.html`
  12219. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  12220. `http://localhost:3000/bar.html`
  12221. strict_selectors : Union[bool, None]
  12222. If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
  12223. selectors that imply single target DOM element will throw when more than one element matches the selector. This
  12224. option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
  12225. more about the strict mode.
  12226. service_workers : Union["allow", "block", None]
  12227. Whether to allow sites to register Service workers. Defaults to `'allow'`.
  12228. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
  12229. registered.
  12230. - `'block'`: Playwright will block all registration of Service Workers.
  12231. record_har_url_filter : Union[Pattern[str], str, None]
  12232. record_har_mode : Union["full", "minimal", None]
  12233. When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
  12234. cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
  12235. record_har_content : Union["attach", "embed", "omit", None]
  12236. Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
  12237. `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
  12238. HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
  12239. 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]
  12240. TLS Client Authentication allows the server to request a client certificate and verify it.
  12241. **Details**
  12242. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  12243. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  12244. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  12245. with an exact match to the request origin that the certificate is valid for.
  12246. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  12247. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  12248. does not match any of the domains you plan to visit.
  12249. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  12250. work by replacing `localhost` with `local.playwright`.
  12251. Returns
  12252. -------
  12253. BrowserContext
  12254. """
  12255. return mapping.from_impl(
  12256. await self._impl_obj.launch_persistent_context(
  12257. userDataDir=user_data_dir,
  12258. channel=channel,
  12259. executablePath=executable_path,
  12260. args=mapping.to_impl(args),
  12261. ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
  12262. handleSIGINT=handle_sigint,
  12263. handleSIGTERM=handle_sigterm,
  12264. handleSIGHUP=handle_sighup,
  12265. timeout=timeout,
  12266. env=mapping.to_impl(env),
  12267. headless=headless,
  12268. proxy=proxy,
  12269. downloadsPath=downloads_path,
  12270. slowMo=slow_mo,
  12271. viewport=viewport,
  12272. screen=screen,
  12273. noViewport=no_viewport,
  12274. ignoreHTTPSErrors=ignore_https_errors,
  12275. javaScriptEnabled=java_script_enabled,
  12276. bypassCSP=bypass_csp,
  12277. userAgent=user_agent,
  12278. locale=locale,
  12279. timezoneId=timezone_id,
  12280. geolocation=geolocation,
  12281. permissions=mapping.to_impl(permissions),
  12282. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  12283. offline=offline,
  12284. httpCredentials=http_credentials,
  12285. deviceScaleFactor=device_scale_factor,
  12286. isMobile=is_mobile,
  12287. hasTouch=has_touch,
  12288. colorScheme=color_scheme,
  12289. reducedMotion=reduced_motion,
  12290. forcedColors=forced_colors,
  12291. contrast=contrast,
  12292. acceptDownloads=accept_downloads,
  12293. tracesDir=traces_dir,
  12294. chromiumSandbox=chromium_sandbox,
  12295. firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
  12296. recordHarPath=record_har_path,
  12297. recordHarOmitContent=record_har_omit_content,
  12298. recordVideoDir=record_video_dir,
  12299. recordVideoSize=record_video_size,
  12300. baseURL=base_url,
  12301. strictSelectors=strict_selectors,
  12302. serviceWorkers=service_workers,
  12303. recordHarUrlFilter=record_har_url_filter,
  12304. recordHarMode=record_har_mode,
  12305. recordHarContent=record_har_content,
  12306. clientCertificates=client_certificates,
  12307. )
  12308. )
  12309. async def connect_over_cdp(
  12310. self,
  12311. endpoint_url: str,
  12312. *,
  12313. timeout: typing.Optional[float] = None,
  12314. slow_mo: typing.Optional[float] = None,
  12315. headers: typing.Optional[typing.Dict[str, str]] = None,
  12316. is_local: typing.Optional[bool] = None,
  12317. ) -> "Browser":
  12318. """BrowserType.connect_over_cdp
  12319. This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
  12320. The default browser context is accessible via `browser.contexts()`.
  12321. **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
  12322. **NOTE** This connection is significantly lower fidelity than the Playwright protocol connection via
  12323. `browser_type.connect()`. If you are experiencing issues or attempting to use advanced functionality, you
  12324. probably want to use `browser_type.connect()`.
  12325. **Usage**
  12326. ```py
  12327. browser = await playwright.chromium.connect_over_cdp(\"http://localhost:9222\")
  12328. default_context = browser.contexts[0]
  12329. page = default_context.pages[0]
  12330. ```
  12331. Parameters
  12332. ----------
  12333. endpoint_url : str
  12334. A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
  12335. `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
  12336. timeout : Union[float, None]
  12337. Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
  12338. `0` to disable timeout.
  12339. slow_mo : Union[float, None]
  12340. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12341. on. Defaults to 0.
  12342. headers : Union[Dict[str, str], None]
  12343. Additional HTTP headers to be sent with connect request. Optional.
  12344. is_local : Union[bool, None]
  12345. Tells Playwright that it runs on the same host as the CDP server. It will enable certain optimizations that rely
  12346. upon the file system being the same between Playwright and the Browser.
  12347. Returns
  12348. -------
  12349. Browser
  12350. """
  12351. return mapping.from_impl(
  12352. await self._impl_obj.connect_over_cdp(
  12353. endpointURL=endpoint_url,
  12354. timeout=timeout,
  12355. slowMo=slow_mo,
  12356. headers=mapping.to_impl(headers),
  12357. isLocal=is_local,
  12358. )
  12359. )
  12360. async def connect(
  12361. self,
  12362. ws_endpoint: str,
  12363. *,
  12364. timeout: typing.Optional[float] = None,
  12365. slow_mo: typing.Optional[float] = None,
  12366. headers: typing.Optional[typing.Dict[str, str]] = None,
  12367. expose_network: typing.Optional[str] = None,
  12368. ) -> "Browser":
  12369. """BrowserType.connect
  12370. This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js.
  12371. **NOTE** The major and minor version of the Playwright instance that connects needs to match the version of
  12372. Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
  12373. Parameters
  12374. ----------
  12375. ws_endpoint : str
  12376. A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`.
  12377. timeout : Union[float, None]
  12378. Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout).
  12379. slow_mo : Union[float, None]
  12380. Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
  12381. on. Defaults to 0.
  12382. headers : Union[Dict[str, str], None]
  12383. Additional HTTP headers to be sent with web socket connect request. Optional.
  12384. expose_network : Union[str, None]
  12385. This option exposes network available on the connecting client to the browser being connected to. Consists of a
  12386. list of rules separated by comma.
  12387. Available rules:
  12388. 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
  12389. 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
  12390. 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
  12391. Some common examples:
  12392. 1. `"*"` to expose all network.
  12393. 1. `"<loopback>"` to expose localhost network.
  12394. 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to expose test/staging deployments and
  12395. localhost.
  12396. Returns
  12397. -------
  12398. Browser
  12399. """
  12400. return mapping.from_impl(
  12401. await self._impl_obj.connect(
  12402. wsEndpoint=ws_endpoint,
  12403. timeout=timeout,
  12404. slowMo=slow_mo,
  12405. headers=mapping.to_impl(headers),
  12406. exposeNetwork=expose_network,
  12407. )
  12408. )
  12409. mapping.register(BrowserTypeImpl, BrowserType)
  12410. class Playwright(AsyncBase):
  12411. @property
  12412. def devices(self) -> typing.Dict:
  12413. """Playwright.devices
  12414. Returns a dictionary of devices to be used with `browser.new_context()` or `browser.new_page()`.
  12415. ```py
  12416. import asyncio
  12417. from playwright.async_api import async_playwright, Playwright
  12418. async def run(playwright: Playwright):
  12419. webkit = playwright.webkit
  12420. iphone = playwright.devices[\"iPhone 6\"]
  12421. browser = await webkit.launch()
  12422. context = await browser.new_context(**iphone)
  12423. page = await context.new_page()
  12424. await page.goto(\"http://example.com\")
  12425. # other actions...
  12426. await browser.close()
  12427. async def main():
  12428. async with async_playwright() as playwright:
  12429. await run(playwright)
  12430. asyncio.run(main())
  12431. ```
  12432. Returns
  12433. -------
  12434. Dict
  12435. """
  12436. return mapping.from_maybe_impl(self._impl_obj.devices)
  12437. @property
  12438. def selectors(self) -> "Selectors":
  12439. """Playwright.selectors
  12440. Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/python/docs/extensibility) for more
  12441. information.
  12442. Returns
  12443. -------
  12444. Selectors
  12445. """
  12446. return mapping.from_impl(self._impl_obj.selectors)
  12447. @property
  12448. def chromium(self) -> "BrowserType":
  12449. """Playwright.chromium
  12450. This object can be used to launch or connect to Chromium, returning instances of `Browser`.
  12451. Returns
  12452. -------
  12453. BrowserType
  12454. """
  12455. return mapping.from_impl(self._impl_obj.chromium)
  12456. @property
  12457. def firefox(self) -> "BrowserType":
  12458. """Playwright.firefox
  12459. This object can be used to launch or connect to Firefox, returning instances of `Browser`.
  12460. Returns
  12461. -------
  12462. BrowserType
  12463. """
  12464. return mapping.from_impl(self._impl_obj.firefox)
  12465. @property
  12466. def webkit(self) -> "BrowserType":
  12467. """Playwright.webkit
  12468. This object can be used to launch or connect to WebKit, returning instances of `Browser`.
  12469. Returns
  12470. -------
  12471. BrowserType
  12472. """
  12473. return mapping.from_impl(self._impl_obj.webkit)
  12474. @property
  12475. def request(self) -> "APIRequest":
  12476. """Playwright.request
  12477. Exposes API that can be used for the Web API testing.
  12478. Returns
  12479. -------
  12480. APIRequest
  12481. """
  12482. return mapping.from_impl(self._impl_obj.request)
  12483. def __getitem__(self, value: str) -> "BrowserType":
  12484. return mapping.from_impl(self._impl_obj.__getitem__(value=value))
  12485. async def stop(self) -> None:
  12486. """Playwright.stop
  12487. Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful
  12488. in REPL applications.
  12489. ```py
  12490. from playwright.sync_api import sync_playwright
  12491. playwright = sync_playwright().start()
  12492. browser = playwright.chromium.launch()
  12493. page = browser.new_page()
  12494. page.goto(\"https://playwright.dev/\")
  12495. page.screenshot(path=\"example.png\")
  12496. browser.close()
  12497. playwright.stop()
  12498. ```
  12499. """
  12500. return mapping.from_maybe_impl(await self._impl_obj.stop())
  12501. mapping.register(PlaywrightImpl, Playwright)
  12502. class Tracing(AsyncBase):
  12503. async def start(
  12504. self,
  12505. *,
  12506. name: typing.Optional[str] = None,
  12507. title: typing.Optional[str] = None,
  12508. snapshots: typing.Optional[bool] = None,
  12509. screenshots: typing.Optional[bool] = None,
  12510. sources: typing.Optional[bool] = None,
  12511. ) -> None:
  12512. """Tracing.start
  12513. Start tracing.
  12514. **NOTE** You probably want to
  12515. [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead
  12516. of using `Tracing.start`.
  12517. The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions
  12518. (like `expect` calls). We recommend
  12519. [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),
  12520. which includes those assertions and provides a more complete trace for debugging test failures.
  12521. **Usage**
  12522. ```py
  12523. await context.tracing.start(screenshots=True, snapshots=True)
  12524. page = await context.new_page()
  12525. await page.goto(\"https://playwright.dev\")
  12526. await context.tracing.stop(path = \"trace.zip\")
  12527. ```
  12528. Parameters
  12529. ----------
  12530. name : Union[str, None]
  12531. If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
  12532. `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
  12533. need to pass `path` option to `tracing.stop()` instead.
  12534. title : Union[str, None]
  12535. Trace name to be shown in the Trace Viewer.
  12536. snapshots : Union[bool, None]
  12537. If this option is true tracing will
  12538. - capture DOM snapshot on every action
  12539. - record network activity
  12540. screenshots : Union[bool, None]
  12541. Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.
  12542. sources : Union[bool, None]
  12543. Whether to include source files for trace actions.
  12544. """
  12545. return mapping.from_maybe_impl(
  12546. await self._impl_obj.start(
  12547. name=name,
  12548. title=title,
  12549. snapshots=snapshots,
  12550. screenshots=screenshots,
  12551. sources=sources,
  12552. )
  12553. )
  12554. async def start_chunk(
  12555. self, *, title: typing.Optional[str] = None, name: typing.Optional[str] = None
  12556. ) -> None:
  12557. """Tracing.start_chunk
  12558. Start a new trace chunk. If you'd like to record multiple traces on the same `BrowserContext`, use
  12559. `tracing.start()` once, and then create multiple trace chunks with `tracing.start_chunk()` and
  12560. `tracing.stop_chunk()`.
  12561. **Usage**
  12562. ```py
  12563. await context.tracing.start(screenshots=True, snapshots=True)
  12564. page = await context.new_page()
  12565. await page.goto(\"https://playwright.dev\")
  12566. await context.tracing.start_chunk()
  12567. await page.get_by_text(\"Get Started\").click()
  12568. # Everything between start_chunk and stop_chunk will be recorded in the trace.
  12569. await context.tracing.stop_chunk(path = \"trace1.zip\")
  12570. await context.tracing.start_chunk()
  12571. await page.goto(\"http://example.com\")
  12572. # Save a second trace file with different actions.
  12573. await context.tracing.stop_chunk(path = \"trace2.zip\")
  12574. ```
  12575. Parameters
  12576. ----------
  12577. title : Union[str, None]
  12578. Trace name to be shown in the Trace Viewer.
  12579. name : Union[str, None]
  12580. If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
  12581. `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
  12582. need to pass `path` option to `tracing.stop_chunk()` instead.
  12583. """
  12584. return mapping.from_maybe_impl(
  12585. await self._impl_obj.start_chunk(title=title, name=name)
  12586. )
  12587. async def stop_chunk(
  12588. self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
  12589. ) -> None:
  12590. """Tracing.stop_chunk
  12591. Stop the trace chunk. See `tracing.start_chunk()` for more details about multiple trace chunks.
  12592. Parameters
  12593. ----------
  12594. path : Union[pathlib.Path, str, None]
  12595. Export trace collected since the last `tracing.start_chunk()` call into the file with the given path.
  12596. """
  12597. return mapping.from_maybe_impl(await self._impl_obj.stop_chunk(path=path))
  12598. async def stop(
  12599. self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
  12600. ) -> None:
  12601. """Tracing.stop
  12602. Stop tracing.
  12603. Parameters
  12604. ----------
  12605. path : Union[pathlib.Path, str, None]
  12606. Export trace into the file with the given path.
  12607. """
  12608. return mapping.from_maybe_impl(await self._impl_obj.stop(path=path))
  12609. async def group(
  12610. self, name: str, *, location: typing.Optional[TracingGroupLocation] = None
  12611. ) -> None:
  12612. """Tracing.group
  12613. **NOTE** Use `test.step` instead when available.
  12614. Creates a new group within the trace, assigning any subsequent API calls to this group, until
  12615. `tracing.group_end()` is called. Groups can be nested and will be visible in the trace viewer.
  12616. **Usage**
  12617. ```py
  12618. # All actions between group and group_end
  12619. # will be shown in the trace viewer as a group.
  12620. page.context.tracing.group(\"Open Playwright.dev > API\")
  12621. page.goto(\"https://playwright.dev/\")
  12622. page.get_by_role(\"link\", name=\"API\").click()
  12623. page.context.tracing.group_end()
  12624. ```
  12625. Parameters
  12626. ----------
  12627. name : str
  12628. Group name shown in the trace viewer.
  12629. location : Union[{file: str, line: Union[int, None], column: Union[int, None]}, None]
  12630. Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the
  12631. `tracing.group()` call.
  12632. """
  12633. return mapping.from_maybe_impl(
  12634. await self._impl_obj.group(name=name, location=location)
  12635. )
  12636. async def group_end(self) -> None:
  12637. """Tracing.group_end
  12638. Closes the last group created by `tracing.group()`.
  12639. """
  12640. return mapping.from_maybe_impl(await self._impl_obj.group_end())
  12641. mapping.register(TracingImpl, Tracing)
  12642. class Locator(AsyncBase):
  12643. @property
  12644. def page(self) -> "Page":
  12645. """Locator.page
  12646. A page this locator belongs to.
  12647. Returns
  12648. -------
  12649. Page
  12650. """
  12651. return mapping.from_impl(self._impl_obj.page)
  12652. @property
  12653. def first(self) -> "Locator":
  12654. """Locator.first
  12655. Returns locator to the first matching element.
  12656. Returns
  12657. -------
  12658. Locator
  12659. """
  12660. return mapping.from_impl(self._impl_obj.first)
  12661. @property
  12662. def last(self) -> "Locator":
  12663. """Locator.last
  12664. Returns locator to the last matching element.
  12665. **Usage**
  12666. ```py
  12667. banana = await page.get_by_role(\"listitem\").last
  12668. ```
  12669. Returns
  12670. -------
  12671. Locator
  12672. """
  12673. return mapping.from_impl(self._impl_obj.last)
  12674. @property
  12675. def content_frame(self) -> "FrameLocator":
  12676. """Locator.content_frame
  12677. Returns a `FrameLocator` object pointing to the same `iframe` as this locator.
  12678. Useful when you have a `Locator` object obtained somewhere, and later on would like to interact with the content
  12679. inside the frame.
  12680. For a reverse operation, use `frame_locator.owner()`.
  12681. **Usage**
  12682. ```py
  12683. locator = page.locator(\"iframe[name=\\\"embedded\\\"]\")
  12684. # ...
  12685. frame_locator = locator.content_frame
  12686. await frame_locator.get_by_role(\"button\").click()
  12687. ```
  12688. Returns
  12689. -------
  12690. FrameLocator
  12691. """
  12692. return mapping.from_impl(self._impl_obj.content_frame)
  12693. @property
  12694. def description(self) -> typing.Optional[str]:
  12695. """Locator.description
  12696. Returns locator description previously set with `locator.describe()`. Returns `null` if no custom
  12697. description has been set.
  12698. **Usage**
  12699. ```py
  12700. button = page.get_by_role(\"button\").describe(\"Subscribe button\")
  12701. print(button.description()) # \"Subscribe button\"
  12702. input = page.get_by_role(\"textbox\")
  12703. print(input.description()) # None
  12704. ```
  12705. Returns
  12706. -------
  12707. Union[str, None]
  12708. """
  12709. return mapping.from_maybe_impl(self._impl_obj.description)
  12710. async def bounding_box(
  12711. self, *, timeout: typing.Optional[float] = None
  12712. ) -> typing.Optional[FloatRect]:
  12713. """Locator.bounding_box
  12714. This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
  12715. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
  12716. window.
  12717. **Details**
  12718. Scrolling affects the returned bounding box, similarly to
  12719. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  12720. That means `x` and/or `y` may be negative.
  12721. Elements from child frames return the bounding box relative to the main frame, unlike the
  12722. [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  12723. Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
  12724. following snippet should click the center of the element.
  12725. **Usage**
  12726. ```py
  12727. box = await page.get_by_role(\"button\").bounding_box()
  12728. await page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
  12729. ```
  12730. Parameters
  12731. ----------
  12732. timeout : Union[float, None]
  12733. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12734. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12735. Returns
  12736. -------
  12737. Union[{x: float, y: float, width: float, height: float}, None]
  12738. """
  12739. return mapping.from_impl_nullable(
  12740. await self._impl_obj.bounding_box(timeout=timeout)
  12741. )
  12742. async def check(
  12743. self,
  12744. *,
  12745. position: typing.Optional[Position] = None,
  12746. timeout: typing.Optional[float] = None,
  12747. force: typing.Optional[bool] = None,
  12748. no_wait_after: typing.Optional[bool] = None,
  12749. trial: typing.Optional[bool] = None,
  12750. ) -> None:
  12751. """Locator.check
  12752. Ensure that checkbox or radio element is checked.
  12753. **Details**
  12754. Performs the following steps:
  12755. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  12756. checked, this method returns immediately.
  12757. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  12758. 1. Scroll the element into view if needed.
  12759. 1. Use `page.mouse` to click in the center of the element.
  12760. 1. Ensure that the element is now checked. If not, this method throws.
  12761. If the element is detached from the DOM at any moment during the action, this method throws.
  12762. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  12763. Passing zero timeout disables this.
  12764. **Usage**
  12765. ```py
  12766. await page.get_by_role(\"checkbox\").check()
  12767. ```
  12768. Parameters
  12769. ----------
  12770. position : Union[{x: float, y: float}, None]
  12771. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  12772. the element.
  12773. timeout : Union[float, None]
  12774. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12775. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12776. force : Union[bool, None]
  12777. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  12778. no_wait_after : Union[bool, None]
  12779. This option has no effect.
  12780. Deprecated: This option has no effect.
  12781. trial : Union[bool, None]
  12782. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  12783. to `false`. Useful to wait until the element is ready for the action without performing it.
  12784. """
  12785. return mapping.from_maybe_impl(
  12786. await self._impl_obj.check(
  12787. position=position,
  12788. timeout=timeout,
  12789. force=force,
  12790. noWaitAfter=no_wait_after,
  12791. trial=trial,
  12792. )
  12793. )
  12794. async def click(
  12795. self,
  12796. *,
  12797. modifiers: typing.Optional[
  12798. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  12799. ] = None,
  12800. position: typing.Optional[Position] = None,
  12801. delay: typing.Optional[float] = None,
  12802. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  12803. click_count: typing.Optional[int] = None,
  12804. timeout: typing.Optional[float] = None,
  12805. force: typing.Optional[bool] = None,
  12806. no_wait_after: typing.Optional[bool] = None,
  12807. trial: typing.Optional[bool] = None,
  12808. steps: typing.Optional[int] = None,
  12809. ) -> None:
  12810. """Locator.click
  12811. Click an element.
  12812. **Details**
  12813. This method clicks the element by performing the following steps:
  12814. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  12815. 1. Scroll the element into view if needed.
  12816. 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
  12817. 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
  12818. If the element is detached from the DOM at any moment during the action, this method throws.
  12819. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  12820. Passing zero timeout disables this.
  12821. **Usage**
  12822. Click a button:
  12823. ```py
  12824. await page.get_by_role(\"button\").click()
  12825. ```
  12826. Shift-right-click at a specific position on a canvas:
  12827. ```py
  12828. await page.locator(\"canvas\").click(
  12829. button=\"right\", modifiers=[\"Shift\"], position={\"x\": 23, \"y\": 32}
  12830. )
  12831. ```
  12832. Parameters
  12833. ----------
  12834. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  12835. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  12836. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  12837. "Control" on Windows and Linux and to "Meta" on macOS.
  12838. position : Union[{x: float, y: float}, None]
  12839. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  12840. the element.
  12841. delay : Union[float, None]
  12842. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  12843. button : Union["left", "middle", "right", None]
  12844. Defaults to `left`.
  12845. click_count : Union[int, None]
  12846. defaults to 1. See [UIEvent.detail].
  12847. timeout : Union[float, None]
  12848. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12849. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12850. force : Union[bool, None]
  12851. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  12852. no_wait_after : Union[bool, None]
  12853. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  12854. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  12855. navigating to inaccessible pages. Defaults to `false`.
  12856. Deprecated: This option will default to `true` in the future.
  12857. trial : Union[bool, None]
  12858. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  12859. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  12860. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  12861. are pressed.
  12862. steps : Union[int, None]
  12863. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  12864. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  12865. """
  12866. return mapping.from_maybe_impl(
  12867. await self._impl_obj.click(
  12868. modifiers=mapping.to_impl(modifiers),
  12869. position=position,
  12870. delay=delay,
  12871. button=button,
  12872. clickCount=click_count,
  12873. timeout=timeout,
  12874. force=force,
  12875. noWaitAfter=no_wait_after,
  12876. trial=trial,
  12877. steps=steps,
  12878. )
  12879. )
  12880. async def dblclick(
  12881. self,
  12882. *,
  12883. modifiers: typing.Optional[
  12884. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  12885. ] = None,
  12886. position: typing.Optional[Position] = None,
  12887. delay: typing.Optional[float] = None,
  12888. button: typing.Optional[Literal["left", "middle", "right"]] = None,
  12889. timeout: typing.Optional[float] = None,
  12890. force: typing.Optional[bool] = None,
  12891. no_wait_after: typing.Optional[bool] = None,
  12892. trial: typing.Optional[bool] = None,
  12893. steps: typing.Optional[int] = None,
  12894. ) -> None:
  12895. """Locator.dblclick
  12896. Double-click an element.
  12897. **Details**
  12898. This method double clicks the element by performing the following steps:
  12899. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  12900. 1. Scroll the element into view if needed.
  12901. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
  12902. If the element is detached from the DOM at any moment during the action, this method throws.
  12903. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  12904. Passing zero timeout disables this.
  12905. **NOTE** `element.dblclick()` dispatches two `click` events and a single `dblclick` event.
  12906. Parameters
  12907. ----------
  12908. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  12909. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  12910. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  12911. "Control" on Windows and Linux and to "Meta" on macOS.
  12912. position : Union[{x: float, y: float}, None]
  12913. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  12914. the element.
  12915. delay : Union[float, None]
  12916. Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
  12917. button : Union["left", "middle", "right", None]
  12918. Defaults to `left`.
  12919. timeout : Union[float, None]
  12920. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12921. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12922. force : Union[bool, None]
  12923. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  12924. no_wait_after : Union[bool, None]
  12925. This option has no effect.
  12926. Deprecated: This option has no effect.
  12927. trial : Union[bool, None]
  12928. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  12929. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  12930. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  12931. are pressed.
  12932. steps : Union[int, None]
  12933. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
  12934. position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
  12935. """
  12936. return mapping.from_maybe_impl(
  12937. await self._impl_obj.dblclick(
  12938. modifiers=mapping.to_impl(modifiers),
  12939. position=position,
  12940. delay=delay,
  12941. button=button,
  12942. timeout=timeout,
  12943. force=force,
  12944. noWaitAfter=no_wait_after,
  12945. trial=trial,
  12946. steps=steps,
  12947. )
  12948. )
  12949. async def dispatch_event(
  12950. self,
  12951. type: str,
  12952. event_init: typing.Optional[typing.Dict] = None,
  12953. *,
  12954. timeout: typing.Optional[float] = None,
  12955. ) -> None:
  12956. """Locator.dispatch_event
  12957. Programmatically dispatch an event on the matching element.
  12958. **Usage**
  12959. ```py
  12960. await locator.dispatch_event(\"click\")
  12961. ```
  12962. **Details**
  12963. The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
  12964. `click` is dispatched. This is equivalent to calling
  12965. [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
  12966. Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
  12967. properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
  12968. Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
  12969. - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
  12970. - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
  12971. - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
  12972. - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
  12973. - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
  12974. - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
  12975. - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
  12976. - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
  12977. - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
  12978. - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
  12979. You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
  12980. ```py
  12981. data_transfer = await page.evaluate_handle(\"new DataTransfer()\")
  12982. await locator.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
  12983. ```
  12984. Parameters
  12985. ----------
  12986. type : str
  12987. DOM event type: `"click"`, `"dragstart"`, etc.
  12988. event_init : Union[Dict, None]
  12989. Optional event-specific initialization properties.
  12990. timeout : Union[float, None]
  12991. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  12992. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  12993. """
  12994. return mapping.from_maybe_impl(
  12995. await self._impl_obj.dispatch_event(
  12996. type=type, eventInit=mapping.to_impl(event_init), timeout=timeout
  12997. )
  12998. )
  12999. async def evaluate(
  13000. self,
  13001. expression: str,
  13002. arg: typing.Optional[typing.Any] = None,
  13003. *,
  13004. timeout: typing.Optional[float] = None,
  13005. ) -> typing.Any:
  13006. """Locator.evaluate
  13007. Execute JavaScript code in the page, taking the matching element as an argument.
  13008. **Details**
  13009. Returns the return value of `expression`, called with the matching element as a first argument, and `arg` as a
  13010. second argument.
  13011. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  13012. If `expression` throws or rejects, this method throws.
  13013. **Usage**
  13014. Passing argument to `expression`:
  13015. ```py
  13016. result = await page.get_by_testid(\"myId\").evaluate(\"(element, [x, y]) => element.textContent + ' ' + x * y\", [7, 8])
  13017. print(result) # prints \"myId text 56\"
  13018. ```
  13019. Parameters
  13020. ----------
  13021. expression : str
  13022. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  13023. function is automatically invoked.
  13024. arg : Union[Any, None]
  13025. Optional argument to pass to `expression`.
  13026. timeout : Union[float, None]
  13027. Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
  13028. evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  13029. Returns
  13030. -------
  13031. Any
  13032. """
  13033. return mapping.from_maybe_impl(
  13034. await self._impl_obj.evaluate(
  13035. expression=expression, arg=mapping.to_impl(arg), timeout=timeout
  13036. )
  13037. )
  13038. async def evaluate_all(
  13039. self, expression: str, arg: typing.Optional[typing.Any] = None
  13040. ) -> typing.Any:
  13041. """Locator.evaluate_all
  13042. Execute JavaScript code in the page, taking all matching elements as an argument.
  13043. **Details**
  13044. Returns the return value of `expression`, called with an array of all matching elements as a first argument, and
  13045. `arg` as a second argument.
  13046. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  13047. If `expression` throws or rejects, this method throws.
  13048. **Usage**
  13049. ```py
  13050. locator = page.locator(\"div\")
  13051. more_than_ten = await locator.evaluate_all(\"(divs, min) => divs.length > min\", 10)
  13052. ```
  13053. Parameters
  13054. ----------
  13055. expression : str
  13056. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  13057. function is automatically invoked.
  13058. arg : Union[Any, None]
  13059. Optional argument to pass to `expression`.
  13060. Returns
  13061. -------
  13062. Any
  13063. """
  13064. return mapping.from_maybe_impl(
  13065. await self._impl_obj.evaluate_all(
  13066. expression=expression, arg=mapping.to_impl(arg)
  13067. )
  13068. )
  13069. async def evaluate_handle(
  13070. self,
  13071. expression: str,
  13072. arg: typing.Optional[typing.Any] = None,
  13073. *,
  13074. timeout: typing.Optional[float] = None,
  13075. ) -> "JSHandle":
  13076. """Locator.evaluate_handle
  13077. Execute JavaScript code in the page, taking the matching element as an argument, and return a `JSHandle` with the
  13078. result.
  13079. **Details**
  13080. Returns the return value of `expression` as a`JSHandle`, called with the matching element as a first argument, and
  13081. `arg` as a second argument.
  13082. The only difference between `locator.evaluate()` and `locator.evaluate_handle()` is that
  13083. `locator.evaluate_handle()` returns `JSHandle`.
  13084. If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
  13085. If `expression` throws or rejects, this method throws.
  13086. See `page.evaluate_handle()` for more details.
  13087. Parameters
  13088. ----------
  13089. expression : str
  13090. JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
  13091. function is automatically invoked.
  13092. arg : Union[Any, None]
  13093. Optional argument to pass to `expression`.
  13094. timeout : Union[float, None]
  13095. Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
  13096. evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  13097. Returns
  13098. -------
  13099. JSHandle
  13100. """
  13101. return mapping.from_impl(
  13102. await self._impl_obj.evaluate_handle(
  13103. expression=expression, arg=mapping.to_impl(arg), timeout=timeout
  13104. )
  13105. )
  13106. async def fill(
  13107. self,
  13108. value: str,
  13109. *,
  13110. timeout: typing.Optional[float] = None,
  13111. no_wait_after: typing.Optional[bool] = None,
  13112. force: typing.Optional[bool] = None,
  13113. ) -> None:
  13114. """Locator.fill
  13115. Set a value to the input field.
  13116. **Usage**
  13117. ```py
  13118. await page.get_by_role(\"textbox\").fill(\"example value\")
  13119. ```
  13120. **Details**
  13121. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
  13122. `input` event after filling. Note that you can pass an empty string to clear the input field.
  13123. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  13124. error. However, if the element is inside the `<label>` element that has an associated
  13125. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
  13126. instead.
  13127. To send fine-grained keyboard events, use `locator.press_sequentially()`.
  13128. Parameters
  13129. ----------
  13130. value : str
  13131. Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
  13132. timeout : Union[float, None]
  13133. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13134. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13135. no_wait_after : Union[bool, None]
  13136. This option has no effect.
  13137. Deprecated: This option has no effect.
  13138. force : Union[bool, None]
  13139. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13140. """
  13141. return mapping.from_maybe_impl(
  13142. await self._impl_obj.fill(
  13143. value=value, timeout=timeout, noWaitAfter=no_wait_after, force=force
  13144. )
  13145. )
  13146. async def clear(
  13147. self,
  13148. *,
  13149. timeout: typing.Optional[float] = None,
  13150. no_wait_after: typing.Optional[bool] = None,
  13151. force: typing.Optional[bool] = None,
  13152. ) -> None:
  13153. """Locator.clear
  13154. Clear the input field.
  13155. **Details**
  13156. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, clears it and triggers an
  13157. `input` event after clearing.
  13158. If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
  13159. error. However, if the element is inside the `<label>` element that has an associated
  13160. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
  13161. instead.
  13162. **Usage**
  13163. ```py
  13164. await page.get_by_role(\"textbox\").clear()
  13165. ```
  13166. Parameters
  13167. ----------
  13168. timeout : Union[float, None]
  13169. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13170. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13171. no_wait_after : Union[bool, None]
  13172. This option has no effect.
  13173. Deprecated: This option has no effect.
  13174. force : Union[bool, None]
  13175. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13176. """
  13177. return mapping.from_maybe_impl(
  13178. await self._impl_obj.clear(
  13179. timeout=timeout, noWaitAfter=no_wait_after, force=force
  13180. )
  13181. )
  13182. def locator(
  13183. self,
  13184. selector_or_locator: typing.Union[str, "Locator"],
  13185. *,
  13186. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13187. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13188. has: typing.Optional["Locator"] = None,
  13189. has_not: typing.Optional["Locator"] = None,
  13190. ) -> "Locator":
  13191. """Locator.locator
  13192. The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
  13193. options, similar to `locator.filter()` method.
  13194. [Learn more about locators](https://playwright.dev/python/docs/locators).
  13195. Parameters
  13196. ----------
  13197. selector_or_locator : Union[Locator, str]
  13198. A selector or locator to use when resolving DOM element.
  13199. has_text : Union[Pattern[str], str, None]
  13200. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  13201. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  13202. `<article><div>Playwright</div></article>`.
  13203. has_not_text : Union[Pattern[str], str, None]
  13204. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  13205. When passed a [string], matching is case-insensitive and searches for a substring.
  13206. has : Union[Locator, None]
  13207. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  13208. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  13209. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  13210. the document root. For example, you can find `content` that has `div` in
  13211. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  13212. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  13213. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13214. has_not : Union[Locator, None]
  13215. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  13216. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  13217. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13218. Returns
  13219. -------
  13220. Locator
  13221. """
  13222. return mapping.from_impl(
  13223. self._impl_obj.locator(
  13224. selectorOrLocator=selector_or_locator,
  13225. hasText=has_text,
  13226. hasNotText=has_not_text,
  13227. has=has._impl_obj if has else None,
  13228. hasNot=has_not._impl_obj if has_not else None,
  13229. )
  13230. )
  13231. def get_by_alt_text(
  13232. self,
  13233. text: typing.Union[str, typing.Pattern[str]],
  13234. *,
  13235. exact: typing.Optional[bool] = None,
  13236. ) -> "Locator":
  13237. """Locator.get_by_alt_text
  13238. Allows locating elements by their alt text.
  13239. **Usage**
  13240. For example, this method will find the image by alt text \"Playwright logo\":
  13241. ```html
  13242. <img alt='Playwright logo'>
  13243. ```
  13244. ```py
  13245. await page.get_by_alt_text(\"Playwright logo\").click()
  13246. ```
  13247. Parameters
  13248. ----------
  13249. text : Union[Pattern[str], str]
  13250. Text to locate the element for.
  13251. exact : Union[bool, None]
  13252. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13253. regular expression. Note that exact match still trims whitespace.
  13254. Returns
  13255. -------
  13256. Locator
  13257. """
  13258. return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
  13259. def get_by_label(
  13260. self,
  13261. text: typing.Union[str, typing.Pattern[str]],
  13262. *,
  13263. exact: typing.Optional[bool] = None,
  13264. ) -> "Locator":
  13265. """Locator.get_by_label
  13266. Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
  13267. `aria-label` attribute.
  13268. **Usage**
  13269. For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
  13270. ```html
  13271. <input aria-label=\"Username\">
  13272. <label for=\"password-input\">Password:</label>
  13273. <input id=\"password-input\">
  13274. ```
  13275. ```py
  13276. await page.get_by_label(\"Username\").fill(\"john\")
  13277. await page.get_by_label(\"Password\").fill(\"secret\")
  13278. ```
  13279. Parameters
  13280. ----------
  13281. text : Union[Pattern[str], str]
  13282. Text to locate the element for.
  13283. exact : Union[bool, None]
  13284. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13285. regular expression. Note that exact match still trims whitespace.
  13286. Returns
  13287. -------
  13288. Locator
  13289. """
  13290. return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
  13291. def get_by_placeholder(
  13292. self,
  13293. text: typing.Union[str, typing.Pattern[str]],
  13294. *,
  13295. exact: typing.Optional[bool] = None,
  13296. ) -> "Locator":
  13297. """Locator.get_by_placeholder
  13298. Allows locating input elements by the placeholder text.
  13299. **Usage**
  13300. For example, consider the following DOM structure.
  13301. ```html
  13302. <input type=\"email\" placeholder=\"name@example.com\" />
  13303. ```
  13304. You can fill the input after locating it by the placeholder text:
  13305. ```py
  13306. await page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
  13307. ```
  13308. Parameters
  13309. ----------
  13310. text : Union[Pattern[str], str]
  13311. Text to locate the element for.
  13312. exact : Union[bool, None]
  13313. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13314. regular expression. Note that exact match still trims whitespace.
  13315. Returns
  13316. -------
  13317. Locator
  13318. """
  13319. return mapping.from_impl(
  13320. self._impl_obj.get_by_placeholder(text=text, exact=exact)
  13321. )
  13322. def get_by_role(
  13323. self,
  13324. role: Literal[
  13325. "alert",
  13326. "alertdialog",
  13327. "application",
  13328. "article",
  13329. "banner",
  13330. "blockquote",
  13331. "button",
  13332. "caption",
  13333. "cell",
  13334. "checkbox",
  13335. "code",
  13336. "columnheader",
  13337. "combobox",
  13338. "complementary",
  13339. "contentinfo",
  13340. "definition",
  13341. "deletion",
  13342. "dialog",
  13343. "directory",
  13344. "document",
  13345. "emphasis",
  13346. "feed",
  13347. "figure",
  13348. "form",
  13349. "generic",
  13350. "grid",
  13351. "gridcell",
  13352. "group",
  13353. "heading",
  13354. "img",
  13355. "insertion",
  13356. "link",
  13357. "list",
  13358. "listbox",
  13359. "listitem",
  13360. "log",
  13361. "main",
  13362. "marquee",
  13363. "math",
  13364. "menu",
  13365. "menubar",
  13366. "menuitem",
  13367. "menuitemcheckbox",
  13368. "menuitemradio",
  13369. "meter",
  13370. "navigation",
  13371. "none",
  13372. "note",
  13373. "option",
  13374. "paragraph",
  13375. "presentation",
  13376. "progressbar",
  13377. "radio",
  13378. "radiogroup",
  13379. "region",
  13380. "row",
  13381. "rowgroup",
  13382. "rowheader",
  13383. "scrollbar",
  13384. "search",
  13385. "searchbox",
  13386. "separator",
  13387. "slider",
  13388. "spinbutton",
  13389. "status",
  13390. "strong",
  13391. "subscript",
  13392. "superscript",
  13393. "switch",
  13394. "tab",
  13395. "table",
  13396. "tablist",
  13397. "tabpanel",
  13398. "term",
  13399. "textbox",
  13400. "time",
  13401. "timer",
  13402. "toolbar",
  13403. "tooltip",
  13404. "tree",
  13405. "treegrid",
  13406. "treeitem",
  13407. ],
  13408. *,
  13409. checked: typing.Optional[bool] = None,
  13410. disabled: typing.Optional[bool] = None,
  13411. expanded: typing.Optional[bool] = None,
  13412. include_hidden: typing.Optional[bool] = None,
  13413. level: typing.Optional[int] = None,
  13414. name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13415. pressed: typing.Optional[bool] = None,
  13416. selected: typing.Optional[bool] = None,
  13417. exact: typing.Optional[bool] = None,
  13418. ) -> "Locator":
  13419. """Locator.get_by_role
  13420. Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
  13421. [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
  13422. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  13423. **Usage**
  13424. Consider the following DOM structure.
  13425. ```html
  13426. <h3>Sign up</h3>
  13427. <label>
  13428. <input type=\"checkbox\" /> Subscribe
  13429. </label>
  13430. <br/>
  13431. <button>Submit</button>
  13432. ```
  13433. You can locate each element by it's implicit role:
  13434. ```py
  13435. await expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
  13436. await page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
  13437. await page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
  13438. ```
  13439. **Details**
  13440. Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
  13441. about the ARIA guidelines.
  13442. Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
  13443. that is recognized by the role selector. You can find all the
  13444. [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
  13445. duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
  13446. Parameters
  13447. ----------
  13448. 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"]
  13449. Required aria role.
  13450. checked : Union[bool, None]
  13451. An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
  13452. Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
  13453. disabled : Union[bool, None]
  13454. An attribute that is usually set by `aria-disabled` or `disabled`.
  13455. **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
  13456. [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
  13457. expanded : Union[bool, None]
  13458. An attribute that is usually set by `aria-expanded`.
  13459. Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
  13460. include_hidden : Union[bool, None]
  13461. Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
  13462. [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
  13463. Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
  13464. level : Union[int, None]
  13465. A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
  13466. for `<h1>-<h6>` elements.
  13467. Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
  13468. name : Union[Pattern[str], str, None]
  13469. Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
  13470. case-insensitive and searches for a substring, use `exact` to control this behavior.
  13471. Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  13472. pressed : Union[bool, None]
  13473. An attribute that is usually set by `aria-pressed`.
  13474. Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
  13475. selected : Union[bool, None]
  13476. An attribute that is usually set by `aria-selected`.
  13477. Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
  13478. exact : Union[bool, None]
  13479. Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
  13480. regular expression. Note that exact match still trims whitespace.
  13481. Returns
  13482. -------
  13483. Locator
  13484. """
  13485. return mapping.from_impl(
  13486. self._impl_obj.get_by_role(
  13487. role=role,
  13488. checked=checked,
  13489. disabled=disabled,
  13490. expanded=expanded,
  13491. includeHidden=include_hidden,
  13492. level=level,
  13493. name=name,
  13494. pressed=pressed,
  13495. selected=selected,
  13496. exact=exact,
  13497. )
  13498. )
  13499. def get_by_test_id(
  13500. self, test_id: typing.Union[str, typing.Pattern[str]]
  13501. ) -> "Locator":
  13502. """Locator.get_by_test_id
  13503. Locate element by the test id.
  13504. **Usage**
  13505. Consider the following DOM structure.
  13506. ```html
  13507. <button data-testid=\"directions\">Itinéraire</button>
  13508. ```
  13509. You can locate the element by it's test id:
  13510. ```py
  13511. await page.get_by_test_id(\"directions\").click()
  13512. ```
  13513. **Details**
  13514. By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
  13515. configure a different test id attribute if necessary.
  13516. Parameters
  13517. ----------
  13518. test_id : Union[Pattern[str], str]
  13519. Id to locate the element by.
  13520. Returns
  13521. -------
  13522. Locator
  13523. """
  13524. return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
  13525. def get_by_text(
  13526. self,
  13527. text: typing.Union[str, typing.Pattern[str]],
  13528. *,
  13529. exact: typing.Optional[bool] = None,
  13530. ) -> "Locator":
  13531. """Locator.get_by_text
  13532. Allows locating elements that contain given text.
  13533. See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
  13534. filter by the text content.
  13535. **Usage**
  13536. Consider the following DOM structure:
  13537. ```html
  13538. <div>Hello <span>world</span></div>
  13539. <div>Hello</div>
  13540. ```
  13541. You can locate by text substring, exact string, or a regular expression:
  13542. ```py
  13543. # Matches <span>
  13544. page.get_by_text(\"world\")
  13545. # Matches first <div>
  13546. page.get_by_text(\"Hello world\")
  13547. # Matches second <div>
  13548. page.get_by_text(\"Hello\", exact=True)
  13549. # Matches both <div>s
  13550. page.get_by_text(re.compile(\"Hello\"))
  13551. # Matches second <div>
  13552. page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
  13553. ```
  13554. **Details**
  13555. Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
  13556. one, turns line breaks into spaces and ignores leading and trailing whitespace.
  13557. Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
  13558. example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
  13559. Parameters
  13560. ----------
  13561. text : Union[Pattern[str], str]
  13562. Text to locate the element for.
  13563. exact : Union[bool, None]
  13564. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13565. regular expression. Note that exact match still trims whitespace.
  13566. Returns
  13567. -------
  13568. Locator
  13569. """
  13570. return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
  13571. def get_by_title(
  13572. self,
  13573. text: typing.Union[str, typing.Pattern[str]],
  13574. *,
  13575. exact: typing.Optional[bool] = None,
  13576. ) -> "Locator":
  13577. """Locator.get_by_title
  13578. Allows locating elements by their title attribute.
  13579. **Usage**
  13580. Consider the following DOM structure.
  13581. ```html
  13582. <span title='Issues count'>25 issues</span>
  13583. ```
  13584. You can check the issues count after locating it by the title text:
  13585. ```py
  13586. await expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
  13587. ```
  13588. Parameters
  13589. ----------
  13590. text : Union[Pattern[str], str]
  13591. Text to locate the element for.
  13592. exact : Union[bool, None]
  13593. Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
  13594. regular expression. Note that exact match still trims whitespace.
  13595. Returns
  13596. -------
  13597. Locator
  13598. """
  13599. return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
  13600. def frame_locator(self, selector: str) -> "FrameLocator":
  13601. """Locator.frame_locator
  13602. When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
  13603. that iframe:
  13604. **Usage**
  13605. ```py
  13606. locator = page.frame_locator(\"iframe\").get_by_text(\"Submit\")
  13607. await locator.click()
  13608. ```
  13609. Parameters
  13610. ----------
  13611. selector : str
  13612. A selector to use when resolving DOM element.
  13613. Returns
  13614. -------
  13615. FrameLocator
  13616. """
  13617. return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
  13618. async def element_handle(
  13619. self, *, timeout: typing.Optional[float] = None
  13620. ) -> "ElementHandle":
  13621. """Locator.element_handle
  13622. Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
  13623. multiple elements match the locator, throws.
  13624. Parameters
  13625. ----------
  13626. timeout : Union[float, None]
  13627. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13628. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13629. Returns
  13630. -------
  13631. ElementHandle
  13632. """
  13633. return mapping.from_impl(await self._impl_obj.element_handle(timeout=timeout))
  13634. async def element_handles(self) -> typing.List["ElementHandle"]:
  13635. """Locator.element_handles
  13636. Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
  13637. Returns
  13638. -------
  13639. List[ElementHandle]
  13640. """
  13641. return mapping.from_impl_list(await self._impl_obj.element_handles())
  13642. def nth(self, index: int) -> "Locator":
  13643. """Locator.nth
  13644. Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
  13645. **Usage**
  13646. ```py
  13647. banana = await page.get_by_role(\"listitem\").nth(2)
  13648. ```
  13649. Parameters
  13650. ----------
  13651. index : int
  13652. Returns
  13653. -------
  13654. Locator
  13655. """
  13656. return mapping.from_impl(self._impl_obj.nth(index=index))
  13657. def describe(self, description: str) -> "Locator":
  13658. """Locator.describe
  13659. Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the
  13660. same element.
  13661. **Usage**
  13662. ```py
  13663. button = page.get_by_test_id(\"btn-sub\").describe(\"Subscribe button\")
  13664. await button.click()
  13665. ```
  13666. Parameters
  13667. ----------
  13668. description : str
  13669. Locator description.
  13670. Returns
  13671. -------
  13672. Locator
  13673. """
  13674. return mapping.from_impl(self._impl_obj.describe(description=description))
  13675. def filter(
  13676. self,
  13677. *,
  13678. has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13679. has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
  13680. has: typing.Optional["Locator"] = None,
  13681. has_not: typing.Optional["Locator"] = None,
  13682. visible: typing.Optional[bool] = None,
  13683. ) -> "Locator":
  13684. """Locator.filter
  13685. This method narrows existing locator according to the options, for example filters by text. It can be chained to
  13686. filter multiple times.
  13687. **Usage**
  13688. ```py
  13689. row_locator = page.locator(\"tr\")
  13690. # ...
  13691. await row_locator.filter(has_text=\"text in column 1\").filter(
  13692. has=page.get_by_role(\"button\", name=\"column 2 button\")
  13693. ).screenshot()
  13694. ```
  13695. Parameters
  13696. ----------
  13697. has_text : Union[Pattern[str], str, None]
  13698. Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
  13699. passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
  13700. `<article><div>Playwright</div></article>`.
  13701. has_not_text : Union[Pattern[str], str, None]
  13702. Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
  13703. When passed a [string], matching is case-insensitive and searches for a substring.
  13704. has : Union[Locator, None]
  13705. Narrows down the results of the method to those which contain elements matching this relative locator. For example,
  13706. `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
  13707. Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
  13708. the document root. For example, you can find `content` that has `div` in
  13709. `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
  13710. div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
  13711. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13712. has_not : Union[Locator, None]
  13713. Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
  13714. outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
  13715. Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
  13716. visible : Union[bool, None]
  13717. Only matches visible or invisible elements.
  13718. Returns
  13719. -------
  13720. Locator
  13721. """
  13722. return mapping.from_impl(
  13723. self._impl_obj.filter(
  13724. hasText=has_text,
  13725. hasNotText=has_not_text,
  13726. has=has._impl_obj if has else None,
  13727. hasNot=has_not._impl_obj if has_not else None,
  13728. visible=visible,
  13729. )
  13730. )
  13731. def or_(self, locator: "Locator") -> "Locator":
  13732. """Locator.or_
  13733. Creates a locator matching all elements that match one or both of the two locators.
  13734. Note that when both locators match something, the resulting locator will have multiple matches, potentially causing
  13735. a [locator strictness](https://playwright.dev/python/docs/locators#strictness) violation.
  13736. **Usage**
  13737. Consider a scenario where you'd like to click on a \"New email\" button, but sometimes a security settings dialog
  13738. shows up instead. In this case, you can wait for either a \"New email\" button, or a dialog and act accordingly.
  13739. **NOTE** If both \"New email\" button and security dialog appear on screen, the \"or\" locator will match both of them,
  13740. possibly throwing the [\"strict mode violation\" error](https://playwright.dev/python/docs/locators#strictness). In this case, you can use
  13741. `locator.first()` to only match one of them.
  13742. ```py
  13743. new_email = page.get_by_role(\"button\", name=\"New\")
  13744. dialog = page.get_by_text(\"Confirm security settings\")
  13745. await expect(new_email.or_(dialog).first).to_be_visible()
  13746. if (await dialog.is_visible()):
  13747. await page.get_by_role(\"button\", name=\"Dismiss\").click()
  13748. await new_email.click()
  13749. ```
  13750. Parameters
  13751. ----------
  13752. locator : Locator
  13753. Alternative locator to match.
  13754. Returns
  13755. -------
  13756. Locator
  13757. """
  13758. return mapping.from_impl(self._impl_obj.or_(locator=locator._impl_obj))
  13759. def and_(self, locator: "Locator") -> "Locator":
  13760. """Locator.and_
  13761. Creates a locator that matches both this locator and the argument locator.
  13762. **Usage**
  13763. The following example finds a button with a specific title.
  13764. ```py
  13765. button = page.get_by_role(\"button\").and_(page.get_by_title(\"Subscribe\"))
  13766. ```
  13767. Parameters
  13768. ----------
  13769. locator : Locator
  13770. Additional locator to match.
  13771. Returns
  13772. -------
  13773. Locator
  13774. """
  13775. return mapping.from_impl(self._impl_obj.and_(locator=locator._impl_obj))
  13776. async def focus(self, *, timeout: typing.Optional[float] = None) -> None:
  13777. """Locator.focus
  13778. Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
  13779. Parameters
  13780. ----------
  13781. timeout : Union[float, None]
  13782. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13783. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13784. """
  13785. return mapping.from_maybe_impl(await self._impl_obj.focus(timeout=timeout))
  13786. async def blur(self, *, timeout: typing.Optional[float] = None) -> None:
  13787. """Locator.blur
  13788. Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur) on the element.
  13789. Parameters
  13790. ----------
  13791. timeout : Union[float, None]
  13792. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13793. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13794. """
  13795. return mapping.from_maybe_impl(await self._impl_obj.blur(timeout=timeout))
  13796. async def all(self) -> typing.List["Locator"]:
  13797. """Locator.all
  13798. When the locator points to a list of elements, this returns an array of locators, pointing to their respective
  13799. elements.
  13800. **NOTE** `locator.all()` does not wait for elements to match the locator, and instead immediately returns
  13801. whatever is present in the page.
  13802. When the list of elements changes dynamically, `locator.all()` will produce unpredictable and flaky
  13803. results.
  13804. When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before
  13805. calling `locator.all()`.
  13806. **Usage**
  13807. ```py
  13808. for li in await page.get_by_role('listitem').all():
  13809. await li.click();
  13810. ```
  13811. Returns
  13812. -------
  13813. List[Locator]
  13814. """
  13815. return mapping.from_impl_list(await self._impl_obj.all())
  13816. async def count(self) -> int:
  13817. """Locator.count
  13818. Returns the number of elements matching the locator.
  13819. **NOTE** If you need to assert the number of elements on the page, prefer `locator_assertions.to_have_count()`
  13820. to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  13821. **Usage**
  13822. ```py
  13823. count = await page.get_by_role(\"listitem\").count()
  13824. ```
  13825. Returns
  13826. -------
  13827. int
  13828. """
  13829. return mapping.from_maybe_impl(await self._impl_obj.count())
  13830. async def drag_to(
  13831. self,
  13832. target: "Locator",
  13833. *,
  13834. force: typing.Optional[bool] = None,
  13835. no_wait_after: typing.Optional[bool] = None,
  13836. timeout: typing.Optional[float] = None,
  13837. trial: typing.Optional[bool] = None,
  13838. source_position: typing.Optional[Position] = None,
  13839. target_position: typing.Optional[Position] = None,
  13840. steps: typing.Optional[int] = None,
  13841. ) -> None:
  13842. """Locator.drag_to
  13843. Drag the source element towards the target element and drop it.
  13844. **Details**
  13845. This method drags the locator to another target locator or target position. It will first move to the source
  13846. element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
  13847. **Usage**
  13848. ```py
  13849. source = page.locator(\"#source\")
  13850. target = page.locator(\"#target\")
  13851. await source.drag_to(target)
  13852. # or specify exact positions relative to the top-left corners of the elements:
  13853. await source.drag_to(
  13854. target,
  13855. source_position={\"x\": 34, \"y\": 7},
  13856. target_position={\"x\": 10, \"y\": 20}
  13857. )
  13858. ```
  13859. Parameters
  13860. ----------
  13861. target : Locator
  13862. Locator of the element to drag to.
  13863. force : Union[bool, None]
  13864. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13865. no_wait_after : Union[bool, None]
  13866. This option has no effect.
  13867. Deprecated: This option has no effect.
  13868. timeout : Union[float, None]
  13869. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13870. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13871. trial : Union[bool, None]
  13872. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  13873. to `false`. Useful to wait until the element is ready for the action without performing it.
  13874. source_position : Union[{x: float, y: float}, None]
  13875. Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
  13876. specified, some visible point of the element is used.
  13877. target_position : Union[{x: float, y: float}, None]
  13878. Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
  13879. specified, some visible point of the element is used.
  13880. steps : Union[int, None]
  13881. Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
  13882. of the drag. When set to 1, emits a single `mousemove` event at the destination location.
  13883. """
  13884. return mapping.from_maybe_impl(
  13885. await self._impl_obj.drag_to(
  13886. target=target._impl_obj,
  13887. force=force,
  13888. noWaitAfter=no_wait_after,
  13889. timeout=timeout,
  13890. trial=trial,
  13891. sourcePosition=source_position,
  13892. targetPosition=target_position,
  13893. steps=steps,
  13894. )
  13895. )
  13896. async def get_attribute(
  13897. self, name: str, *, timeout: typing.Optional[float] = None
  13898. ) -> typing.Optional[str]:
  13899. """Locator.get_attribute
  13900. Returns the matching element's attribute value.
  13901. **NOTE** If you need to assert an element's attribute, prefer `locator_assertions.to_have_attribute()` to
  13902. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  13903. Parameters
  13904. ----------
  13905. name : str
  13906. Attribute name to get the value for.
  13907. timeout : Union[float, None]
  13908. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13909. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13910. Returns
  13911. -------
  13912. Union[str, None]
  13913. """
  13914. return mapping.from_maybe_impl(
  13915. await self._impl_obj.get_attribute(name=name, timeout=timeout)
  13916. )
  13917. async def hover(
  13918. self,
  13919. *,
  13920. modifiers: typing.Optional[
  13921. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  13922. ] = None,
  13923. position: typing.Optional[Position] = None,
  13924. timeout: typing.Optional[float] = None,
  13925. no_wait_after: typing.Optional[bool] = None,
  13926. force: typing.Optional[bool] = None,
  13927. trial: typing.Optional[bool] = None,
  13928. ) -> None:
  13929. """Locator.hover
  13930. Hover over the matching element.
  13931. **Usage**
  13932. ```py
  13933. await page.get_by_role(\"link\").hover()
  13934. ```
  13935. **Details**
  13936. This method hovers over the element by performing the following steps:
  13937. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  13938. 1. Scroll the element into view if needed.
  13939. 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
  13940. If the element is detached from the DOM at any moment during the action, this method throws.
  13941. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  13942. Passing zero timeout disables this.
  13943. Parameters
  13944. ----------
  13945. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  13946. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  13947. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  13948. "Control" on Windows and Linux and to "Meta" on macOS.
  13949. position : Union[{x: float, y: float}, None]
  13950. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  13951. the element.
  13952. timeout : Union[float, None]
  13953. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13954. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13955. no_wait_after : Union[bool, None]
  13956. This option has no effect.
  13957. Deprecated: This option has no effect.
  13958. force : Union[bool, None]
  13959. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  13960. trial : Union[bool, None]
  13961. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  13962. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  13963. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  13964. are pressed.
  13965. """
  13966. return mapping.from_maybe_impl(
  13967. await self._impl_obj.hover(
  13968. modifiers=mapping.to_impl(modifiers),
  13969. position=position,
  13970. timeout=timeout,
  13971. noWaitAfter=no_wait_after,
  13972. force=force,
  13973. trial=trial,
  13974. )
  13975. )
  13976. async def inner_html(self, *, timeout: typing.Optional[float] = None) -> str:
  13977. """Locator.inner_html
  13978. Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
  13979. Parameters
  13980. ----------
  13981. timeout : Union[float, None]
  13982. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13983. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13984. Returns
  13985. -------
  13986. str
  13987. """
  13988. return mapping.from_maybe_impl(await self._impl_obj.inner_html(timeout=timeout))
  13989. async def inner_text(self, *, timeout: typing.Optional[float] = None) -> str:
  13990. """Locator.inner_text
  13991. Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
  13992. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
  13993. `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  13994. Parameters
  13995. ----------
  13996. timeout : Union[float, None]
  13997. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  13998. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  13999. Returns
  14000. -------
  14001. str
  14002. """
  14003. return mapping.from_maybe_impl(await self._impl_obj.inner_text(timeout=timeout))
  14004. async def input_value(self, *, timeout: typing.Optional[float] = None) -> str:
  14005. """Locator.input_value
  14006. Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
  14007. **NOTE** If you need to assert input value, prefer `locator_assertions.to_have_value()` to avoid flakiness.
  14008. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14009. **Usage**
  14010. ```py
  14011. value = await page.get_by_role(\"textbox\").input_value()
  14012. ```
  14013. **Details**
  14014. Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
  14015. element that has an associated
  14016. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
  14017. control.
  14018. Parameters
  14019. ----------
  14020. timeout : Union[float, None]
  14021. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14022. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14023. Returns
  14024. -------
  14025. str
  14026. """
  14027. return mapping.from_maybe_impl(
  14028. await self._impl_obj.input_value(timeout=timeout)
  14029. )
  14030. async def is_checked(self, *, timeout: typing.Optional[float] = None) -> bool:
  14031. """Locator.is_checked
  14032. Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
  14033. **NOTE** If you need to assert that checkbox is checked, prefer `locator_assertions.to_be_checked()` to avoid
  14034. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14035. **Usage**
  14036. ```py
  14037. checked = await page.get_by_role(\"checkbox\").is_checked()
  14038. ```
  14039. Parameters
  14040. ----------
  14041. timeout : Union[float, None]
  14042. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14043. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14044. Returns
  14045. -------
  14046. bool
  14047. """
  14048. return mapping.from_maybe_impl(await self._impl_obj.is_checked(timeout=timeout))
  14049. async def is_disabled(self, *, timeout: typing.Optional[float] = None) -> bool:
  14050. """Locator.is_disabled
  14051. Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
  14052. **NOTE** If you need to assert that an element is disabled, prefer `locator_assertions.to_be_disabled()` to
  14053. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14054. **Usage**
  14055. ```py
  14056. disabled = await page.get_by_role(\"button\").is_disabled()
  14057. ```
  14058. Parameters
  14059. ----------
  14060. timeout : Union[float, None]
  14061. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14062. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14063. Returns
  14064. -------
  14065. bool
  14066. """
  14067. return mapping.from_maybe_impl(
  14068. await self._impl_obj.is_disabled(timeout=timeout)
  14069. )
  14070. async def is_editable(self, *, timeout: typing.Optional[float] = None) -> bool:
  14071. """Locator.is_editable
  14072. Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable). If the target element is not an `<input>`,
  14073. `<textarea>`, `<select>`, `[contenteditable]` and does not have a role allowing `[aria-readonly]`, this method
  14074. throws an error.
  14075. **NOTE** If you need to assert that an element is editable, prefer `locator_assertions.to_be_editable()` to
  14076. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14077. **Usage**
  14078. ```py
  14079. editable = await page.get_by_role(\"textbox\").is_editable()
  14080. ```
  14081. Parameters
  14082. ----------
  14083. timeout : Union[float, None]
  14084. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14085. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14086. Returns
  14087. -------
  14088. bool
  14089. """
  14090. return mapping.from_maybe_impl(
  14091. await self._impl_obj.is_editable(timeout=timeout)
  14092. )
  14093. async def is_enabled(self, *, timeout: typing.Optional[float] = None) -> bool:
  14094. """Locator.is_enabled
  14095. Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
  14096. **NOTE** If you need to assert that an element is enabled, prefer `locator_assertions.to_be_enabled()` to
  14097. avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14098. **Usage**
  14099. ```py
  14100. enabled = await page.get_by_role(\"button\").is_enabled()
  14101. ```
  14102. Parameters
  14103. ----------
  14104. timeout : Union[float, None]
  14105. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14106. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14107. Returns
  14108. -------
  14109. bool
  14110. """
  14111. return mapping.from_maybe_impl(await self._impl_obj.is_enabled(timeout=timeout))
  14112. async def is_hidden(self, *, timeout: typing.Optional[float] = None) -> bool:
  14113. """Locator.is_hidden
  14114. Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
  14115. **NOTE** If you need to assert that element is hidden, prefer `locator_assertions.to_be_hidden()` to avoid
  14116. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14117. **Usage**
  14118. ```py
  14119. hidden = await page.get_by_role(\"button\").is_hidden()
  14120. ```
  14121. Parameters
  14122. ----------
  14123. timeout : Union[float, None]
  14124. Deprecated: This option is ignored. `locator.is_hidden()` does not wait for the element to become hidden and returns immediately.
  14125. Returns
  14126. -------
  14127. bool
  14128. """
  14129. return mapping.from_maybe_impl(await self._impl_obj.is_hidden(timeout=timeout))
  14130. async def is_visible(self, *, timeout: typing.Optional[float] = None) -> bool:
  14131. """Locator.is_visible
  14132. Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
  14133. **NOTE** If you need to assert that element is visible, prefer `locator_assertions.to_be_visible()` to avoid
  14134. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14135. **Usage**
  14136. ```py
  14137. visible = await page.get_by_role(\"button\").is_visible()
  14138. ```
  14139. Parameters
  14140. ----------
  14141. timeout : Union[float, None]
  14142. Deprecated: This option is ignored. `locator.is_visible()` does not wait for the element to become visible and returns immediately.
  14143. Returns
  14144. -------
  14145. bool
  14146. """
  14147. return mapping.from_maybe_impl(await self._impl_obj.is_visible(timeout=timeout))
  14148. async def press(
  14149. self,
  14150. key: str,
  14151. *,
  14152. delay: typing.Optional[float] = None,
  14153. timeout: typing.Optional[float] = None,
  14154. no_wait_after: typing.Optional[bool] = None,
  14155. ) -> None:
  14156. """Locator.press
  14157. Focuses the matching element and presses a combination of the keys.
  14158. **Usage**
  14159. ```py
  14160. await page.get_by_role(\"textbox\").press(\"Backspace\")
  14161. ```
  14162. **Details**
  14163. Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
  14164. `key` can specify the intended
  14165. [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
  14166. to generate the text for. A superset of the `key` values can be found
  14167. [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
  14168. `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
  14169. `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
  14170. etc.
  14171. Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
  14172. `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
  14173. Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
  14174. If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
  14175. texts.
  14176. Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
  14177. specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
  14178. Parameters
  14179. ----------
  14180. key : str
  14181. Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
  14182. delay : Union[float, None]
  14183. Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
  14184. timeout : Union[float, None]
  14185. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14186. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14187. no_wait_after : Union[bool, None]
  14188. Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
  14189. can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
  14190. navigating to inaccessible pages. Defaults to `false`.
  14191. Deprecated: This option will default to `true` in the future.
  14192. """
  14193. return mapping.from_maybe_impl(
  14194. await self._impl_obj.press(
  14195. key=key, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  14196. )
  14197. )
  14198. async def screenshot(
  14199. self,
  14200. *,
  14201. timeout: typing.Optional[float] = None,
  14202. type: typing.Optional[Literal["jpeg", "png"]] = None,
  14203. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  14204. quality: typing.Optional[int] = None,
  14205. omit_background: typing.Optional[bool] = None,
  14206. animations: typing.Optional[Literal["allow", "disabled"]] = None,
  14207. caret: typing.Optional[Literal["hide", "initial"]] = None,
  14208. scale: typing.Optional[Literal["css", "device"]] = None,
  14209. mask: typing.Optional[typing.Sequence["Locator"]] = None,
  14210. mask_color: typing.Optional[str] = None,
  14211. style: typing.Optional[str] = None,
  14212. ) -> bytes:
  14213. """Locator.screenshot
  14214. Take a screenshot of the element matching the locator.
  14215. **Usage**
  14216. ```py
  14217. await page.get_by_role(\"link\").screenshot()
  14218. ```
  14219. Disable animations and save screenshot to a file:
  14220. ```py
  14221. await page.get_by_role(\"link\").screenshot(animations=\"disabled\", path=\"link.png\")
  14222. ```
  14223. **Details**
  14224. This method captures a screenshot of the page, clipped to the size and position of a particular element matching
  14225. the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
  14226. element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
  14227. This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
  14228. a screenshot. If the element is detached from DOM, the method throws an error.
  14229. Returns the buffer with the captured screenshot.
  14230. Parameters
  14231. ----------
  14232. timeout : Union[float, None]
  14233. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14234. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14235. type : Union["jpeg", "png", None]
  14236. Specify screenshot type, defaults to `png`.
  14237. path : Union[pathlib.Path, str, None]
  14238. The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
  14239. relative path, then it is resolved relative to the current working directory. If no path is provided, the image
  14240. won't be saved to the disk.
  14241. quality : Union[int, None]
  14242. The quality of the image, between 0-100. Not applicable to `png` images.
  14243. omit_background : Union[bool, None]
  14244. Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
  14245. Defaults to `false`.
  14246. animations : Union["allow", "disabled", None]
  14247. When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
  14248. treatment depending on their duration:
  14249. - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
  14250. - infinite animations are canceled to initial state, and then played over after the screenshot.
  14251. Defaults to `"allow"` that leaves animations untouched.
  14252. caret : Union["hide", "initial", None]
  14253. When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
  14254. changed. Defaults to `"hide"`.
  14255. scale : Union["css", "device", None]
  14256. When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
  14257. will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
  14258. screenshots of high-dpi devices will be twice as large or even larger.
  14259. Defaults to `"device"`.
  14260. mask : Union[Sequence[Locator], None]
  14261. Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
  14262. box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
  14263. invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
  14264. that.
  14265. mask_color : Union[str, None]
  14266. Specify the color of the overlay box for masked elements, in
  14267. [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
  14268. style : Union[str, None]
  14269. Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
  14270. elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
  14271. the Shadow DOM and applies to the inner frames.
  14272. Returns
  14273. -------
  14274. bytes
  14275. """
  14276. return mapping.from_maybe_impl(
  14277. await self._impl_obj.screenshot(
  14278. timeout=timeout,
  14279. type=type,
  14280. path=path,
  14281. quality=quality,
  14282. omitBackground=omit_background,
  14283. animations=animations,
  14284. caret=caret,
  14285. scale=scale,
  14286. mask=mapping.to_impl(mask),
  14287. maskColor=mask_color,
  14288. style=style,
  14289. )
  14290. )
  14291. async def aria_snapshot(self, *, timeout: typing.Optional[float] = None) -> str:
  14292. """Locator.aria_snapshot
  14293. Captures the aria snapshot of the given element. Read more about [aria snapshots](https://playwright.dev/python/docs/aria-snapshots) and
  14294. `locator_assertions.to_match_aria_snapshot()` for the corresponding assertion.
  14295. **Usage**
  14296. ```py
  14297. await page.get_by_role(\"link\").aria_snapshot()
  14298. ```
  14299. **Details**
  14300. This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of
  14301. the element and its children. The snapshot can be used to assert the state of the element in the test, or to
  14302. compare it to state in the future.
  14303. The ARIA snapshot is represented using [YAML](https://yaml.org/spec/1.2.2/) markup language:
  14304. - The keys of the objects are the roles and optional accessible names of the elements.
  14305. - The values are either text content or an array of child elements.
  14306. - Generic static text can be represented with the `text` key.
  14307. Below is the HTML markup and the respective ARIA snapshot:
  14308. ```html
  14309. <ul aria-label=\"Links\">
  14310. <li><a href=\"/\">Home</a></li>
  14311. <li><a href=\"/about\">About</a></li>
  14312. <ul>
  14313. ```
  14314. ```yml
  14315. - list \"Links\":
  14316. - listitem:
  14317. - link \"Home\"
  14318. - listitem:
  14319. - link \"About\"
  14320. ```
  14321. Parameters
  14322. ----------
  14323. timeout : Union[float, None]
  14324. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14325. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14326. Returns
  14327. -------
  14328. str
  14329. """
  14330. return mapping.from_maybe_impl(
  14331. await self._impl_obj.aria_snapshot(timeout=timeout)
  14332. )
  14333. async def scroll_into_view_if_needed(
  14334. self, *, timeout: typing.Optional[float] = None
  14335. ) -> None:
  14336. """Locator.scroll_into_view_if_needed
  14337. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
  14338. it is completely visible as defined by
  14339. [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
  14340. See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
  14341. Parameters
  14342. ----------
  14343. timeout : Union[float, None]
  14344. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14345. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14346. """
  14347. return mapping.from_maybe_impl(
  14348. await self._impl_obj.scroll_into_view_if_needed(timeout=timeout)
  14349. )
  14350. async def select_option(
  14351. self,
  14352. value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  14353. *,
  14354. index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
  14355. label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
  14356. element: typing.Optional[
  14357. typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
  14358. ] = None,
  14359. timeout: typing.Optional[float] = None,
  14360. no_wait_after: typing.Optional[bool] = None,
  14361. force: typing.Optional[bool] = None,
  14362. ) -> typing.List[str]:
  14363. """Locator.select_option
  14364. Selects option or options in `<select>`.
  14365. **Details**
  14366. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
  14367. the `<select>` element and selects these options.
  14368. If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
  14369. the `<label>` element that has an associated
  14370. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
  14371. instead.
  14372. Returns the array of option values that have been successfully selected.
  14373. Triggers a `change` and `input` event once all the provided options have been selected.
  14374. **Usage**
  14375. ```html
  14376. <select multiple>
  14377. <option value=\"red\">Red</option>
  14378. <option value=\"green\">Green</option>
  14379. <option value=\"blue\">Blue</option>
  14380. </select>
  14381. ```
  14382. ```py
  14383. # single selection matching the value or label
  14384. await element.select_option(\"blue\")
  14385. # single selection matching the label
  14386. await element.select_option(label=\"blue\")
  14387. # multiple selection for blue, red and second option
  14388. await element.select_option(value=[\"red\", \"green\", \"blue\"])
  14389. ```
  14390. Parameters
  14391. ----------
  14392. value : Union[Sequence[str], str, None]
  14393. Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
  14394. otherwise only the first option matching one of the passed options is selected. Optional.
  14395. index : Union[Sequence[int], int, None]
  14396. Options to select by index. Optional.
  14397. label : Union[Sequence[str], str, None]
  14398. Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
  14399. otherwise only the first option matching one of the passed options is selected. Optional.
  14400. element : Union[ElementHandle, Sequence[ElementHandle], None]
  14401. Option elements to select. Optional.
  14402. timeout : Union[float, None]
  14403. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14404. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14405. no_wait_after : Union[bool, None]
  14406. This option has no effect.
  14407. Deprecated: This option has no effect.
  14408. force : Union[bool, None]
  14409. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14410. Returns
  14411. -------
  14412. List[str]
  14413. """
  14414. return mapping.from_maybe_impl(
  14415. await self._impl_obj.select_option(
  14416. value=mapping.to_impl(value),
  14417. index=mapping.to_impl(index),
  14418. label=mapping.to_impl(label),
  14419. element=mapping.to_impl(element),
  14420. timeout=timeout,
  14421. noWaitAfter=no_wait_after,
  14422. force=force,
  14423. )
  14424. )
  14425. async def select_text(
  14426. self,
  14427. *,
  14428. force: typing.Optional[bool] = None,
  14429. timeout: typing.Optional[float] = None,
  14430. ) -> None:
  14431. """Locator.select_text
  14432. This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
  14433. text content.
  14434. If the element is inside the `<label>` element that has an associated
  14435. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
  14436. the control instead.
  14437. Parameters
  14438. ----------
  14439. force : Union[bool, None]
  14440. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14441. timeout : Union[float, None]
  14442. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14443. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14444. """
  14445. return mapping.from_maybe_impl(
  14446. await self._impl_obj.select_text(force=force, timeout=timeout)
  14447. )
  14448. async def set_input_files(
  14449. self,
  14450. files: typing.Union[
  14451. str,
  14452. pathlib.Path,
  14453. FilePayload,
  14454. typing.Sequence[typing.Union[str, pathlib.Path]],
  14455. typing.Sequence[FilePayload],
  14456. ],
  14457. *,
  14458. timeout: typing.Optional[float] = None,
  14459. no_wait_after: typing.Optional[bool] = None,
  14460. ) -> None:
  14461. """Locator.set_input_files
  14462. Upload file or multiple files into `<input type=file>`. For inputs with a `[webkitdirectory]` attribute, only a
  14463. single directory path is supported.
  14464. **Usage**
  14465. ```py
  14466. # Select one file
  14467. await page.get_by_label(\"Upload file\").set_input_files('myfile.pdf')
  14468. # Select multiple files
  14469. await page.get_by_label(\"Upload files\").set_input_files(['file1.txt', 'file2.txt'])
  14470. # Select a directory
  14471. await page.get_by_label(\"Upload directory\").set_input_files('mydir')
  14472. # Remove all the selected files
  14473. await page.get_by_label(\"Upload file\").set_input_files([])
  14474. # Upload buffer from memory
  14475. await page.get_by_label(\"Upload file\").set_input_files(
  14476. files=[
  14477. {\"name\": \"test.txt\", \"mimeType\": \"text/plain\", \"buffer\": b\"this is a test\"}
  14478. ],
  14479. )
  14480. ```
  14481. **Details**
  14482. Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
  14483. they are resolved relative to the current working directory. For empty array, clears the selected files.
  14484. This method expects `Locator` to point to an
  14485. [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
  14486. the `<label>` element that has an associated
  14487. [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
  14488. Parameters
  14489. ----------
  14490. files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
  14491. timeout : Union[float, None]
  14492. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14493. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14494. no_wait_after : Union[bool, None]
  14495. This option has no effect.
  14496. Deprecated: This option has no effect.
  14497. """
  14498. return mapping.from_maybe_impl(
  14499. await self._impl_obj.set_input_files(
  14500. files=mapping.to_impl(files), timeout=timeout, noWaitAfter=no_wait_after
  14501. )
  14502. )
  14503. async def tap(
  14504. self,
  14505. *,
  14506. modifiers: typing.Optional[
  14507. typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
  14508. ] = None,
  14509. position: typing.Optional[Position] = None,
  14510. timeout: typing.Optional[float] = None,
  14511. force: typing.Optional[bool] = None,
  14512. no_wait_after: typing.Optional[bool] = None,
  14513. trial: typing.Optional[bool] = None,
  14514. ) -> None:
  14515. """Locator.tap
  14516. Perform a tap gesture on the element matching the locator. For examples of emulating other gestures by manually
  14517. dispatching touch events, see the [emulating legacy touch events](https://playwright.dev/python/docs/touch-events) page.
  14518. **Details**
  14519. This method taps the element by performing the following steps:
  14520. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14521. 1. Scroll the element into view if needed.
  14522. 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
  14523. If the element is detached from the DOM at any moment during the action, this method throws.
  14524. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14525. Passing zero timeout disables this.
  14526. **NOTE** `element.tap()` requires that the `hasTouch` option of the browser context be set to true.
  14527. Parameters
  14528. ----------
  14529. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
  14530. Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
  14531. current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
  14532. "Control" on Windows and Linux and to "Meta" on macOS.
  14533. position : Union[{x: float, y: float}, None]
  14534. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14535. the element.
  14536. timeout : Union[float, None]
  14537. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14538. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14539. force : Union[bool, None]
  14540. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14541. no_wait_after : Union[bool, None]
  14542. This option has no effect.
  14543. Deprecated: This option has no effect.
  14544. trial : Union[bool, None]
  14545. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14546. to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
  14547. `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
  14548. are pressed.
  14549. """
  14550. return mapping.from_maybe_impl(
  14551. await self._impl_obj.tap(
  14552. modifiers=mapping.to_impl(modifiers),
  14553. position=position,
  14554. timeout=timeout,
  14555. force=force,
  14556. noWaitAfter=no_wait_after,
  14557. trial=trial,
  14558. )
  14559. )
  14560. async def text_content(
  14561. self, *, timeout: typing.Optional[float] = None
  14562. ) -> typing.Optional[str]:
  14563. """Locator.text_content
  14564. Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
  14565. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
  14566. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14567. Parameters
  14568. ----------
  14569. timeout : Union[float, None]
  14570. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14571. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14572. Returns
  14573. -------
  14574. Union[str, None]
  14575. """
  14576. return mapping.from_maybe_impl(
  14577. await self._impl_obj.text_content(timeout=timeout)
  14578. )
  14579. async def type(
  14580. self,
  14581. text: str,
  14582. *,
  14583. delay: typing.Optional[float] = None,
  14584. timeout: typing.Optional[float] = None,
  14585. no_wait_after: typing.Optional[bool] = None,
  14586. ) -> None:
  14587. """Locator.type
  14588. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  14589. text.
  14590. To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
  14591. **Usage**
  14592. Parameters
  14593. ----------
  14594. text : str
  14595. A text to type into a focused element.
  14596. delay : Union[float, None]
  14597. Time to wait between key presses in milliseconds. Defaults to 0.
  14598. timeout : Union[float, None]
  14599. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14600. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14601. no_wait_after : Union[bool, None]
  14602. This option has no effect.
  14603. Deprecated: This option has no effect.
  14604. """
  14605. return mapping.from_maybe_impl(
  14606. await self._impl_obj.type(
  14607. text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  14608. )
  14609. )
  14610. async def press_sequentially(
  14611. self,
  14612. text: str,
  14613. *,
  14614. delay: typing.Optional[float] = None,
  14615. timeout: typing.Optional[float] = None,
  14616. no_wait_after: typing.Optional[bool] = None,
  14617. ) -> None:
  14618. """Locator.press_sequentially
  14619. **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
  14620. there is special keyboard handling on the page.
  14621. Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
  14622. text.
  14623. To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
  14624. **Usage**
  14625. ```py
  14626. await locator.press_sequentially(\"hello\") # types instantly
  14627. await locator.press_sequentially(\"world\", delay=100) # types slower, like a user
  14628. ```
  14629. An example of typing into a text field and then submitting the form:
  14630. ```py
  14631. locator = page.get_by_label(\"Password\")
  14632. await locator.press_sequentially(\"my password\")
  14633. await locator.press(\"Enter\")
  14634. ```
  14635. Parameters
  14636. ----------
  14637. text : str
  14638. String of characters to sequentially press into a focused element.
  14639. delay : Union[float, None]
  14640. Time to wait between key presses in milliseconds. Defaults to 0.
  14641. timeout : Union[float, None]
  14642. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14643. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14644. no_wait_after : Union[bool, None]
  14645. This option has no effect.
  14646. Deprecated: This option has no effect.
  14647. """
  14648. return mapping.from_maybe_impl(
  14649. await self._impl_obj.press_sequentially(
  14650. text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
  14651. )
  14652. )
  14653. async def uncheck(
  14654. self,
  14655. *,
  14656. position: typing.Optional[Position] = None,
  14657. timeout: typing.Optional[float] = None,
  14658. force: typing.Optional[bool] = None,
  14659. no_wait_after: typing.Optional[bool] = None,
  14660. trial: typing.Optional[bool] = None,
  14661. ) -> None:
  14662. """Locator.uncheck
  14663. Ensure that checkbox or radio element is unchecked.
  14664. **Usage**
  14665. ```py
  14666. await page.get_by_role(\"checkbox\").uncheck()
  14667. ```
  14668. **Details**
  14669. This method unchecks the element by performing the following steps:
  14670. 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
  14671. unchecked, this method returns immediately.
  14672. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
  14673. 1. Scroll the element into view if needed.
  14674. 1. Use `page.mouse` to click in the center of the element.
  14675. 1. Ensure that the element is now unchecked. If not, this method throws.
  14676. If the element is detached from the DOM at any moment during the action, this method throws.
  14677. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14678. Passing zero timeout disables this.
  14679. Parameters
  14680. ----------
  14681. position : Union[{x: float, y: float}, None]
  14682. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14683. the element.
  14684. timeout : Union[float, None]
  14685. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14686. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14687. force : Union[bool, None]
  14688. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14689. no_wait_after : Union[bool, None]
  14690. This option has no effect.
  14691. Deprecated: This option has no effect.
  14692. trial : Union[bool, None]
  14693. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14694. to `false`. Useful to wait until the element is ready for the action without performing it.
  14695. """
  14696. return mapping.from_maybe_impl(
  14697. await self._impl_obj.uncheck(
  14698. position=position,
  14699. timeout=timeout,
  14700. force=force,
  14701. noWaitAfter=no_wait_after,
  14702. trial=trial,
  14703. )
  14704. )
  14705. async def all_inner_texts(self) -> typing.List[str]:
  14706. """Locator.all_inner_texts
  14707. Returns an array of `node.innerText` values for all matching nodes.
  14708. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
  14709. `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14710. **Usage**
  14711. ```py
  14712. texts = await page.get_by_role(\"link\").all_inner_texts()
  14713. ```
  14714. Returns
  14715. -------
  14716. List[str]
  14717. """
  14718. return mapping.from_maybe_impl(await self._impl_obj.all_inner_texts())
  14719. async def all_text_contents(self) -> typing.List[str]:
  14720. """Locator.all_text_contents
  14721. Returns an array of `node.textContent` values for all matching nodes.
  14722. **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
  14723. flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
  14724. **Usage**
  14725. ```py
  14726. texts = await page.get_by_role(\"link\").all_text_contents()
  14727. ```
  14728. Returns
  14729. -------
  14730. List[str]
  14731. """
  14732. return mapping.from_maybe_impl(await self._impl_obj.all_text_contents())
  14733. async def wait_for(
  14734. self,
  14735. *,
  14736. timeout: typing.Optional[float] = None,
  14737. state: typing.Optional[
  14738. Literal["attached", "detached", "hidden", "visible"]
  14739. ] = None,
  14740. ) -> None:
  14741. """Locator.wait_for
  14742. Returns when element specified by locator satisfies the `state` option.
  14743. If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
  14744. `timeout` milliseconds until the condition is met.
  14745. **Usage**
  14746. ```py
  14747. order_sent = page.locator(\"#order-sent\")
  14748. await order_sent.wait_for()
  14749. ```
  14750. Parameters
  14751. ----------
  14752. timeout : Union[float, None]
  14753. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14754. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14755. state : Union["attached", "detached", "hidden", "visible", None]
  14756. Defaults to `'visible'`. Can be either:
  14757. - `'attached'` - wait for element to be present in DOM.
  14758. - `'detached'` - wait for element to not be present in DOM.
  14759. - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
  14760. without any content or with `display:none` has an empty bounding box and is not considered visible.
  14761. - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
  14762. `visibility:hidden`. This is opposite to the `'visible'` option.
  14763. """
  14764. return mapping.from_maybe_impl(
  14765. await self._impl_obj.wait_for(timeout=timeout, state=state)
  14766. )
  14767. async def set_checked(
  14768. self,
  14769. checked: bool,
  14770. *,
  14771. position: typing.Optional[Position] = None,
  14772. timeout: typing.Optional[float] = None,
  14773. force: typing.Optional[bool] = None,
  14774. no_wait_after: typing.Optional[bool] = None,
  14775. trial: typing.Optional[bool] = None,
  14776. ) -> None:
  14777. """Locator.set_checked
  14778. Set the state of a checkbox or a radio element.
  14779. **Usage**
  14780. ```py
  14781. await page.get_by_role(\"checkbox\").set_checked(True)
  14782. ```
  14783. **Details**
  14784. This method checks or unchecks an element by performing the following steps:
  14785. 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  14786. 1. If the element already has the right checked state, this method returns immediately.
  14787. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
  14788. the element is detached during the checks, the whole action is retried.
  14789. 1. Scroll the element into view if needed.
  14790. 1. Use `page.mouse` to click in the center of the element.
  14791. 1. Ensure that the element is now checked or unchecked. If not, this method throws.
  14792. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
  14793. Passing zero timeout disables this.
  14794. Parameters
  14795. ----------
  14796. checked : bool
  14797. Whether to check or uncheck the checkbox.
  14798. position : Union[{x: float, y: float}, None]
  14799. A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
  14800. the element.
  14801. timeout : Union[float, None]
  14802. Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
  14803. be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
  14804. force : Union[bool, None]
  14805. Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
  14806. no_wait_after : Union[bool, None]
  14807. This option has no effect.
  14808. Deprecated: This option has no effect.
  14809. trial : Union[bool, None]
  14810. When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
  14811. to `false`. Useful to wait until the element is ready for the action without performing it.
  14812. """
  14813. return mapping.from_maybe_impl(
  14814. await self._impl_obj.set_checked(
  14815. checked=checked,
  14816. position=position,
  14817. timeout=timeout,
  14818. force=force,
  14819. noWaitAfter=no_wait_after,
  14820. trial=trial,
  14821. )
  14822. )
  14823. async def highlight(self) -> None:
  14824. """Locator.highlight
  14825. Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
  14826. `locator.highlight()`.
  14827. """
  14828. return mapping.from_maybe_impl(await self._impl_obj.highlight())
  14829. mapping.register(LocatorImpl, Locator)
  14830. class APIResponse(AsyncBase):
  14831. @property
  14832. def ok(self) -> bool:
  14833. """APIResponse.ok
  14834. Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
  14835. Returns
  14836. -------
  14837. bool
  14838. """
  14839. return mapping.from_maybe_impl(self._impl_obj.ok)
  14840. @property
  14841. def url(self) -> str:
  14842. """APIResponse.url
  14843. Contains the URL of the response.
  14844. Returns
  14845. -------
  14846. str
  14847. """
  14848. return mapping.from_maybe_impl(self._impl_obj.url)
  14849. @property
  14850. def status(self) -> int:
  14851. """APIResponse.status
  14852. Contains the status code of the response (e.g., 200 for a success).
  14853. Returns
  14854. -------
  14855. int
  14856. """
  14857. return mapping.from_maybe_impl(self._impl_obj.status)
  14858. @property
  14859. def status_text(self) -> str:
  14860. """APIResponse.status_text
  14861. Contains the status text of the response (e.g. usually an \"OK\" for a success).
  14862. Returns
  14863. -------
  14864. str
  14865. """
  14866. return mapping.from_maybe_impl(self._impl_obj.status_text)
  14867. @property
  14868. def headers(self) -> typing.Dict[str, str]:
  14869. """APIResponse.headers
  14870. An object with all the response HTTP headers associated with this response.
  14871. Returns
  14872. -------
  14873. Dict[str, str]
  14874. """
  14875. return mapping.from_maybe_impl(self._impl_obj.headers)
  14876. @property
  14877. def headers_array(self) -> typing.List[NameValue]:
  14878. """APIResponse.headers_array
  14879. An array with all the response HTTP headers associated with this response. Header names are not lower-cased.
  14880. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.
  14881. Returns
  14882. -------
  14883. List[{name: str, value: str}]
  14884. """
  14885. return mapping.from_impl_list(self._impl_obj.headers_array)
  14886. async def body(self) -> bytes:
  14887. """APIResponse.body
  14888. Returns the buffer with response body.
  14889. Returns
  14890. -------
  14891. bytes
  14892. """
  14893. return mapping.from_maybe_impl(await self._impl_obj.body())
  14894. async def text(self) -> str:
  14895. """APIResponse.text
  14896. Returns the text representation of response body.
  14897. Returns
  14898. -------
  14899. str
  14900. """
  14901. return mapping.from_maybe_impl(await self._impl_obj.text())
  14902. async def json(self) -> typing.Any:
  14903. """APIResponse.json
  14904. Returns the JSON representation of response body.
  14905. This method will throw if the response body is not parsable via `JSON.parse`.
  14906. Returns
  14907. -------
  14908. Any
  14909. """
  14910. return mapping.from_maybe_impl(await self._impl_obj.json())
  14911. async def dispose(self) -> None:
  14912. """APIResponse.dispose
  14913. Disposes the body of this response. If not called then the body will stay in memory until the context closes.
  14914. """
  14915. return mapping.from_maybe_impl(await self._impl_obj.dispose())
  14916. mapping.register(APIResponseImpl, APIResponse)
  14917. class APIRequestContext(AsyncBase):
  14918. async def dispose(self, *, reason: typing.Optional[str] = None) -> None:
  14919. """APIRequestContext.dispose
  14920. All responses returned by `a_pi_request_context.get()` and similar methods are stored in the memory, so that
  14921. you can later call `a_pi_response.body()`.This method discards all its resources, calling any method on
  14922. disposed `APIRequestContext` will throw an exception.
  14923. Parameters
  14924. ----------
  14925. reason : Union[str, None]
  14926. The reason to be reported to the operations interrupted by the context disposal.
  14927. """
  14928. return mapping.from_maybe_impl(await self._impl_obj.dispose(reason=reason))
  14929. async def delete(
  14930. self,
  14931. url: str,
  14932. *,
  14933. params: typing.Optional[
  14934. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  14935. ] = None,
  14936. headers: typing.Optional[typing.Dict[str, str]] = None,
  14937. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  14938. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  14939. multipart: typing.Optional[
  14940. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  14941. ] = None,
  14942. timeout: typing.Optional[float] = None,
  14943. fail_on_status_code: typing.Optional[bool] = None,
  14944. ignore_https_errors: typing.Optional[bool] = None,
  14945. max_redirects: typing.Optional[int] = None,
  14946. max_retries: typing.Optional[int] = None,
  14947. ) -> "APIResponse":
  14948. """APIRequestContext.delete
  14949. Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
  14950. response. The method will populate request cookies from the context and update context cookies from the response.
  14951. The method will automatically follow redirects.
  14952. Parameters
  14953. ----------
  14954. url : str
  14955. Target URL.
  14956. params : Union[Dict[str, Union[bool, float, str]], str, None]
  14957. Query parameters to be sent with the URL.
  14958. headers : Union[Dict[str, str], None]
  14959. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  14960. it.
  14961. data : Union[Any, bytes, str, None]
  14962. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  14963. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  14964. header will be set to `application/octet-stream` if not explicitly set.
  14965. form : Union[Dict[str, Union[bool, float, str]], None]
  14966. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  14967. as this request body. If this parameter is specified `content-type` header will be set to
  14968. `application/x-www-form-urlencoded` unless explicitly provided.
  14969. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  14970. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  14971. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  14972. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  14973. timeout : Union[float, None]
  14974. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  14975. fail_on_status_code : Union[bool, None]
  14976. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  14977. codes.
  14978. ignore_https_errors : Union[bool, None]
  14979. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  14980. max_redirects : Union[int, None]
  14981. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  14982. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  14983. max_retries : Union[int, None]
  14984. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  14985. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  14986. Returns
  14987. -------
  14988. APIResponse
  14989. """
  14990. return mapping.from_impl(
  14991. await self._impl_obj.delete(
  14992. url=url,
  14993. params=mapping.to_impl(params),
  14994. headers=mapping.to_impl(headers),
  14995. data=mapping.to_impl(data),
  14996. form=mapping.to_impl(form),
  14997. multipart=mapping.to_impl(multipart),
  14998. timeout=timeout,
  14999. failOnStatusCode=fail_on_status_code,
  15000. ignoreHTTPSErrors=ignore_https_errors,
  15001. maxRedirects=max_redirects,
  15002. maxRetries=max_retries,
  15003. )
  15004. )
  15005. async def head(
  15006. self,
  15007. url: str,
  15008. *,
  15009. params: typing.Optional[
  15010. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15011. ] = None,
  15012. headers: typing.Optional[typing.Dict[str, str]] = None,
  15013. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15014. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15015. multipart: typing.Optional[
  15016. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15017. ] = None,
  15018. timeout: typing.Optional[float] = None,
  15019. fail_on_status_code: typing.Optional[bool] = None,
  15020. ignore_https_errors: typing.Optional[bool] = None,
  15021. max_redirects: typing.Optional[int] = None,
  15022. max_retries: typing.Optional[int] = None,
  15023. ) -> "APIResponse":
  15024. """APIRequestContext.head
  15025. Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its
  15026. response. The method will populate request cookies from the context and update context cookies from the response.
  15027. The method will automatically follow redirects.
  15028. Parameters
  15029. ----------
  15030. url : str
  15031. Target URL.
  15032. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15033. Query parameters to be sent with the URL.
  15034. headers : Union[Dict[str, str], None]
  15035. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15036. it.
  15037. data : Union[Any, bytes, str, None]
  15038. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15039. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15040. header will be set to `application/octet-stream` if not explicitly set.
  15041. form : Union[Dict[str, Union[bool, float, str]], None]
  15042. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15043. as this request body. If this parameter is specified `content-type` header will be set to
  15044. `application/x-www-form-urlencoded` unless explicitly provided.
  15045. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15046. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15047. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15048. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15049. timeout : Union[float, None]
  15050. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15051. fail_on_status_code : Union[bool, None]
  15052. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15053. codes.
  15054. ignore_https_errors : Union[bool, None]
  15055. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15056. max_redirects : Union[int, None]
  15057. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15058. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15059. max_retries : Union[int, None]
  15060. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15061. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15062. Returns
  15063. -------
  15064. APIResponse
  15065. """
  15066. return mapping.from_impl(
  15067. await self._impl_obj.head(
  15068. url=url,
  15069. params=mapping.to_impl(params),
  15070. headers=mapping.to_impl(headers),
  15071. data=mapping.to_impl(data),
  15072. form=mapping.to_impl(form),
  15073. multipart=mapping.to_impl(multipart),
  15074. timeout=timeout,
  15075. failOnStatusCode=fail_on_status_code,
  15076. ignoreHTTPSErrors=ignore_https_errors,
  15077. maxRedirects=max_redirects,
  15078. maxRetries=max_retries,
  15079. )
  15080. )
  15081. async def get(
  15082. self,
  15083. url: str,
  15084. *,
  15085. params: typing.Optional[
  15086. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15087. ] = None,
  15088. headers: typing.Optional[typing.Dict[str, str]] = None,
  15089. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15090. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15091. multipart: typing.Optional[
  15092. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15093. ] = None,
  15094. timeout: typing.Optional[float] = None,
  15095. fail_on_status_code: typing.Optional[bool] = None,
  15096. ignore_https_errors: typing.Optional[bool] = None,
  15097. max_redirects: typing.Optional[int] = None,
  15098. max_retries: typing.Optional[int] = None,
  15099. ) -> "APIResponse":
  15100. """APIRequestContext.get
  15101. Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its
  15102. response. The method will populate request cookies from the context and update context cookies from the response.
  15103. The method will automatically follow redirects.
  15104. **Usage**
  15105. Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
  15106. ```python
  15107. query_params = {
  15108. \"isbn\": \"1234\",
  15109. \"page\": \"23\"
  15110. }
  15111. api_request_context.get(\"https://example.com/api/getText\", params=query_params)
  15112. ```
  15113. Parameters
  15114. ----------
  15115. url : str
  15116. Target URL.
  15117. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15118. Query parameters to be sent with the URL.
  15119. headers : Union[Dict[str, str], None]
  15120. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15121. it.
  15122. data : Union[Any, bytes, str, None]
  15123. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15124. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15125. header will be set to `application/octet-stream` if not explicitly set.
  15126. form : Union[Dict[str, Union[bool, float, str]], None]
  15127. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15128. as this request body. If this parameter is specified `content-type` header will be set to
  15129. `application/x-www-form-urlencoded` unless explicitly provided.
  15130. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15131. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15132. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15133. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15134. timeout : Union[float, None]
  15135. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15136. fail_on_status_code : Union[bool, None]
  15137. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15138. codes.
  15139. ignore_https_errors : Union[bool, None]
  15140. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15141. max_redirects : Union[int, None]
  15142. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15143. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15144. max_retries : Union[int, None]
  15145. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15146. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15147. Returns
  15148. -------
  15149. APIResponse
  15150. """
  15151. return mapping.from_impl(
  15152. await self._impl_obj.get(
  15153. url=url,
  15154. params=mapping.to_impl(params),
  15155. headers=mapping.to_impl(headers),
  15156. data=mapping.to_impl(data),
  15157. form=mapping.to_impl(form),
  15158. multipart=mapping.to_impl(multipart),
  15159. timeout=timeout,
  15160. failOnStatusCode=fail_on_status_code,
  15161. ignoreHTTPSErrors=ignore_https_errors,
  15162. maxRedirects=max_redirects,
  15163. maxRetries=max_retries,
  15164. )
  15165. )
  15166. async def patch(
  15167. self,
  15168. url: str,
  15169. *,
  15170. params: typing.Optional[
  15171. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15172. ] = None,
  15173. headers: typing.Optional[typing.Dict[str, str]] = None,
  15174. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15175. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15176. multipart: typing.Optional[
  15177. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15178. ] = None,
  15179. timeout: typing.Optional[float] = None,
  15180. fail_on_status_code: typing.Optional[bool] = None,
  15181. ignore_https_errors: typing.Optional[bool] = None,
  15182. max_redirects: typing.Optional[int] = None,
  15183. max_retries: typing.Optional[int] = None,
  15184. ) -> "APIResponse":
  15185. """APIRequestContext.patch
  15186. Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its
  15187. response. The method will populate request cookies from the context and update context cookies from the response.
  15188. The method will automatically follow redirects.
  15189. Parameters
  15190. ----------
  15191. url : str
  15192. Target URL.
  15193. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15194. Query parameters to be sent with the URL.
  15195. headers : Union[Dict[str, str], None]
  15196. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15197. it.
  15198. data : Union[Any, bytes, str, None]
  15199. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15200. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15201. header will be set to `application/octet-stream` if not explicitly set.
  15202. form : Union[Dict[str, Union[bool, float, str]], None]
  15203. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15204. as this request body. If this parameter is specified `content-type` header will be set to
  15205. `application/x-www-form-urlencoded` unless explicitly provided.
  15206. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15207. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15208. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15209. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15210. timeout : Union[float, None]
  15211. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15212. fail_on_status_code : Union[bool, None]
  15213. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15214. codes.
  15215. ignore_https_errors : Union[bool, None]
  15216. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15217. max_redirects : Union[int, None]
  15218. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15219. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15220. max_retries : Union[int, None]
  15221. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15222. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15223. Returns
  15224. -------
  15225. APIResponse
  15226. """
  15227. return mapping.from_impl(
  15228. await self._impl_obj.patch(
  15229. url=url,
  15230. params=mapping.to_impl(params),
  15231. headers=mapping.to_impl(headers),
  15232. data=mapping.to_impl(data),
  15233. form=mapping.to_impl(form),
  15234. multipart=mapping.to_impl(multipart),
  15235. timeout=timeout,
  15236. failOnStatusCode=fail_on_status_code,
  15237. ignoreHTTPSErrors=ignore_https_errors,
  15238. maxRedirects=max_redirects,
  15239. maxRetries=max_retries,
  15240. )
  15241. )
  15242. async def put(
  15243. self,
  15244. url: str,
  15245. *,
  15246. params: typing.Optional[
  15247. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15248. ] = None,
  15249. headers: typing.Optional[typing.Dict[str, str]] = None,
  15250. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15251. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15252. multipart: typing.Optional[
  15253. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15254. ] = None,
  15255. timeout: typing.Optional[float] = None,
  15256. fail_on_status_code: typing.Optional[bool] = None,
  15257. ignore_https_errors: typing.Optional[bool] = None,
  15258. max_redirects: typing.Optional[int] = None,
  15259. max_retries: typing.Optional[int] = None,
  15260. ) -> "APIResponse":
  15261. """APIRequestContext.put
  15262. Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its
  15263. response. The method will populate request cookies from the context and update context cookies from the response.
  15264. The method will automatically follow redirects.
  15265. Parameters
  15266. ----------
  15267. url : str
  15268. Target URL.
  15269. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15270. Query parameters to be sent with the URL.
  15271. headers : Union[Dict[str, str], None]
  15272. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15273. it.
  15274. data : Union[Any, bytes, str, None]
  15275. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15276. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15277. header will be set to `application/octet-stream` if not explicitly set.
  15278. form : Union[Dict[str, Union[bool, float, str]], None]
  15279. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15280. as this request body. If this parameter is specified `content-type` header will be set to
  15281. `application/x-www-form-urlencoded` unless explicitly provided.
  15282. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15283. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15284. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15285. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15286. timeout : Union[float, None]
  15287. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15288. fail_on_status_code : Union[bool, None]
  15289. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15290. codes.
  15291. ignore_https_errors : Union[bool, None]
  15292. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15293. max_redirects : Union[int, None]
  15294. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15295. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15296. max_retries : Union[int, None]
  15297. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15298. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15299. Returns
  15300. -------
  15301. APIResponse
  15302. """
  15303. return mapping.from_impl(
  15304. await self._impl_obj.put(
  15305. url=url,
  15306. params=mapping.to_impl(params),
  15307. headers=mapping.to_impl(headers),
  15308. data=mapping.to_impl(data),
  15309. form=mapping.to_impl(form),
  15310. multipart=mapping.to_impl(multipart),
  15311. timeout=timeout,
  15312. failOnStatusCode=fail_on_status_code,
  15313. ignoreHTTPSErrors=ignore_https_errors,
  15314. maxRedirects=max_redirects,
  15315. maxRetries=max_retries,
  15316. )
  15317. )
  15318. async def post(
  15319. self,
  15320. url: str,
  15321. *,
  15322. params: typing.Optional[
  15323. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15324. ] = None,
  15325. headers: typing.Optional[typing.Dict[str, str]] = None,
  15326. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15327. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15328. multipart: typing.Optional[
  15329. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15330. ] = None,
  15331. timeout: typing.Optional[float] = None,
  15332. fail_on_status_code: typing.Optional[bool] = None,
  15333. ignore_https_errors: typing.Optional[bool] = None,
  15334. max_redirects: typing.Optional[int] = None,
  15335. max_retries: typing.Optional[int] = None,
  15336. ) -> "APIResponse":
  15337. """APIRequestContext.post
  15338. Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its
  15339. response. The method will populate request cookies from the context and update context cookies from the response.
  15340. The method will automatically follow redirects.
  15341. **Usage**
  15342. JSON objects can be passed directly to the request:
  15343. ```python
  15344. data = {
  15345. \"title\": \"Book Title\",
  15346. \"body\": \"John Doe\",
  15347. }
  15348. api_request_context.post(\"https://example.com/api/createBook\", data=data)
  15349. ```
  15350. To send form data to the server use `form` option. Its value will be encoded into the request body with
  15351. `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send
  15352. files):
  15353. The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
  15354. encoding. Use `FormData` to construct request body and pass it to the request as `multipart` parameter:
  15355. ```python
  15356. api_request_context.post(
  15357. \"https://example.com/api/uploadScript'\",
  15358. multipart={
  15359. \"fileField\": {
  15360. \"name\": \"f.js\",
  15361. \"mimeType\": \"text/javascript\",
  15362. \"buffer\": b\"console.log(2022);\",
  15363. },
  15364. })
  15365. ```
  15366. Parameters
  15367. ----------
  15368. url : str
  15369. Target URL.
  15370. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15371. Query parameters to be sent with the URL.
  15372. headers : Union[Dict[str, str], None]
  15373. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15374. it.
  15375. data : Union[Any, bytes, str, None]
  15376. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15377. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15378. header will be set to `application/octet-stream` if not explicitly set.
  15379. form : Union[Dict[str, Union[bool, float, str]], None]
  15380. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15381. as this request body. If this parameter is specified `content-type` header will be set to
  15382. `application/x-www-form-urlencoded` unless explicitly provided.
  15383. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15384. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15385. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15386. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15387. timeout : Union[float, None]
  15388. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15389. fail_on_status_code : Union[bool, None]
  15390. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15391. codes.
  15392. ignore_https_errors : Union[bool, None]
  15393. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15394. max_redirects : Union[int, None]
  15395. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15396. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15397. max_retries : Union[int, None]
  15398. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15399. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15400. Returns
  15401. -------
  15402. APIResponse
  15403. """
  15404. return mapping.from_impl(
  15405. await self._impl_obj.post(
  15406. url=url,
  15407. params=mapping.to_impl(params),
  15408. headers=mapping.to_impl(headers),
  15409. data=mapping.to_impl(data),
  15410. form=mapping.to_impl(form),
  15411. multipart=mapping.to_impl(multipart),
  15412. timeout=timeout,
  15413. failOnStatusCode=fail_on_status_code,
  15414. ignoreHTTPSErrors=ignore_https_errors,
  15415. maxRedirects=max_redirects,
  15416. maxRetries=max_retries,
  15417. )
  15418. )
  15419. async def fetch(
  15420. self,
  15421. url_or_request: typing.Union[str, "Request"],
  15422. *,
  15423. params: typing.Optional[
  15424. typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
  15425. ] = None,
  15426. method: typing.Optional[str] = None,
  15427. headers: typing.Optional[typing.Dict[str, str]] = None,
  15428. data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
  15429. form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
  15430. multipart: typing.Optional[
  15431. typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
  15432. ] = None,
  15433. timeout: typing.Optional[float] = None,
  15434. fail_on_status_code: typing.Optional[bool] = None,
  15435. ignore_https_errors: typing.Optional[bool] = None,
  15436. max_redirects: typing.Optional[int] = None,
  15437. max_retries: typing.Optional[int] = None,
  15438. ) -> "APIResponse":
  15439. """APIRequestContext.fetch
  15440. Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
  15441. update context cookies from the response. The method will automatically follow redirects.
  15442. **Usage**
  15443. JSON objects can be passed directly to the request:
  15444. ```python
  15445. data = {
  15446. \"title\": \"Book Title\",
  15447. \"body\": \"John Doe\",
  15448. }
  15449. api_request_context.fetch(\"https://example.com/api/createBook\", method=\"post\", data=data)
  15450. ```
  15451. The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
  15452. encoding, by specifiying the `multipart` parameter:
  15453. Parameters
  15454. ----------
  15455. url_or_request : Union[Request, str]
  15456. Target URL or Request to get all parameters from.
  15457. params : Union[Dict[str, Union[bool, float, str]], str, None]
  15458. Query parameters to be sent with the URL.
  15459. method : Union[str, None]
  15460. If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or
  15461. [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.
  15462. headers : Union[Dict[str, str], None]
  15463. Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
  15464. it.
  15465. data : Union[Any, bytes, str, None]
  15466. Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  15467. and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
  15468. header will be set to `application/octet-stream` if not explicitly set.
  15469. form : Union[Dict[str, Union[bool, float, str]], None]
  15470. Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
  15471. as this request body. If this parameter is specified `content-type` header will be set to
  15472. `application/x-www-form-urlencoded` unless explicitly provided.
  15473. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
  15474. Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
  15475. request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
  15476. explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
  15477. timeout : Union[float, None]
  15478. Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  15479. fail_on_status_code : Union[bool, None]
  15480. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15481. codes.
  15482. ignore_https_errors : Union[bool, None]
  15483. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15484. max_redirects : Union[int, None]
  15485. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15486. exceeded. Defaults to `20`. Pass `0` to not follow redirects.
  15487. max_retries : Union[int, None]
  15488. Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
  15489. retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
  15490. Returns
  15491. -------
  15492. APIResponse
  15493. """
  15494. return mapping.from_impl(
  15495. await self._impl_obj.fetch(
  15496. urlOrRequest=url_or_request,
  15497. params=mapping.to_impl(params),
  15498. method=method,
  15499. headers=mapping.to_impl(headers),
  15500. data=mapping.to_impl(data),
  15501. form=mapping.to_impl(form),
  15502. multipart=mapping.to_impl(multipart),
  15503. timeout=timeout,
  15504. failOnStatusCode=fail_on_status_code,
  15505. ignoreHTTPSErrors=ignore_https_errors,
  15506. maxRedirects=max_redirects,
  15507. maxRetries=max_retries,
  15508. )
  15509. )
  15510. async def storage_state(
  15511. self,
  15512. *,
  15513. path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
  15514. indexed_db: typing.Optional[bool] = None,
  15515. ) -> StorageState:
  15516. """APIRequestContext.storage_state
  15517. Returns storage state for this request context, contains current cookies and local storage snapshot if it was
  15518. passed to the constructor.
  15519. Parameters
  15520. ----------
  15521. path : Union[pathlib.Path, str, None]
  15522. The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
  15523. working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
  15524. indexed_db : Union[bool, None]
  15525. Set to `true` to include IndexedDB in the storage state snapshot.
  15526. Returns
  15527. -------
  15528. {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}]}]}
  15529. """
  15530. return mapping.from_impl(
  15531. await self._impl_obj.storage_state(path=path, indexedDB=indexed_db)
  15532. )
  15533. mapping.register(APIRequestContextImpl, APIRequestContext)
  15534. class APIRequest(AsyncBase):
  15535. async def new_context(
  15536. self,
  15537. *,
  15538. base_url: typing.Optional[str] = None,
  15539. extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
  15540. http_credentials: typing.Optional[HttpCredentials] = None,
  15541. ignore_https_errors: typing.Optional[bool] = None,
  15542. proxy: typing.Optional[ProxySettings] = None,
  15543. user_agent: typing.Optional[str] = None,
  15544. timeout: typing.Optional[float] = None,
  15545. storage_state: typing.Optional[
  15546. typing.Union[StorageState, str, pathlib.Path]
  15547. ] = None,
  15548. client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
  15549. fail_on_status_code: typing.Optional[bool] = None,
  15550. max_redirects: typing.Optional[int] = None,
  15551. ) -> "APIRequestContext":
  15552. """APIRequest.new_context
  15553. Creates new instances of `APIRequestContext`.
  15554. Parameters
  15555. ----------
  15556. base_url : Union[str, None]
  15557. Methods like `a_pi_request_context.get()` take the base URL into consideration by using the
  15558. [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
  15559. Examples:
  15560. - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`
  15561. - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in
  15562. `http://localhost:3000/foo/bar.html`
  15563. - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
  15564. `http://localhost:3000/bar.html`
  15565. extra_http_headers : Union[Dict[str, str], None]
  15566. An object containing additional HTTP headers to be sent with every request. Defaults to none.
  15567. http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
  15568. Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
  15569. origin is specified, the username and password are sent to any servers upon unauthorized responses.
  15570. ignore_https_errors : Union[bool, None]
  15571. Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
  15572. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
  15573. Network proxy settings.
  15574. user_agent : Union[str, None]
  15575. Specific user agent to use in this context.
  15576. timeout : Union[float, None]
  15577. Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable
  15578. timeout.
  15579. 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]
  15580. Populates context with given storage state. This option can be used to initialize context with logged-in
  15581. information obtained via `browser_context.storage_state()` or `a_pi_request_context.storage_state()`.
  15582. Either a path to the file with saved storage, or the value returned by one of
  15583. `browser_context.storage_state()` or `a_pi_request_context.storage_state()` methods.
  15584. 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]
  15585. TLS Client Authentication allows the server to request a client certificate and verify it.
  15586. **Details**
  15587. An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
  15588. a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
  15589. `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
  15590. with an exact match to the request origin that the certificate is valid for.
  15591. Client certificate authentication is only active when at least one client certificate is provided. If you want to
  15592. reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
  15593. does not match any of the domains you plan to visit.
  15594. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
  15595. work by replacing `localhost` with `local.playwright`.
  15596. fail_on_status_code : Union[bool, None]
  15597. Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
  15598. codes.
  15599. max_redirects : Union[int, None]
  15600. Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
  15601. exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request
  15602. individually.
  15603. Returns
  15604. -------
  15605. APIRequestContext
  15606. """
  15607. return mapping.from_impl(
  15608. await self._impl_obj.new_context(
  15609. baseURL=base_url,
  15610. extraHTTPHeaders=mapping.to_impl(extra_http_headers),
  15611. httpCredentials=http_credentials,
  15612. ignoreHTTPSErrors=ignore_https_errors,
  15613. proxy=proxy,
  15614. userAgent=user_agent,
  15615. timeout=timeout,
  15616. storageState=storage_state,
  15617. clientCertificates=client_certificates,
  15618. failOnStatusCode=fail_on_status_code,
  15619. maxRedirects=max_redirects,
  15620. )
  15621. )
  15622. mapping.register(APIRequestImpl, APIRequest)
  15623. class PageAssertions(AsyncBase):
  15624. async def to_have_title(
  15625. self,
  15626. title_or_reg_exp: typing.Union[typing.Pattern[str], str],
  15627. *,
  15628. timeout: typing.Optional[float] = None,
  15629. ) -> None:
  15630. """PageAssertions.to_have_title
  15631. Ensures the page has the given title.
  15632. **Usage**
  15633. ```py
  15634. import re
  15635. from playwright.async_api import expect
  15636. # ...
  15637. await expect(page).to_have_title(re.compile(r\".*checkout\"))
  15638. ```
  15639. Parameters
  15640. ----------
  15641. title_or_reg_exp : Union[Pattern[str], str]
  15642. Expected title or RegExp.
  15643. timeout : Union[float, None]
  15644. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15645. """
  15646. __tracebackhide__ = True
  15647. return mapping.from_maybe_impl(
  15648. await self._impl_obj.to_have_title(
  15649. titleOrRegExp=title_or_reg_exp, timeout=timeout
  15650. )
  15651. )
  15652. async def not_to_have_title(
  15653. self,
  15654. title_or_reg_exp: typing.Union[typing.Pattern[str], str],
  15655. *,
  15656. timeout: typing.Optional[float] = None,
  15657. ) -> None:
  15658. """PageAssertions.not_to_have_title
  15659. The opposite of `page_assertions.to_have_title()`.
  15660. Parameters
  15661. ----------
  15662. title_or_reg_exp : Union[Pattern[str], str]
  15663. Expected title or RegExp.
  15664. timeout : Union[float, None]
  15665. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15666. """
  15667. __tracebackhide__ = True
  15668. return mapping.from_maybe_impl(
  15669. await self._impl_obj.not_to_have_title(
  15670. titleOrRegExp=title_or_reg_exp, timeout=timeout
  15671. )
  15672. )
  15673. async def to_have_url(
  15674. self,
  15675. url_or_reg_exp: typing.Union[str, typing.Pattern[str]],
  15676. *,
  15677. timeout: typing.Optional[float] = None,
  15678. ignore_case: typing.Optional[bool] = None,
  15679. ) -> None:
  15680. """PageAssertions.to_have_url
  15681. Ensures the page is navigated to the given URL.
  15682. **Usage**
  15683. ```py
  15684. import re
  15685. from playwright.async_api import expect
  15686. # ...
  15687. await expect(page).to_have_url(re.compile(\".*checkout\"))
  15688. ```
  15689. Parameters
  15690. ----------
  15691. url_or_reg_exp : Union[Pattern[str], str]
  15692. Expected URL string or RegExp.
  15693. timeout : Union[float, None]
  15694. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15695. ignore_case : Union[bool, None]
  15696. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15697. expression parameter if specified. A provided predicate ignores this flag.
  15698. """
  15699. __tracebackhide__ = True
  15700. return mapping.from_maybe_impl(
  15701. await self._impl_obj.to_have_url(
  15702. urlOrRegExp=url_or_reg_exp, timeout=timeout, ignoreCase=ignore_case
  15703. )
  15704. )
  15705. async def not_to_have_url(
  15706. self,
  15707. url_or_reg_exp: typing.Union[typing.Pattern[str], str],
  15708. *,
  15709. timeout: typing.Optional[float] = None,
  15710. ignore_case: typing.Optional[bool] = None,
  15711. ) -> None:
  15712. """PageAssertions.not_to_have_url
  15713. The opposite of `page_assertions.to_have_url()`.
  15714. Parameters
  15715. ----------
  15716. url_or_reg_exp : Union[Pattern[str], str]
  15717. Expected URL string or RegExp.
  15718. timeout : Union[float, None]
  15719. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15720. ignore_case : Union[bool, None]
  15721. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15722. expression flag if specified.
  15723. """
  15724. __tracebackhide__ = True
  15725. return mapping.from_maybe_impl(
  15726. await self._impl_obj.not_to_have_url(
  15727. urlOrRegExp=url_or_reg_exp, timeout=timeout, ignoreCase=ignore_case
  15728. )
  15729. )
  15730. mapping.register(PageAssertionsImpl, PageAssertions)
  15731. class LocatorAssertions(AsyncBase):
  15732. async def to_contain_text(
  15733. self,
  15734. expected: typing.Union[
  15735. typing.Sequence[str],
  15736. typing.Sequence[typing.Pattern[str]],
  15737. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  15738. typing.Pattern[str],
  15739. str,
  15740. ],
  15741. *,
  15742. use_inner_text: typing.Optional[bool] = None,
  15743. timeout: typing.Optional[float] = None,
  15744. ignore_case: typing.Optional[bool] = None,
  15745. ) -> None:
  15746. """LocatorAssertions.to_contain_text
  15747. Ensures the `Locator` points to an element that contains the given text. All nested elements will be considered
  15748. when computing the text content of the element. You can use regular expressions for the value as well.
  15749. **Details**
  15750. When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
  15751. text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
  15752. **Usage**
  15753. ```py
  15754. import re
  15755. from playwright.async_api import expect
  15756. locator = page.locator('.title')
  15757. await expect(locator).to_contain_text(\"substring\")
  15758. await expect(locator).to_contain_text(re.compile(r\"\\d messages\"))
  15759. ```
  15760. If you pass an array as an expected value, the expectations are:
  15761. 1. Locator resolves to a list of elements.
  15762. 1. Elements from a **subset** of this list contain text from the expected array, respectively.
  15763. 1. The matching subset of elements has the same order as the expected array.
  15764. 1. Each text value from the expected array is matched by some element from the list.
  15765. For example, consider the following list:
  15766. ```html
  15767. <ul>
  15768. <li>Item Text 1</li>
  15769. <li>Item Text 2</li>
  15770. <li>Item Text 3</li>
  15771. </ul>
  15772. ```
  15773. Let's see how we can use the assertion:
  15774. ```py
  15775. from playwright.async_api import expect
  15776. # ✓ Contains the right items in the right order
  15777. await expect(page.locator(\"ul > li\")).to_contain_text([\"Text 1\", \"Text 3\"])
  15778. # ✖ Wrong order
  15779. await expect(page.locator(\"ul > li\")).to_contain_text([\"Text 3\", \"Text 2\"])
  15780. # ✖ No item contains this text
  15781. await expect(page.locator(\"ul > li\")).to_contain_text([\"Some 33\"])
  15782. # ✖ Locator points to the outer list element, not to the list items
  15783. await expect(page.locator(\"ul\")).to_contain_text([\"Text 3\"])
  15784. ```
  15785. Parameters
  15786. ----------
  15787. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  15788. Expected substring or RegExp or a list of those.
  15789. use_inner_text : Union[bool, None]
  15790. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  15791. timeout : Union[float, None]
  15792. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15793. ignore_case : Union[bool, None]
  15794. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15795. expression flag if specified.
  15796. """
  15797. __tracebackhide__ = True
  15798. return mapping.from_maybe_impl(
  15799. await self._impl_obj.to_contain_text(
  15800. expected=mapping.to_impl(expected),
  15801. useInnerText=use_inner_text,
  15802. timeout=timeout,
  15803. ignoreCase=ignore_case,
  15804. )
  15805. )
  15806. async def not_to_contain_text(
  15807. self,
  15808. expected: typing.Union[
  15809. typing.Sequence[str],
  15810. typing.Sequence[typing.Pattern[str]],
  15811. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  15812. typing.Pattern[str],
  15813. str,
  15814. ],
  15815. *,
  15816. use_inner_text: typing.Optional[bool] = None,
  15817. timeout: typing.Optional[float] = None,
  15818. ignore_case: typing.Optional[bool] = None,
  15819. ) -> None:
  15820. """LocatorAssertions.not_to_contain_text
  15821. The opposite of `locator_assertions.to_contain_text()`.
  15822. Parameters
  15823. ----------
  15824. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  15825. Expected substring or RegExp or a list of those.
  15826. use_inner_text : Union[bool, None]
  15827. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  15828. timeout : Union[float, None]
  15829. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15830. ignore_case : Union[bool, None]
  15831. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15832. expression flag if specified.
  15833. """
  15834. __tracebackhide__ = True
  15835. return mapping.from_maybe_impl(
  15836. await self._impl_obj.not_to_contain_text(
  15837. expected=mapping.to_impl(expected),
  15838. useInnerText=use_inner_text,
  15839. timeout=timeout,
  15840. ignoreCase=ignore_case,
  15841. )
  15842. )
  15843. async def to_have_attribute(
  15844. self,
  15845. name: str,
  15846. value: typing.Union[str, typing.Pattern[str]],
  15847. *,
  15848. ignore_case: typing.Optional[bool] = None,
  15849. timeout: typing.Optional[float] = None,
  15850. ) -> None:
  15851. """LocatorAssertions.to_have_attribute
  15852. Ensures the `Locator` points to an element with given attribute.
  15853. **Usage**
  15854. ```py
  15855. from playwright.async_api import expect
  15856. locator = page.locator(\"input\")
  15857. await expect(locator).to_have_attribute(\"type\", \"text\")
  15858. ```
  15859. Parameters
  15860. ----------
  15861. name : str
  15862. Attribute name.
  15863. value : Union[Pattern[str], str]
  15864. Expected attribute value.
  15865. ignore_case : Union[bool, None]
  15866. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15867. expression flag if specified.
  15868. timeout : Union[float, None]
  15869. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15870. """
  15871. __tracebackhide__ = True
  15872. return mapping.from_maybe_impl(
  15873. await self._impl_obj.to_have_attribute(
  15874. name=name, value=value, ignoreCase=ignore_case, timeout=timeout
  15875. )
  15876. )
  15877. async def not_to_have_attribute(
  15878. self,
  15879. name: str,
  15880. value: typing.Union[str, typing.Pattern[str]],
  15881. *,
  15882. ignore_case: typing.Optional[bool] = None,
  15883. timeout: typing.Optional[float] = None,
  15884. ) -> None:
  15885. """LocatorAssertions.not_to_have_attribute
  15886. The opposite of `locator_assertions.to_have_attribute()`.
  15887. Parameters
  15888. ----------
  15889. name : str
  15890. Attribute name.
  15891. value : Union[Pattern[str], str]
  15892. Expected attribute value.
  15893. ignore_case : Union[bool, None]
  15894. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  15895. expression flag if specified.
  15896. timeout : Union[float, None]
  15897. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15898. """
  15899. __tracebackhide__ = True
  15900. return mapping.from_maybe_impl(
  15901. await self._impl_obj.not_to_have_attribute(
  15902. name=name, value=value, ignoreCase=ignore_case, timeout=timeout
  15903. )
  15904. )
  15905. async def to_have_class(
  15906. self,
  15907. expected: typing.Union[
  15908. typing.Sequence[str],
  15909. typing.Sequence[typing.Pattern[str]],
  15910. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  15911. typing.Pattern[str],
  15912. str,
  15913. ],
  15914. *,
  15915. timeout: typing.Optional[float] = None,
  15916. ) -> None:
  15917. """LocatorAssertions.to_have_class
  15918. Ensures the `Locator` points to an element with given CSS classes. When a string is provided, it must fully match
  15919. the element's `class` attribute. To match individual classes use `locator_assertions.to_contain_class()`.
  15920. **Usage**
  15921. ```html
  15922. <div class='middle selected row' id='component'></div>
  15923. ```
  15924. ```py
  15925. from playwright.async_api import expect
  15926. locator = page.locator(\"#component\")
  15927. await expect(locator).to_have_class(\"middle selected row\")
  15928. await expect(locator).to_have_class(re.compile(r\"(^|\\\\s)selected(\\\\s|$)\"))
  15929. ```
  15930. When an array is passed, the method asserts that the list of elements located matches the corresponding list of
  15931. expected class values. Each element's class attribute is matched against the corresponding string or regular
  15932. expression in the array:
  15933. ```py
  15934. from playwright.async_api import expect
  15935. locator = page.locator(\".list > .component\")
  15936. await expect(locator).to_have_class([\"component\", \"component selected\", \"component\"])
  15937. ```
  15938. Parameters
  15939. ----------
  15940. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  15941. Expected class or RegExp or a list of those.
  15942. timeout : Union[float, None]
  15943. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15944. """
  15945. __tracebackhide__ = True
  15946. return mapping.from_maybe_impl(
  15947. await self._impl_obj.to_have_class(
  15948. expected=mapping.to_impl(expected), timeout=timeout
  15949. )
  15950. )
  15951. async def not_to_have_class(
  15952. self,
  15953. expected: typing.Union[
  15954. typing.Sequence[str],
  15955. typing.Sequence[typing.Pattern[str]],
  15956. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  15957. typing.Pattern[str],
  15958. str,
  15959. ],
  15960. *,
  15961. timeout: typing.Optional[float] = None,
  15962. ) -> None:
  15963. """LocatorAssertions.not_to_have_class
  15964. The opposite of `locator_assertions.to_have_class()`.
  15965. Parameters
  15966. ----------
  15967. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  15968. Expected class or RegExp or a list of those.
  15969. timeout : Union[float, None]
  15970. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  15971. """
  15972. __tracebackhide__ = True
  15973. return mapping.from_maybe_impl(
  15974. await self._impl_obj.not_to_have_class(
  15975. expected=mapping.to_impl(expected), timeout=timeout
  15976. )
  15977. )
  15978. async def to_contain_class(
  15979. self,
  15980. expected: typing.Union[typing.Sequence[str], str],
  15981. *,
  15982. timeout: typing.Optional[float] = None,
  15983. ) -> None:
  15984. """LocatorAssertions.to_contain_class
  15985. Ensures the `Locator` points to an element with given CSS classes. All classes from the asserted value, separated
  15986. by spaces, must be present in the
  15987. [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) in any order.
  15988. **Usage**
  15989. ```html
  15990. <div class='middle selected row' id='component'></div>
  15991. ```
  15992. ```py
  15993. from playwright.async_api import expect
  15994. locator = page.locator(\"#component\")
  15995. await expect(locator).to_contain_class(\"middle selected row\")
  15996. await expect(locator).to_contain_class(\"selected\")
  15997. await expect(locator).to_contain_class(\"row middle\")
  15998. ```
  15999. When an array is passed, the method asserts that the list of elements located matches the corresponding list of
  16000. expected class lists. Each element's class attribute is matched against the corresponding class in the array:
  16001. ```html
  16002. <div class='list'>
  16003. <div class='component inactive'></div>
  16004. <div class='component active'></div>
  16005. <div class='component inactive'></div>
  16006. </div>
  16007. ```
  16008. ```py
  16009. from playwright.async_api import expect
  16010. locator = page.locator(\".list > .component\")
  16011. await expect(locator).to_contain_class([\"inactive\", \"active\", \"inactive\"])
  16012. ```
  16013. Parameters
  16014. ----------
  16015. expected : Union[Sequence[str], str]
  16016. A string containing expected class names, separated by spaces, or a list of such strings to assert multiple
  16017. elements.
  16018. timeout : Union[float, None]
  16019. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16020. """
  16021. __tracebackhide__ = True
  16022. return mapping.from_maybe_impl(
  16023. await self._impl_obj.to_contain_class(
  16024. expected=mapping.to_impl(expected), timeout=timeout
  16025. )
  16026. )
  16027. async def not_to_contain_class(
  16028. self,
  16029. expected: typing.Union[typing.Sequence[str], str],
  16030. *,
  16031. timeout: typing.Optional[float] = None,
  16032. ) -> None:
  16033. """LocatorAssertions.not_to_contain_class
  16034. The opposite of `locator_assertions.to_contain_class()`.
  16035. Parameters
  16036. ----------
  16037. expected : Union[Sequence[str], str]
  16038. Expected class or RegExp or a list of those.
  16039. timeout : Union[float, None]
  16040. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16041. """
  16042. __tracebackhide__ = True
  16043. return mapping.from_maybe_impl(
  16044. await self._impl_obj.not_to_contain_class(
  16045. expected=mapping.to_impl(expected), timeout=timeout
  16046. )
  16047. )
  16048. async def to_have_count(
  16049. self, count: int, *, timeout: typing.Optional[float] = None
  16050. ) -> None:
  16051. """LocatorAssertions.to_have_count
  16052. Ensures the `Locator` resolves to an exact number of DOM nodes.
  16053. **Usage**
  16054. ```py
  16055. from playwright.async_api import expect
  16056. locator = page.locator(\"list > .component\")
  16057. await expect(locator).to_have_count(3)
  16058. ```
  16059. Parameters
  16060. ----------
  16061. count : int
  16062. Expected count.
  16063. timeout : Union[float, None]
  16064. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16065. """
  16066. __tracebackhide__ = True
  16067. return mapping.from_maybe_impl(
  16068. await self._impl_obj.to_have_count(count=count, timeout=timeout)
  16069. )
  16070. async def not_to_have_count(
  16071. self, count: int, *, timeout: typing.Optional[float] = None
  16072. ) -> None:
  16073. """LocatorAssertions.not_to_have_count
  16074. The opposite of `locator_assertions.to_have_count()`.
  16075. Parameters
  16076. ----------
  16077. count : int
  16078. Expected count.
  16079. timeout : Union[float, None]
  16080. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16081. """
  16082. __tracebackhide__ = True
  16083. return mapping.from_maybe_impl(
  16084. await self._impl_obj.not_to_have_count(count=count, timeout=timeout)
  16085. )
  16086. async def to_have_css(
  16087. self,
  16088. name: str,
  16089. value: typing.Union[str, typing.Pattern[str]],
  16090. *,
  16091. timeout: typing.Optional[float] = None,
  16092. ) -> None:
  16093. """LocatorAssertions.to_have_css
  16094. Ensures the `Locator` resolves to an element with the given computed CSS style.
  16095. **Usage**
  16096. ```py
  16097. from playwright.async_api import expect
  16098. locator = page.get_by_role(\"button\")
  16099. await expect(locator).to_have_css(\"display\", \"flex\")
  16100. ```
  16101. Parameters
  16102. ----------
  16103. name : str
  16104. CSS property name.
  16105. value : Union[Pattern[str], str]
  16106. CSS property value.
  16107. timeout : Union[float, None]
  16108. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16109. """
  16110. __tracebackhide__ = True
  16111. return mapping.from_maybe_impl(
  16112. await self._impl_obj.to_have_css(name=name, value=value, timeout=timeout)
  16113. )
  16114. async def not_to_have_css(
  16115. self,
  16116. name: str,
  16117. value: typing.Union[str, typing.Pattern[str]],
  16118. *,
  16119. timeout: typing.Optional[float] = None,
  16120. ) -> None:
  16121. """LocatorAssertions.not_to_have_css
  16122. The opposite of `locator_assertions.to_have_css()`.
  16123. Parameters
  16124. ----------
  16125. name : str
  16126. CSS property name.
  16127. value : Union[Pattern[str], str]
  16128. CSS property value.
  16129. timeout : Union[float, None]
  16130. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16131. """
  16132. __tracebackhide__ = True
  16133. return mapping.from_maybe_impl(
  16134. await self._impl_obj.not_to_have_css(
  16135. name=name, value=value, timeout=timeout
  16136. )
  16137. )
  16138. async def to_have_id(
  16139. self,
  16140. id: typing.Union[str, typing.Pattern[str]],
  16141. *,
  16142. timeout: typing.Optional[float] = None,
  16143. ) -> None:
  16144. """LocatorAssertions.to_have_id
  16145. Ensures the `Locator` points to an element with the given DOM Node ID.
  16146. **Usage**
  16147. ```py
  16148. from playwright.async_api import expect
  16149. locator = page.get_by_role(\"textbox\")
  16150. await expect(locator).to_have_id(\"lastname\")
  16151. ```
  16152. Parameters
  16153. ----------
  16154. id : Union[Pattern[str], str]
  16155. Element id.
  16156. timeout : Union[float, None]
  16157. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16158. """
  16159. __tracebackhide__ = True
  16160. return mapping.from_maybe_impl(
  16161. await self._impl_obj.to_have_id(id=id, timeout=timeout)
  16162. )
  16163. async def not_to_have_id(
  16164. self,
  16165. id: typing.Union[str, typing.Pattern[str]],
  16166. *,
  16167. timeout: typing.Optional[float] = None,
  16168. ) -> None:
  16169. """LocatorAssertions.not_to_have_id
  16170. The opposite of `locator_assertions.to_have_id()`.
  16171. Parameters
  16172. ----------
  16173. id : Union[Pattern[str], str]
  16174. Element id.
  16175. timeout : Union[float, None]
  16176. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16177. """
  16178. __tracebackhide__ = True
  16179. return mapping.from_maybe_impl(
  16180. await self._impl_obj.not_to_have_id(id=id, timeout=timeout)
  16181. )
  16182. async def to_have_js_property(
  16183. self, name: str, value: typing.Any, *, timeout: typing.Optional[float] = None
  16184. ) -> None:
  16185. """LocatorAssertions.to_have_js_property
  16186. Ensures the `Locator` points to an element with given JavaScript property. Note that this property can be of a
  16187. primitive type as well as a plain serializable JavaScript object.
  16188. **Usage**
  16189. ```py
  16190. from playwright.async_api import expect
  16191. locator = page.locator(\".component\")
  16192. await expect(locator).to_have_js_property(\"loaded\", True)
  16193. ```
  16194. Parameters
  16195. ----------
  16196. name : str
  16197. Property name.
  16198. value : Any
  16199. Property value.
  16200. timeout : Union[float, None]
  16201. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16202. """
  16203. __tracebackhide__ = True
  16204. return mapping.from_maybe_impl(
  16205. await self._impl_obj.to_have_js_property(
  16206. name=name, value=mapping.to_impl(value), timeout=timeout
  16207. )
  16208. )
  16209. async def not_to_have_js_property(
  16210. self, name: str, value: typing.Any, *, timeout: typing.Optional[float] = None
  16211. ) -> None:
  16212. """LocatorAssertions.not_to_have_js_property
  16213. The opposite of `locator_assertions.to_have_js_property()`.
  16214. Parameters
  16215. ----------
  16216. name : str
  16217. Property name.
  16218. value : Any
  16219. Property value.
  16220. timeout : Union[float, None]
  16221. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16222. """
  16223. __tracebackhide__ = True
  16224. return mapping.from_maybe_impl(
  16225. await self._impl_obj.not_to_have_js_property(
  16226. name=name, value=mapping.to_impl(value), timeout=timeout
  16227. )
  16228. )
  16229. async def to_have_value(
  16230. self,
  16231. value: typing.Union[str, typing.Pattern[str]],
  16232. *,
  16233. timeout: typing.Optional[float] = None,
  16234. ) -> None:
  16235. """LocatorAssertions.to_have_value
  16236. Ensures the `Locator` points to an element with the given input value. You can use regular expressions for the
  16237. value as well.
  16238. **Usage**
  16239. ```py
  16240. import re
  16241. from playwright.async_api import expect
  16242. locator = page.locator(\"input[type=number]\")
  16243. await expect(locator).to_have_value(re.compile(r\"[0-9]\"))
  16244. ```
  16245. Parameters
  16246. ----------
  16247. value : Union[Pattern[str], str]
  16248. Expected value.
  16249. timeout : Union[float, None]
  16250. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16251. """
  16252. __tracebackhide__ = True
  16253. return mapping.from_maybe_impl(
  16254. await self._impl_obj.to_have_value(value=value, timeout=timeout)
  16255. )
  16256. async def not_to_have_value(
  16257. self,
  16258. value: typing.Union[str, typing.Pattern[str]],
  16259. *,
  16260. timeout: typing.Optional[float] = None,
  16261. ) -> None:
  16262. """LocatorAssertions.not_to_have_value
  16263. The opposite of `locator_assertions.to_have_value()`.
  16264. Parameters
  16265. ----------
  16266. value : Union[Pattern[str], str]
  16267. Expected value.
  16268. timeout : Union[float, None]
  16269. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16270. """
  16271. __tracebackhide__ = True
  16272. return mapping.from_maybe_impl(
  16273. await self._impl_obj.not_to_have_value(value=value, timeout=timeout)
  16274. )
  16275. async def to_have_values(
  16276. self,
  16277. values: typing.Union[
  16278. typing.Sequence[str],
  16279. typing.Sequence[typing.Pattern[str]],
  16280. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16281. ],
  16282. *,
  16283. timeout: typing.Optional[float] = None,
  16284. ) -> None:
  16285. """LocatorAssertions.to_have_values
  16286. Ensures the `Locator` points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the
  16287. specified values are selected.
  16288. **Usage**
  16289. For example, given the following element:
  16290. ```html
  16291. <select id=\"favorite-colors\" multiple>
  16292. <option value=\"R\">Red</option>
  16293. <option value=\"G\">Green</option>
  16294. <option value=\"B\">Blue</option>
  16295. </select>
  16296. ```
  16297. ```py
  16298. import re
  16299. from playwright.async_api import expect
  16300. locator = page.locator(\"id=favorite-colors\")
  16301. await locator.select_option([\"R\", \"G\"])
  16302. await expect(locator).to_have_values([re.compile(r\"R\"), re.compile(r\"G\")])
  16303. ```
  16304. Parameters
  16305. ----------
  16306. values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
  16307. Expected options currently selected.
  16308. timeout : Union[float, None]
  16309. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16310. """
  16311. __tracebackhide__ = True
  16312. return mapping.from_maybe_impl(
  16313. await self._impl_obj.to_have_values(
  16314. values=mapping.to_impl(values), timeout=timeout
  16315. )
  16316. )
  16317. async def not_to_have_values(
  16318. self,
  16319. values: typing.Union[
  16320. typing.Sequence[str],
  16321. typing.Sequence[typing.Pattern[str]],
  16322. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16323. ],
  16324. *,
  16325. timeout: typing.Optional[float] = None,
  16326. ) -> None:
  16327. """LocatorAssertions.not_to_have_values
  16328. The opposite of `locator_assertions.to_have_values()`.
  16329. Parameters
  16330. ----------
  16331. values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
  16332. Expected options currently selected.
  16333. timeout : Union[float, None]
  16334. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16335. """
  16336. __tracebackhide__ = True
  16337. return mapping.from_maybe_impl(
  16338. await self._impl_obj.not_to_have_values(
  16339. values=mapping.to_impl(values), timeout=timeout
  16340. )
  16341. )
  16342. async def to_have_text(
  16343. self,
  16344. expected: typing.Union[
  16345. typing.Sequence[str],
  16346. typing.Sequence[typing.Pattern[str]],
  16347. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16348. typing.Pattern[str],
  16349. str,
  16350. ],
  16351. *,
  16352. use_inner_text: typing.Optional[bool] = None,
  16353. timeout: typing.Optional[float] = None,
  16354. ignore_case: typing.Optional[bool] = None,
  16355. ) -> None:
  16356. """LocatorAssertions.to_have_text
  16357. Ensures the `Locator` points to an element with the given text. All nested elements will be considered when
  16358. computing the text content of the element. You can use regular expressions for the value as well.
  16359. **Details**
  16360. When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
  16361. text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
  16362. **Usage**
  16363. ```py
  16364. import re
  16365. from playwright.async_api import expect
  16366. locator = page.locator(\".title\")
  16367. await expect(locator).to_have_text(re.compile(r\"Welcome, Test User\"))
  16368. await expect(locator).to_have_text(re.compile(r\"Welcome, .*\"))
  16369. ```
  16370. If you pass an array as an expected value, the expectations are:
  16371. 1. Locator resolves to a list of elements.
  16372. 1. The number of elements equals the number of expected values in the array.
  16373. 1. Elements from the list have text matching expected array values, one by one, in order.
  16374. For example, consider the following list:
  16375. ```html
  16376. <ul>
  16377. <li>Text 1</li>
  16378. <li>Text 2</li>
  16379. <li>Text 3</li>
  16380. </ul>
  16381. ```
  16382. Let's see how we can use the assertion:
  16383. ```py
  16384. from playwright.async_api import expect
  16385. # ✓ Has the right items in the right order
  16386. await expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
  16387. # ✖ Wrong order
  16388. await expect(page.locator(\"ul > li\")).to_have_text([\"Text 3\", \"Text 2\", \"Text 1\"])
  16389. # ✖ Last item does not match
  16390. await expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text\"])
  16391. # ✖ Locator points to the outer list element, not to the list items
  16392. await expect(page.locator(\"ul\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
  16393. ```
  16394. Parameters
  16395. ----------
  16396. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  16397. Expected string or RegExp or a list of those.
  16398. use_inner_text : Union[bool, None]
  16399. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  16400. timeout : Union[float, None]
  16401. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16402. ignore_case : Union[bool, None]
  16403. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16404. expression flag if specified.
  16405. """
  16406. __tracebackhide__ = True
  16407. return mapping.from_maybe_impl(
  16408. await self._impl_obj.to_have_text(
  16409. expected=mapping.to_impl(expected),
  16410. useInnerText=use_inner_text,
  16411. timeout=timeout,
  16412. ignoreCase=ignore_case,
  16413. )
  16414. )
  16415. async def not_to_have_text(
  16416. self,
  16417. expected: typing.Union[
  16418. typing.Sequence[str],
  16419. typing.Sequence[typing.Pattern[str]],
  16420. typing.Sequence[typing.Union[typing.Pattern[str], str]],
  16421. typing.Pattern[str],
  16422. str,
  16423. ],
  16424. *,
  16425. use_inner_text: typing.Optional[bool] = None,
  16426. timeout: typing.Optional[float] = None,
  16427. ignore_case: typing.Optional[bool] = None,
  16428. ) -> None:
  16429. """LocatorAssertions.not_to_have_text
  16430. The opposite of `locator_assertions.to_have_text()`.
  16431. Parameters
  16432. ----------
  16433. expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
  16434. Expected string or RegExp or a list of those.
  16435. use_inner_text : Union[bool, None]
  16436. Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
  16437. timeout : Union[float, None]
  16438. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16439. ignore_case : Union[bool, None]
  16440. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16441. expression flag if specified.
  16442. """
  16443. __tracebackhide__ = True
  16444. return mapping.from_maybe_impl(
  16445. await self._impl_obj.not_to_have_text(
  16446. expected=mapping.to_impl(expected),
  16447. useInnerText=use_inner_text,
  16448. timeout=timeout,
  16449. ignoreCase=ignore_case,
  16450. )
  16451. )
  16452. async def to_be_attached(
  16453. self,
  16454. *,
  16455. attached: typing.Optional[bool] = None,
  16456. timeout: typing.Optional[float] = None,
  16457. ) -> None:
  16458. """LocatorAssertions.to_be_attached
  16459. Ensures that `Locator` points to an element that is
  16460. [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
  16461. **Usage**
  16462. ```py
  16463. await expect(page.get_by_text(\"Hidden text\")).to_be_attached()
  16464. ```
  16465. Parameters
  16466. ----------
  16467. attached : Union[bool, None]
  16468. timeout : Union[float, None]
  16469. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16470. """
  16471. __tracebackhide__ = True
  16472. return mapping.from_maybe_impl(
  16473. await self._impl_obj.to_be_attached(attached=attached, timeout=timeout)
  16474. )
  16475. async def to_be_checked(
  16476. self,
  16477. *,
  16478. timeout: typing.Optional[float] = None,
  16479. checked: typing.Optional[bool] = None,
  16480. indeterminate: typing.Optional[bool] = None,
  16481. ) -> None:
  16482. """LocatorAssertions.to_be_checked
  16483. Ensures the `Locator` points to a checked input.
  16484. **Usage**
  16485. ```py
  16486. from playwright.async_api import expect
  16487. locator = page.get_by_label(\"Subscribe to newsletter\")
  16488. await expect(locator).to_be_checked()
  16489. ```
  16490. Parameters
  16491. ----------
  16492. timeout : Union[float, None]
  16493. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16494. checked : Union[bool, None]
  16495. Provides state to assert for. Asserts for input to be checked by default. This option can't be used when
  16496. `indeterminate` is set to true.
  16497. indeterminate : Union[bool, None]
  16498. Asserts that the element is in the indeterminate (mixed) state. Only supported for checkboxes and radio buttons.
  16499. This option can't be true when `checked` is provided.
  16500. """
  16501. __tracebackhide__ = True
  16502. return mapping.from_maybe_impl(
  16503. await self._impl_obj.to_be_checked(
  16504. timeout=timeout, checked=checked, indeterminate=indeterminate
  16505. )
  16506. )
  16507. async def not_to_be_attached(
  16508. self,
  16509. *,
  16510. attached: typing.Optional[bool] = None,
  16511. timeout: typing.Optional[float] = None,
  16512. ) -> None:
  16513. """LocatorAssertions.not_to_be_attached
  16514. The opposite of `locator_assertions.to_be_attached()`.
  16515. Parameters
  16516. ----------
  16517. attached : Union[bool, None]
  16518. timeout : Union[float, None]
  16519. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16520. """
  16521. __tracebackhide__ = True
  16522. return mapping.from_maybe_impl(
  16523. await self._impl_obj.not_to_be_attached(attached=attached, timeout=timeout)
  16524. )
  16525. async def not_to_be_checked(
  16526. self, *, timeout: typing.Optional[float] = None
  16527. ) -> None:
  16528. """LocatorAssertions.not_to_be_checked
  16529. The opposite of `locator_assertions.to_be_checked()`.
  16530. Parameters
  16531. ----------
  16532. timeout : Union[float, None]
  16533. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16534. """
  16535. __tracebackhide__ = True
  16536. return mapping.from_maybe_impl(
  16537. await self._impl_obj.not_to_be_checked(timeout=timeout)
  16538. )
  16539. async def to_be_disabled(self, *, timeout: typing.Optional[float] = None) -> None:
  16540. """LocatorAssertions.to_be_disabled
  16541. Ensures the `Locator` points to a disabled element. Element is disabled if it has \"disabled\" attribute or is
  16542. disabled via
  16543. ['aria-disabled'](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled). Note
  16544. that only native control elements such as HTML `button`, `input`, `select`, `textarea`, `option`, `optgroup` can be
  16545. disabled by setting \"disabled\" attribute. \"disabled\" attribute on other elements is ignored by the browser.
  16546. **Usage**
  16547. ```py
  16548. from playwright.async_api import expect
  16549. locator = page.locator(\"button.submit\")
  16550. await expect(locator).to_be_disabled()
  16551. ```
  16552. Parameters
  16553. ----------
  16554. timeout : Union[float, None]
  16555. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16556. """
  16557. __tracebackhide__ = True
  16558. return mapping.from_maybe_impl(
  16559. await self._impl_obj.to_be_disabled(timeout=timeout)
  16560. )
  16561. async def not_to_be_disabled(
  16562. self, *, timeout: typing.Optional[float] = None
  16563. ) -> None:
  16564. """LocatorAssertions.not_to_be_disabled
  16565. The opposite of `locator_assertions.to_be_disabled()`.
  16566. Parameters
  16567. ----------
  16568. timeout : Union[float, None]
  16569. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16570. """
  16571. __tracebackhide__ = True
  16572. return mapping.from_maybe_impl(
  16573. await self._impl_obj.not_to_be_disabled(timeout=timeout)
  16574. )
  16575. async def to_be_editable(
  16576. self,
  16577. *,
  16578. editable: typing.Optional[bool] = None,
  16579. timeout: typing.Optional[float] = None,
  16580. ) -> None:
  16581. """LocatorAssertions.to_be_editable
  16582. Ensures the `Locator` points to an editable element.
  16583. **Usage**
  16584. ```py
  16585. from playwright.async_api import expect
  16586. locator = page.get_by_role(\"textbox\")
  16587. await expect(locator).to_be_editable()
  16588. ```
  16589. Parameters
  16590. ----------
  16591. editable : Union[bool, None]
  16592. timeout : Union[float, None]
  16593. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16594. """
  16595. __tracebackhide__ = True
  16596. return mapping.from_maybe_impl(
  16597. await self._impl_obj.to_be_editable(editable=editable, timeout=timeout)
  16598. )
  16599. async def not_to_be_editable(
  16600. self,
  16601. *,
  16602. editable: typing.Optional[bool] = None,
  16603. timeout: typing.Optional[float] = None,
  16604. ) -> None:
  16605. """LocatorAssertions.not_to_be_editable
  16606. The opposite of `locator_assertions.to_be_editable()`.
  16607. Parameters
  16608. ----------
  16609. editable : Union[bool, None]
  16610. timeout : Union[float, None]
  16611. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16612. """
  16613. __tracebackhide__ = True
  16614. return mapping.from_maybe_impl(
  16615. await self._impl_obj.not_to_be_editable(editable=editable, timeout=timeout)
  16616. )
  16617. async def to_be_empty(self, *, timeout: typing.Optional[float] = None) -> None:
  16618. """LocatorAssertions.to_be_empty
  16619. Ensures the `Locator` points to an empty editable element or to a DOM node that has no text.
  16620. **Usage**
  16621. ```py
  16622. from playwright.async_api import expect
  16623. locator = page.locator(\"div.warning\")
  16624. await expect(locator).to_be_empty()
  16625. ```
  16626. Parameters
  16627. ----------
  16628. timeout : Union[float, None]
  16629. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16630. """
  16631. __tracebackhide__ = True
  16632. return mapping.from_maybe_impl(
  16633. await self._impl_obj.to_be_empty(timeout=timeout)
  16634. )
  16635. async def not_to_be_empty(self, *, timeout: typing.Optional[float] = None) -> None:
  16636. """LocatorAssertions.not_to_be_empty
  16637. The opposite of `locator_assertions.to_be_empty()`.
  16638. Parameters
  16639. ----------
  16640. timeout : Union[float, None]
  16641. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16642. """
  16643. __tracebackhide__ = True
  16644. return mapping.from_maybe_impl(
  16645. await self._impl_obj.not_to_be_empty(timeout=timeout)
  16646. )
  16647. async def to_be_enabled(
  16648. self,
  16649. *,
  16650. enabled: typing.Optional[bool] = None,
  16651. timeout: typing.Optional[float] = None,
  16652. ) -> None:
  16653. """LocatorAssertions.to_be_enabled
  16654. Ensures the `Locator` points to an enabled element.
  16655. **Usage**
  16656. ```py
  16657. from playwright.async_api import expect
  16658. locator = page.locator(\"button.submit\")
  16659. await expect(locator).to_be_enabled()
  16660. ```
  16661. Parameters
  16662. ----------
  16663. enabled : Union[bool, None]
  16664. timeout : Union[float, None]
  16665. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16666. """
  16667. __tracebackhide__ = True
  16668. return mapping.from_maybe_impl(
  16669. await self._impl_obj.to_be_enabled(enabled=enabled, timeout=timeout)
  16670. )
  16671. async def not_to_be_enabled(
  16672. self,
  16673. *,
  16674. enabled: typing.Optional[bool] = None,
  16675. timeout: typing.Optional[float] = None,
  16676. ) -> None:
  16677. """LocatorAssertions.not_to_be_enabled
  16678. The opposite of `locator_assertions.to_be_enabled()`.
  16679. Parameters
  16680. ----------
  16681. enabled : Union[bool, None]
  16682. timeout : Union[float, None]
  16683. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16684. """
  16685. __tracebackhide__ = True
  16686. return mapping.from_maybe_impl(
  16687. await self._impl_obj.not_to_be_enabled(enabled=enabled, timeout=timeout)
  16688. )
  16689. async def to_be_hidden(self, *, timeout: typing.Optional[float] = None) -> None:
  16690. """LocatorAssertions.to_be_hidden
  16691. Ensures that `Locator` either does not resolve to any DOM node, or resolves to a
  16692. [non-visible](https://playwright.dev/python/docs/actionability#visible) one.
  16693. **Usage**
  16694. ```py
  16695. from playwright.async_api import expect
  16696. locator = page.locator('.my-element')
  16697. await expect(locator).to_be_hidden()
  16698. ```
  16699. Parameters
  16700. ----------
  16701. timeout : Union[float, None]
  16702. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16703. """
  16704. __tracebackhide__ = True
  16705. return mapping.from_maybe_impl(
  16706. await self._impl_obj.to_be_hidden(timeout=timeout)
  16707. )
  16708. async def not_to_be_hidden(self, *, timeout: typing.Optional[float] = None) -> None:
  16709. """LocatorAssertions.not_to_be_hidden
  16710. The opposite of `locator_assertions.to_be_hidden()`.
  16711. Parameters
  16712. ----------
  16713. timeout : Union[float, None]
  16714. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16715. """
  16716. __tracebackhide__ = True
  16717. return mapping.from_maybe_impl(
  16718. await self._impl_obj.not_to_be_hidden(timeout=timeout)
  16719. )
  16720. async def to_be_visible(
  16721. self,
  16722. *,
  16723. visible: typing.Optional[bool] = None,
  16724. timeout: typing.Optional[float] = None,
  16725. ) -> None:
  16726. """LocatorAssertions.to_be_visible
  16727. Ensures that `Locator` points to an attached and [visible](https://playwright.dev/python/docs/actionability#visible) DOM node.
  16728. To check that at least one element from the list is visible, use `locator.first()`.
  16729. **Usage**
  16730. ```py
  16731. # A specific element is visible.
  16732. await expect(page.get_by_text(\"Welcome\")).to_be_visible()
  16733. # At least one item in the list is visible.
  16734. await expect(page.get_by_test_id(\"todo-item\").first).to_be_visible()
  16735. # At least one of the two elements is visible, possibly both.
  16736. await expect(
  16737. page.get_by_role(\"button\", name=\"Sign in\")
  16738. .or_(page.get_by_role(\"button\", name=\"Sign up\"))
  16739. .first
  16740. ).to_be_visible()
  16741. ```
  16742. Parameters
  16743. ----------
  16744. visible : Union[bool, None]
  16745. timeout : Union[float, None]
  16746. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16747. """
  16748. __tracebackhide__ = True
  16749. return mapping.from_maybe_impl(
  16750. await self._impl_obj.to_be_visible(visible=visible, timeout=timeout)
  16751. )
  16752. async def not_to_be_visible(
  16753. self,
  16754. *,
  16755. visible: typing.Optional[bool] = None,
  16756. timeout: typing.Optional[float] = None,
  16757. ) -> None:
  16758. """LocatorAssertions.not_to_be_visible
  16759. The opposite of `locator_assertions.to_be_visible()`.
  16760. Parameters
  16761. ----------
  16762. visible : Union[bool, None]
  16763. timeout : Union[float, None]
  16764. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16765. """
  16766. __tracebackhide__ = True
  16767. return mapping.from_maybe_impl(
  16768. await self._impl_obj.not_to_be_visible(visible=visible, timeout=timeout)
  16769. )
  16770. async def to_be_focused(self, *, timeout: typing.Optional[float] = None) -> None:
  16771. """LocatorAssertions.to_be_focused
  16772. Ensures the `Locator` points to a focused DOM node.
  16773. **Usage**
  16774. ```py
  16775. from playwright.async_api import expect
  16776. locator = page.get_by_role(\"textbox\")
  16777. await expect(locator).to_be_focused()
  16778. ```
  16779. Parameters
  16780. ----------
  16781. timeout : Union[float, None]
  16782. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16783. """
  16784. __tracebackhide__ = True
  16785. return mapping.from_maybe_impl(
  16786. await self._impl_obj.to_be_focused(timeout=timeout)
  16787. )
  16788. async def not_to_be_focused(
  16789. self, *, timeout: typing.Optional[float] = None
  16790. ) -> None:
  16791. """LocatorAssertions.not_to_be_focused
  16792. The opposite of `locator_assertions.to_be_focused()`.
  16793. Parameters
  16794. ----------
  16795. timeout : Union[float, None]
  16796. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16797. """
  16798. __tracebackhide__ = True
  16799. return mapping.from_maybe_impl(
  16800. await self._impl_obj.not_to_be_focused(timeout=timeout)
  16801. )
  16802. async def to_be_in_viewport(
  16803. self,
  16804. *,
  16805. ratio: typing.Optional[float] = None,
  16806. timeout: typing.Optional[float] = None,
  16807. ) -> None:
  16808. """LocatorAssertions.to_be_in_viewport
  16809. Ensures the `Locator` points to an element that intersects viewport, according to the
  16810. [intersection observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
  16811. **Usage**
  16812. ```py
  16813. from playwright.async_api import expect
  16814. locator = page.get_by_role(\"button\")
  16815. # Make sure at least some part of element intersects viewport.
  16816. await expect(locator).to_be_in_viewport()
  16817. # Make sure element is fully outside of viewport.
  16818. await expect(locator).not_to_be_in_viewport()
  16819. # Make sure that at least half of the element intersects viewport.
  16820. await expect(locator).to_be_in_viewport(ratio=0.5)
  16821. ```
  16822. Parameters
  16823. ----------
  16824. ratio : Union[float, None]
  16825. The minimal ratio of the element to intersect viewport. If equals to `0`, then element should intersect viewport at
  16826. any positive ratio. Defaults to `0`.
  16827. timeout : Union[float, None]
  16828. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16829. """
  16830. __tracebackhide__ = True
  16831. return mapping.from_maybe_impl(
  16832. await self._impl_obj.to_be_in_viewport(ratio=ratio, timeout=timeout)
  16833. )
  16834. async def not_to_be_in_viewport(
  16835. self,
  16836. *,
  16837. ratio: typing.Optional[float] = None,
  16838. timeout: typing.Optional[float] = None,
  16839. ) -> None:
  16840. """LocatorAssertions.not_to_be_in_viewport
  16841. The opposite of `locator_assertions.to_be_in_viewport()`.
  16842. Parameters
  16843. ----------
  16844. ratio : Union[float, None]
  16845. timeout : Union[float, None]
  16846. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16847. """
  16848. __tracebackhide__ = True
  16849. return mapping.from_maybe_impl(
  16850. await self._impl_obj.not_to_be_in_viewport(ratio=ratio, timeout=timeout)
  16851. )
  16852. async def to_have_accessible_description(
  16853. self,
  16854. description: typing.Union[str, typing.Pattern[str]],
  16855. *,
  16856. ignore_case: typing.Optional[bool] = None,
  16857. timeout: typing.Optional[float] = None,
  16858. ) -> None:
  16859. """LocatorAssertions.to_have_accessible_description
  16860. Ensures the `Locator` points to an element with a given
  16861. [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
  16862. **Usage**
  16863. ```py
  16864. locator = page.get_by_test_id(\"save-button\")
  16865. await expect(locator).to_have_accessible_description(\"Save results to disk\")
  16866. ```
  16867. Parameters
  16868. ----------
  16869. description : Union[Pattern[str], str]
  16870. Expected accessible description.
  16871. ignore_case : Union[bool, None]
  16872. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16873. expression flag if specified.
  16874. timeout : Union[float, None]
  16875. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16876. """
  16877. __tracebackhide__ = True
  16878. return mapping.from_maybe_impl(
  16879. await self._impl_obj.to_have_accessible_description(
  16880. description=description, ignoreCase=ignore_case, timeout=timeout
  16881. )
  16882. )
  16883. async def not_to_have_accessible_description(
  16884. self,
  16885. name: typing.Union[str, typing.Pattern[str]],
  16886. *,
  16887. ignore_case: typing.Optional[bool] = None,
  16888. timeout: typing.Optional[float] = None,
  16889. ) -> None:
  16890. """LocatorAssertions.not_to_have_accessible_description
  16891. The opposite of `locator_assertions.to_have_accessible_description()`.
  16892. Parameters
  16893. ----------
  16894. name : Union[Pattern[str], str]
  16895. Expected accessible description.
  16896. ignore_case : Union[bool, None]
  16897. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16898. expression flag if specified.
  16899. timeout : Union[float, None]
  16900. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16901. """
  16902. __tracebackhide__ = True
  16903. return mapping.from_maybe_impl(
  16904. await self._impl_obj.not_to_have_accessible_description(
  16905. name=name, ignoreCase=ignore_case, timeout=timeout
  16906. )
  16907. )
  16908. async def to_have_accessible_name(
  16909. self,
  16910. name: typing.Union[str, typing.Pattern[str]],
  16911. *,
  16912. ignore_case: typing.Optional[bool] = None,
  16913. timeout: typing.Optional[float] = None,
  16914. ) -> None:
  16915. """LocatorAssertions.to_have_accessible_name
  16916. Ensures the `Locator` points to an element with a given
  16917. [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
  16918. **Usage**
  16919. ```py
  16920. locator = page.get_by_test_id(\"save-button\")
  16921. await expect(locator).to_have_accessible_name(\"Save to disk\")
  16922. ```
  16923. Parameters
  16924. ----------
  16925. name : Union[Pattern[str], str]
  16926. Expected accessible name.
  16927. ignore_case : Union[bool, None]
  16928. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16929. expression flag if specified.
  16930. timeout : Union[float, None]
  16931. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16932. """
  16933. __tracebackhide__ = True
  16934. return mapping.from_maybe_impl(
  16935. await self._impl_obj.to_have_accessible_name(
  16936. name=name, ignoreCase=ignore_case, timeout=timeout
  16937. )
  16938. )
  16939. async def not_to_have_accessible_name(
  16940. self,
  16941. name: typing.Union[str, typing.Pattern[str]],
  16942. *,
  16943. ignore_case: typing.Optional[bool] = None,
  16944. timeout: typing.Optional[float] = None,
  16945. ) -> None:
  16946. """LocatorAssertions.not_to_have_accessible_name
  16947. The opposite of `locator_assertions.to_have_accessible_name()`.
  16948. Parameters
  16949. ----------
  16950. name : Union[Pattern[str], str]
  16951. Expected accessible name.
  16952. ignore_case : Union[bool, None]
  16953. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  16954. expression flag if specified.
  16955. timeout : Union[float, None]
  16956. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  16957. """
  16958. __tracebackhide__ = True
  16959. return mapping.from_maybe_impl(
  16960. await self._impl_obj.not_to_have_accessible_name(
  16961. name=name, ignoreCase=ignore_case, timeout=timeout
  16962. )
  16963. )
  16964. async def to_have_role(
  16965. self,
  16966. role: Literal[
  16967. "alert",
  16968. "alertdialog",
  16969. "application",
  16970. "article",
  16971. "banner",
  16972. "blockquote",
  16973. "button",
  16974. "caption",
  16975. "cell",
  16976. "checkbox",
  16977. "code",
  16978. "columnheader",
  16979. "combobox",
  16980. "complementary",
  16981. "contentinfo",
  16982. "definition",
  16983. "deletion",
  16984. "dialog",
  16985. "directory",
  16986. "document",
  16987. "emphasis",
  16988. "feed",
  16989. "figure",
  16990. "form",
  16991. "generic",
  16992. "grid",
  16993. "gridcell",
  16994. "group",
  16995. "heading",
  16996. "img",
  16997. "insertion",
  16998. "link",
  16999. "list",
  17000. "listbox",
  17001. "listitem",
  17002. "log",
  17003. "main",
  17004. "marquee",
  17005. "math",
  17006. "menu",
  17007. "menubar",
  17008. "menuitem",
  17009. "menuitemcheckbox",
  17010. "menuitemradio",
  17011. "meter",
  17012. "navigation",
  17013. "none",
  17014. "note",
  17015. "option",
  17016. "paragraph",
  17017. "presentation",
  17018. "progressbar",
  17019. "radio",
  17020. "radiogroup",
  17021. "region",
  17022. "row",
  17023. "rowgroup",
  17024. "rowheader",
  17025. "scrollbar",
  17026. "search",
  17027. "searchbox",
  17028. "separator",
  17029. "slider",
  17030. "spinbutton",
  17031. "status",
  17032. "strong",
  17033. "subscript",
  17034. "superscript",
  17035. "switch",
  17036. "tab",
  17037. "table",
  17038. "tablist",
  17039. "tabpanel",
  17040. "term",
  17041. "textbox",
  17042. "time",
  17043. "timer",
  17044. "toolbar",
  17045. "tooltip",
  17046. "tree",
  17047. "treegrid",
  17048. "treeitem",
  17049. ],
  17050. *,
  17051. timeout: typing.Optional[float] = None,
  17052. ) -> None:
  17053. """LocatorAssertions.to_have_role
  17054. Ensures the `Locator` points to an element with a given [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles).
  17055. Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass
  17056. role `\"checkbox\"` on an element with a subclass role `\"switch\"` will fail.
  17057. **Usage**
  17058. ```py
  17059. locator = page.get_by_test_id(\"save-button\")
  17060. await expect(locator).to_have_role(\"button\")
  17061. ```
  17062. Parameters
  17063. ----------
  17064. 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"]
  17065. Required aria role.
  17066. timeout : Union[float, None]
  17067. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17068. """
  17069. __tracebackhide__ = True
  17070. return mapping.from_maybe_impl(
  17071. await self._impl_obj.to_have_role(role=role, timeout=timeout)
  17072. )
  17073. async def to_have_accessible_error_message(
  17074. self,
  17075. error_message: typing.Union[str, typing.Pattern[str]],
  17076. *,
  17077. ignore_case: typing.Optional[bool] = None,
  17078. timeout: typing.Optional[float] = None,
  17079. ) -> None:
  17080. """LocatorAssertions.to_have_accessible_error_message
  17081. Ensures the `Locator` points to an element with a given
  17082. [aria errormessage](https://w3c.github.io/aria/#aria-errormessage).
  17083. **Usage**
  17084. ```py
  17085. locator = page.get_by_test_id(\"username-input\")
  17086. await expect(locator).to_have_accessible_error_message(\"Username is required.\")
  17087. ```
  17088. Parameters
  17089. ----------
  17090. error_message : Union[Pattern[str], str]
  17091. Expected accessible error message.
  17092. ignore_case : Union[bool, None]
  17093. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17094. expression flag if specified.
  17095. timeout : Union[float, None]
  17096. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17097. """
  17098. __tracebackhide__ = True
  17099. return mapping.from_maybe_impl(
  17100. await self._impl_obj.to_have_accessible_error_message(
  17101. errorMessage=error_message, ignoreCase=ignore_case, timeout=timeout
  17102. )
  17103. )
  17104. async def not_to_have_accessible_error_message(
  17105. self,
  17106. error_message: typing.Union[str, typing.Pattern[str]],
  17107. *,
  17108. ignore_case: typing.Optional[bool] = None,
  17109. timeout: typing.Optional[float] = None,
  17110. ) -> None:
  17111. """LocatorAssertions.not_to_have_accessible_error_message
  17112. The opposite of `locator_assertions.to_have_accessible_error_message()`.
  17113. Parameters
  17114. ----------
  17115. error_message : Union[Pattern[str], str]
  17116. Expected accessible error message.
  17117. ignore_case : Union[bool, None]
  17118. Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
  17119. expression flag if specified.
  17120. timeout : Union[float, None]
  17121. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17122. """
  17123. __tracebackhide__ = True
  17124. return mapping.from_maybe_impl(
  17125. await self._impl_obj.not_to_have_accessible_error_message(
  17126. errorMessage=error_message, ignoreCase=ignore_case, timeout=timeout
  17127. )
  17128. )
  17129. async def not_to_have_role(
  17130. self,
  17131. role: Literal[
  17132. "alert",
  17133. "alertdialog",
  17134. "application",
  17135. "article",
  17136. "banner",
  17137. "blockquote",
  17138. "button",
  17139. "caption",
  17140. "cell",
  17141. "checkbox",
  17142. "code",
  17143. "columnheader",
  17144. "combobox",
  17145. "complementary",
  17146. "contentinfo",
  17147. "definition",
  17148. "deletion",
  17149. "dialog",
  17150. "directory",
  17151. "document",
  17152. "emphasis",
  17153. "feed",
  17154. "figure",
  17155. "form",
  17156. "generic",
  17157. "grid",
  17158. "gridcell",
  17159. "group",
  17160. "heading",
  17161. "img",
  17162. "insertion",
  17163. "link",
  17164. "list",
  17165. "listbox",
  17166. "listitem",
  17167. "log",
  17168. "main",
  17169. "marquee",
  17170. "math",
  17171. "menu",
  17172. "menubar",
  17173. "menuitem",
  17174. "menuitemcheckbox",
  17175. "menuitemradio",
  17176. "meter",
  17177. "navigation",
  17178. "none",
  17179. "note",
  17180. "option",
  17181. "paragraph",
  17182. "presentation",
  17183. "progressbar",
  17184. "radio",
  17185. "radiogroup",
  17186. "region",
  17187. "row",
  17188. "rowgroup",
  17189. "rowheader",
  17190. "scrollbar",
  17191. "search",
  17192. "searchbox",
  17193. "separator",
  17194. "slider",
  17195. "spinbutton",
  17196. "status",
  17197. "strong",
  17198. "subscript",
  17199. "superscript",
  17200. "switch",
  17201. "tab",
  17202. "table",
  17203. "tablist",
  17204. "tabpanel",
  17205. "term",
  17206. "textbox",
  17207. "time",
  17208. "timer",
  17209. "toolbar",
  17210. "tooltip",
  17211. "tree",
  17212. "treegrid",
  17213. "treeitem",
  17214. ],
  17215. *,
  17216. timeout: typing.Optional[float] = None,
  17217. ) -> None:
  17218. """LocatorAssertions.not_to_have_role
  17219. The opposite of `locator_assertions.to_have_role()`.
  17220. Parameters
  17221. ----------
  17222. 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"]
  17223. Required aria role.
  17224. timeout : Union[float, None]
  17225. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17226. """
  17227. __tracebackhide__ = True
  17228. return mapping.from_maybe_impl(
  17229. await self._impl_obj.not_to_have_role(role=role, timeout=timeout)
  17230. )
  17231. async def to_match_aria_snapshot(
  17232. self, expected: str, *, timeout: typing.Optional[float] = None
  17233. ) -> None:
  17234. """LocatorAssertions.to_match_aria_snapshot
  17235. Asserts that the target element matches the given [accessibility snapshot](https://playwright.dev/python/docs/aria-snapshots).
  17236. **Usage**
  17237. ```py
  17238. await page.goto(\"https://demo.playwright.dev/todomvc/\")
  17239. await expect(page.locator('body')).to_match_aria_snapshot('''
  17240. - heading \"todos\"
  17241. - textbox \"What needs to be done?\"
  17242. ''')
  17243. ```
  17244. Parameters
  17245. ----------
  17246. expected : str
  17247. timeout : Union[float, None]
  17248. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17249. """
  17250. __tracebackhide__ = True
  17251. return mapping.from_maybe_impl(
  17252. await self._impl_obj.to_match_aria_snapshot(
  17253. expected=expected, timeout=timeout
  17254. )
  17255. )
  17256. async def not_to_match_aria_snapshot(
  17257. self, expected: str, *, timeout: typing.Optional[float] = None
  17258. ) -> None:
  17259. """LocatorAssertions.not_to_match_aria_snapshot
  17260. The opposite of `locator_assertions.to_match_aria_snapshot()`.
  17261. Parameters
  17262. ----------
  17263. expected : str
  17264. timeout : Union[float, None]
  17265. Time to retry the assertion for in milliseconds. Defaults to `5000`.
  17266. """
  17267. __tracebackhide__ = True
  17268. return mapping.from_maybe_impl(
  17269. await self._impl_obj.not_to_match_aria_snapshot(
  17270. expected=expected, timeout=timeout
  17271. )
  17272. )
  17273. mapping.register(LocatorAssertionsImpl, LocatorAssertions)
  17274. class APIResponseAssertions(AsyncBase):
  17275. async def to_be_ok(self) -> None:
  17276. """APIResponseAssertions.to_be_ok
  17277. Ensures the response status code is within `200..299` range.
  17278. **Usage**
  17279. ```py
  17280. from playwright.async_api import expect
  17281. # ...
  17282. await expect(response).to_be_ok()
  17283. ```
  17284. """
  17285. __tracebackhide__ = True
  17286. return mapping.from_maybe_impl(await self._impl_obj.to_be_ok())
  17287. async def not_to_be_ok(self) -> None:
  17288. """APIResponseAssertions.not_to_be_ok
  17289. The opposite of `a_pi_response_assertions.to_be_ok()`.
  17290. """
  17291. __tracebackhide__ = True
  17292. return mapping.from_maybe_impl(await self._impl_obj.not_to_be_ok())
  17293. mapping.register(APIResponseAssertionsImpl, APIResponseAssertions)