| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177 |
- # Copyright (c) Microsoft Corporation.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- import datetime
- import pathlib
- import typing
- from typing import Literal
- from playwright._impl._api_structures import (
- ClientCertificate,
- Cookie,
- FilePayload,
- FloatRect,
- Geolocation,
- HttpCredentials,
- NameValue,
- PdfMargins,
- Position,
- ProxySettings,
- RemoteAddr,
- RequestSizes,
- ResourceTiming,
- SecurityDetails,
- SetCookieParam,
- SourceLocation,
- StorageState,
- TracingGroupLocation,
- ViewportSize,
- )
- from playwright._impl._assertions import (
- APIResponseAssertions as APIResponseAssertionsImpl,
- )
- from playwright._impl._assertions import LocatorAssertions as LocatorAssertionsImpl
- from playwright._impl._assertions import PageAssertions as PageAssertionsImpl
- from playwright._impl._browser import Browser as BrowserImpl
- from playwright._impl._browser_context import BrowserContext as BrowserContextImpl
- from playwright._impl._browser_type import BrowserType as BrowserTypeImpl
- from playwright._impl._cdp_session import CDPSession as CDPSessionImpl
- from playwright._impl._clock import Clock as ClockImpl
- from playwright._impl._console_message import ConsoleMessage as ConsoleMessageImpl
- from playwright._impl._dialog import Dialog as DialogImpl
- from playwright._impl._download import Download as DownloadImpl
- from playwright._impl._element_handle import ElementHandle as ElementHandleImpl
- from playwright._impl._errors import Error
- from playwright._impl._fetch import APIRequest as APIRequestImpl
- from playwright._impl._fetch import APIRequestContext as APIRequestContextImpl
- from playwright._impl._fetch import APIResponse as APIResponseImpl
- from playwright._impl._file_chooser import FileChooser as FileChooserImpl
- from playwright._impl._frame import Frame as FrameImpl
- from playwright._impl._input import Keyboard as KeyboardImpl
- from playwright._impl._input import Mouse as MouseImpl
- from playwright._impl._input import Touchscreen as TouchscreenImpl
- from playwright._impl._js_handle import JSHandle as JSHandleImpl
- from playwright._impl._locator import FrameLocator as FrameLocatorImpl
- from playwright._impl._locator import Locator as LocatorImpl
- from playwright._impl._network import Request as RequestImpl
- from playwright._impl._network import Response as ResponseImpl
- from playwright._impl._network import Route as RouteImpl
- from playwright._impl._network import WebSocket as WebSocketImpl
- from playwright._impl._network import WebSocketRoute as WebSocketRouteImpl
- from playwright._impl._page import Page as PageImpl
- from playwright._impl._page import Worker as WorkerImpl
- from playwright._impl._playwright import Playwright as PlaywrightImpl
- from playwright._impl._selectors import Selectors as SelectorsImpl
- from playwright._impl._sync_base import (
- EventContextManager,
- SyncBase,
- SyncContextManager,
- mapping,
- )
- from playwright._impl._tracing import Tracing as TracingImpl
- from playwright._impl._video import Video as VideoImpl
- from playwright._impl._web_error import WebError as WebErrorImpl
- class Request(SyncBase):
- @property
- def url(self) -> str:
- """Request.url
- URL of the request.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- @property
- def resource_type(self) -> str:
- """Request.resource_type
- Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the
- following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,
- `eventsource`, `websocket`, `manifest`, `other`.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.resource_type)
- @property
- def service_worker(self) -> typing.Optional["Worker"]:
- """Request.service_worker
- The Service `Worker` that is performing the request.
- **Details**
- This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.
- Requests originated in a Service Worker do not have a `request.frame()` available.
- Returns
- -------
- Union[Worker, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.service_worker)
- @property
- def method(self) -> str:
- """Request.method
- Request's method (GET, POST, etc.)
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.method)
- @property
- def post_data(self) -> typing.Optional[str]:
- """Request.post_data
- Request's post body, if any.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(self._impl_obj.post_data)
- @property
- def post_data_json(self) -> typing.Optional[typing.Any]:
- """Request.post_data_json
- Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.
- When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.
- Otherwise it will be parsed as JSON.
- Returns
- -------
- Union[Any, None]
- """
- return mapping.from_maybe_impl(self._impl_obj.post_data_json)
- @property
- def post_data_buffer(self) -> typing.Optional[bytes]:
- """Request.post_data_buffer
- Request's post body in a binary form, if any.
- Returns
- -------
- Union[bytes, None]
- """
- return mapping.from_maybe_impl(self._impl_obj.post_data_buffer)
- @property
- def frame(self) -> "Frame":
- """Request.frame
- Returns the `Frame` that initiated this request.
- **Usage**
- ```py
- frame_url = request.frame.url
- ```
- **Details**
- Note that in some cases the frame is not available, and this method will throw.
- - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.
- - When navigation request is issued before the corresponding frame is created. You can use
- `request.is_navigation_request()` to check that.
- Here is an example that handles all the cases:
- Returns
- -------
- Frame
- """
- return mapping.from_impl(self._impl_obj.frame)
- @property
- def redirected_from(self) -> typing.Optional["Request"]:
- """Request.redirected_from
- Request that was redirected by the server to this one, if any.
- When the server responds with a redirect, Playwright creates a new `Request` object. The two requests are connected
- by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
- construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
- **Usage**
- For example, if the website `http://example.com` redirects to `https://example.com`:
- ```py
- response = page.goto(\"http://example.com\")
- print(response.request.redirected_from.url) # \"http://example.com\"
- ```
- If the website `https://google.com` has no redirects:
- ```py
- response = page.goto(\"https://google.com\")
- print(response.request.redirected_from) # None
- ```
- Returns
- -------
- Union[Request, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.redirected_from)
- @property
- def redirected_to(self) -> typing.Optional["Request"]:
- """Request.redirected_to
- New request issued by the browser if the server responded with redirect.
- **Usage**
- This method is the opposite of `request.redirected_from()`:
- ```py
- assert request.redirected_from.redirected_to == request
- ```
- Returns
- -------
- Union[Request, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.redirected_to)
- @property
- def failure(self) -> typing.Optional[str]:
- """Request.failure
- The method returns `null` unless this request has failed, as reported by `requestfailed` event.
- **Usage**
- Example of logging of all the failed requests:
- ```py
- page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure))
- ```
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(self._impl_obj.failure)
- @property
- def timing(self) -> ResourceTiming:
- """Request.timing
- Returns resource timing information for given request. Most of the timing values become available upon the
- response, `responseEnd` becomes available when request finishes. Find more information at
- [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
- **Usage**
- ```py
- with page.expect_event(\"requestfinished\") as request_info:
- page.goto(\"http://example.com\")
- request = request_info.value
- print(request.timing)
- ```
- Returns
- -------
- {startTime: float, domainLookupStart: float, domainLookupEnd: float, connectStart: float, secureConnectionStart: float, connectEnd: float, requestStart: float, responseStart: float, responseEnd: float}
- """
- return mapping.from_impl(self._impl_obj.timing)
- @property
- def headers(self) -> typing.Dict[str, str]:
- """Request.headers
- An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return
- security-related headers, including cookie-related ones. You can use `request.all_headers()` for complete
- list of headers that include `cookie` information.
- Returns
- -------
- Dict[str, str]
- """
- return mapping.from_maybe_impl(self._impl_obj.headers)
- def sizes(self) -> RequestSizes:
- """Request.sizes
- Returns resource size information for given request.
- Returns
- -------
- {requestBodySize: int, requestHeadersSize: int, responseBodySize: int, responseHeadersSize: int}
- """
- return mapping.from_impl(self._sync(self._impl_obj.sizes()))
- def response(self) -> typing.Optional["Response"]:
- """Request.response
- Returns the matching `Response` object, or `null` if the response was not received due to error.
- Returns
- -------
- Union[Response, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.response()))
- def is_navigation_request(self) -> bool:
- """Request.is_navigation_request
- Whether this request is driving frame's navigation.
- Some navigation requests are issued before the corresponding frame is created, and therefore do not have
- `request.frame()` available.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.is_navigation_request())
- def all_headers(self) -> typing.Dict[str, str]:
- """Request.all_headers
- An object with all the request HTTP headers associated with this request. The header names are lower-cased.
- Returns
- -------
- Dict[str, str]
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.all_headers()))
- def headers_array(self) -> typing.List[NameValue]:
- """Request.headers_array
- An array with all the request HTTP headers associated with this request. Unlike `request.all_headers()`,
- header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
- times.
- Returns
- -------
- List[{name: str, value: str}]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.headers_array()))
- def header_value(self, name: str) -> typing.Optional[str]:
- """Request.header_value
- Returns the value of the header matching the name. The name is case-insensitive.
- Parameters
- ----------
- name : str
- Name of the header.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.header_value(name=name))
- )
- mapping.register(RequestImpl, Request)
- class Response(SyncBase):
- @property
- def url(self) -> str:
- """Response.url
- Contains the URL of the response.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- @property
- def ok(self) -> bool:
- """Response.ok
- Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.ok)
- @property
- def status(self) -> int:
- """Response.status
- Contains the status code of the response (e.g., 200 for a success).
- Returns
- -------
- int
- """
- return mapping.from_maybe_impl(self._impl_obj.status)
- @property
- def status_text(self) -> str:
- """Response.status_text
- Contains the status text of the response (e.g. usually an \"OK\" for a success).
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.status_text)
- @property
- def headers(self) -> typing.Dict[str, str]:
- """Response.headers
- An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return
- security-related headers, including cookie-related ones. You can use `response.all_headers()` for complete
- list of headers that include `cookie` information.
- Returns
- -------
- Dict[str, str]
- """
- return mapping.from_maybe_impl(self._impl_obj.headers)
- @property
- def from_service_worker(self) -> bool:
- """Response.from_service_worker
- Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via
- [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.from_service_worker)
- @property
- def request(self) -> "Request":
- """Response.request
- Returns the matching `Request` object.
- Returns
- -------
- Request
- """
- return mapping.from_impl(self._impl_obj.request)
- @property
- def frame(self) -> "Frame":
- """Response.frame
- Returns the `Frame` that initiated this response.
- Returns
- -------
- Frame
- """
- return mapping.from_impl(self._impl_obj.frame)
- def all_headers(self) -> typing.Dict[str, str]:
- """Response.all_headers
- An object with all the response HTTP headers associated with this response.
- Returns
- -------
- Dict[str, str]
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.all_headers()))
- def headers_array(self) -> typing.List[NameValue]:
- """Response.headers_array
- An array with all the request HTTP headers associated with this response. Unlike `response.all_headers()`,
- header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple
- times.
- Returns
- -------
- List[{name: str, value: str}]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.headers_array()))
- def header_value(self, name: str) -> typing.Optional[str]:
- """Response.header_value
- Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same
- name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\\n` separator is
- used. If no headers are found, `null` is returned.
- Parameters
- ----------
- name : str
- Name of the header.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.header_value(name=name))
- )
- def header_values(self, name: str) -> typing.List[str]:
- """Response.header_values
- Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.
- Parameters
- ----------
- name : str
- Name of the header.
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.header_values(name=name))
- )
- def server_addr(self) -> typing.Optional[RemoteAddr]:
- """Response.server_addr
- Returns the IP address and port of the server.
- Returns
- -------
- Union[{ipAddress: str, port: int}, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.server_addr()))
- def security_details(self) -> typing.Optional[SecurityDetails]:
- """Response.security_details
- Returns SSL and other security information.
- Returns
- -------
- Union[{issuer: Union[str, None], protocol: Union[str, None], subjectName: Union[str, None], validFrom: Union[float, None], validTo: Union[float, None]}, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.security_details()))
- def finished(self) -> None:
- """Response.finished
- Waits for this response to finish, returns always `null`.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.finished()))
- def body(self) -> bytes:
- """Response.body
- Returns the buffer with response body.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.body()))
- def text(self) -> str:
- """Response.text
- Returns the text representation of response body.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.text()))
- def json(self) -> typing.Any:
- """Response.json
- Returns the JSON representation of response body.
- This method will throw if the response body is not parsable via `JSON.parse`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.json()))
- mapping.register(ResponseImpl, Response)
- class Route(SyncBase):
- @property
- def request(self) -> "Request":
- """Route.request
- A request to be routed.
- Returns
- -------
- Request
- """
- return mapping.from_impl(self._impl_obj.request)
- def abort(self, error_code: typing.Optional[str] = None) -> None:
- """Route.abort
- Aborts the route's request.
- Parameters
- ----------
- error_code : Union[str, None]
- Optional error code. Defaults to `failed`, could be one of the following:
- - `'aborted'` - An operation was aborted (due to user action)
- - `'accessdenied'` - Permission to access a resource, other than the network, was denied
- - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the
- specified host or network.
- - `'blockedbyclient'` - The client chose to block the request.
- - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are
- not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
- - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
- - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
- - `'connectionfailed'` - A connection attempt failed.
- - `'connectionrefused'` - A connection attempt was refused.
- - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
- - `'internetdisconnected'` - The Internet connection has been lost.
- - `'namenotresolved'` - The host name could not be resolved.
- - `'timedout'` - An operation timed out.
- - `'failed'` - A generic failure occurred.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.abort(errorCode=error_code))
- )
- def fulfill(
- self,
- *,
- status: typing.Optional[int] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- body: typing.Optional[typing.Union[str, bytes]] = None,
- json: typing.Optional[typing.Any] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- content_type: typing.Optional[str] = None,
- response: typing.Optional["APIResponse"] = None,
- ) -> None:
- """Route.fulfill
- Fulfills route's request with given response.
- **Usage**
- An example of fulfilling all requests with 404 responses:
- ```py
- page.route(\"**/*\", lambda route: route.fulfill(
- status=404,
- content_type=\"text/plain\",
- body=\"not found!\"))
- ```
- An example of serving static file:
- ```py
- page.route(\"**/xhr_endpoint\", lambda route: route.fulfill(path=\"mock_data.json\"))
- ```
- Parameters
- ----------
- status : Union[int, None]
- Response status code, defaults to `200`.
- headers : Union[Dict[str, str], None]
- Response headers. Header values will be converted to a string.
- body : Union[bytes, str, None]
- Response body.
- json : Union[Any, None]
- JSON response. This method will set the content type to `application/json` if not set.
- path : Union[pathlib.Path, str, None]
- File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,
- then it is resolved relative to the current working directory.
- content_type : Union[str, None]
- If set, equals to setting `Content-Type` response header.
- response : Union[APIResponse, None]
- `APIResponse` to fulfill route's request with. Individual fields of the response (such as headers) can be
- overridden using fulfill options.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.fulfill(
- status=status,
- headers=mapping.to_impl(headers),
- body=body,
- json=mapping.to_impl(json),
- path=path,
- contentType=content_type,
- response=response._impl_obj if response else None,
- )
- )
- )
- def fetch(
- self,
- *,
- url: typing.Optional[str] = None,
- method: typing.Optional[str] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- timeout: typing.Optional[float] = None,
- ) -> "APIResponse":
- """Route.fetch
- Performs the request and fetches result without fulfilling it, so that the response could be modified and then
- fulfilled.
- **Usage**
- ```py
- def handle(route):
- response = route.fetch()
- json = response.json()
- json[\"message\"][\"big_red_dog\"] = []
- route.fulfill(response=response, json=json)
- page.route(\"https://dog.ceo/api/breeds/list/all\", handle)
- ```
- **Details**
- Note that `headers` option will apply to the fetched request as well as any redirects initiated by it. If you want
- to only apply `headers` to the original request, but not to redirects, look into `route.continue_()`
- instead.
- Parameters
- ----------
- url : Union[str, None]
- If set changes the request URL. New URL must have same protocol as original one.
- method : Union[str, None]
- If set changes the request method (e.g. GET or POST).
- headers : Union[Dict[str, str], None]
- If set changes the request HTTP headers. Header values will be converted to a string.
- post_data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.fetch(
- url=url,
- method=method,
- headers=mapping.to_impl(headers),
- postData=mapping.to_impl(post_data),
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- timeout=timeout,
- )
- )
- )
- def fallback(
- self,
- *,
- url: typing.Optional[str] = None,
- method: typing.Optional[str] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- ) -> None:
- """Route.fallback
- Continues route's request with optional overrides. The method is similar to `route.continue_()` with the
- difference that other matching handlers will be invoked before sending the request.
- **Usage**
- When several routes match the given pattern, they run in the order opposite to their registration. That way the
- last registered route can always override all the previous ones. In the example below, request will be handled by
- the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
- registered route.
- ```py
- page.route(\"**/*\", lambda route: route.abort()) # Runs last.
- page.route(\"**/*\", lambda route: route.fallback()) # Runs second.
- page.route(\"**/*\", lambda route: route.fallback()) # Runs first.
- ```
- Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for
- example API calls vs page resources or GET requests vs POST requests as in the example below.
- ```py
- # Handle GET requests.
- def handle_get(route):
- if route.request.method != \"GET\":
- route.fallback()
- return
- # Handling GET only.
- # ...
- # Handle POST requests.
- def handle_post(route):
- if route.request.method != \"POST\":
- route.fallback()
- return
- # Handling POST only.
- # ...
- page.route(\"**/*\", handle_get)
- page.route(\"**/*\", handle_post)
- ```
- One can also modify request while falling back to the subsequent handler, that way intermediate route handler can
- modify url, method, headers and postData of the request.
- ```py
- def handle(route, request):
- # override headers
- headers = {
- **request.headers,
- \"foo\": \"foo-value\", # set \"foo\" header
- \"bar\": None # remove \"bar\" header
- }
- route.fallback(headers=headers)
- page.route(\"**/*\", handle)
- ```
- Use `route.continue_()` to immediately send the request to the network, other matching handlers won't be
- invoked in that case.
- Parameters
- ----------
- url : Union[str, None]
- If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the
- route matching, all the routes are matched using the original request URL.
- method : Union[str, None]
- If set changes the request method (e.g. GET or POST).
- headers : Union[Dict[str, str], None]
- If set changes the request HTTP headers. Header values will be converted to a string.
- post_data : Union[Any, bytes, str, None]
- If set changes the post data of request.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.fallback(
- url=url,
- method=method,
- headers=mapping.to_impl(headers),
- postData=mapping.to_impl(post_data),
- )
- )
- )
- def continue_(
- self,
- *,
- url: typing.Optional[str] = None,
- method: typing.Optional[str] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- post_data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- ) -> None:
- """Route.continue_
- Sends route's request to the network with optional overrides.
- **Usage**
- ```py
- def handle(route, request):
- # override headers
- headers = {
- **request.headers,
- \"foo\": \"foo-value\", # set \"foo\" header
- \"bar\": None # remove \"bar\" header
- }
- route.continue_(headers=headers)
- page.route(\"**/*\", handle)
- ```
- **Details**
- The `headers` option applies to both the routed request and any redirects it initiates. However, `url`, `method`,
- and `postData` only apply to the original request and are not carried over to redirected requests.
- `route.continue_()` will immediately send the request to the network, other matching handlers won't be
- invoked. Use `route.fallback()` If you want next matching handler in the chain to be invoked.
- **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,
- `Content-Length` and others, see
- [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an
- override is provided for a forbidden header, it will be ignored and the original request header will be used.
- To set custom cookies, use `browser_context.add_cookies()`.
- Parameters
- ----------
- url : Union[str, None]
- If set changes the request URL. New URL must have same protocol as original one.
- method : Union[str, None]
- If set changes the request method (e.g. GET or POST).
- headers : Union[Dict[str, str], None]
- If set changes the request HTTP headers. Header values will be converted to a string.
- post_data : Union[Any, bytes, str, None]
- If set changes the post data of request.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.continue_(
- url=url,
- method=method,
- headers=mapping.to_impl(headers),
- postData=mapping.to_impl(post_data),
- )
- )
- )
- mapping.register(RouteImpl, Route)
- class WebSocket(SyncBase):
- @typing.overload
- def on(
- self, event: Literal["close"], f: typing.Callable[["WebSocket"], "None"]
- ) -> None:
- """
- Fired when the websocket closes."""
- @typing.overload
- def on(
- self,
- event: Literal["framereceived"],
- f: typing.Callable[["typing.Union[bytes, str]"], "None"],
- ) -> None:
- """
- Fired when the websocket receives a frame."""
- @typing.overload
- def on(
- self,
- event: Literal["framesent"],
- f: typing.Callable[["typing.Union[bytes, str]"], "None"],
- ) -> None:
- """
- Fired when the websocket sends a frame."""
- @typing.overload
- def on(
- self, event: Literal["socketerror"], f: typing.Callable[["str"], "None"]
- ) -> None:
- """
- Fired when the websocket has an error."""
- def on(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().on(event=event, f=f)
- @typing.overload
- def once(
- self, event: Literal["close"], f: typing.Callable[["WebSocket"], "None"]
- ) -> None:
- """
- Fired when the websocket closes."""
- @typing.overload
- def once(
- self,
- event: Literal["framereceived"],
- f: typing.Callable[["typing.Union[bytes, str]"], "None"],
- ) -> None:
- """
- Fired when the websocket receives a frame."""
- @typing.overload
- def once(
- self,
- event: Literal["framesent"],
- f: typing.Callable[["typing.Union[bytes, str]"], "None"],
- ) -> None:
- """
- Fired when the websocket sends a frame."""
- @typing.overload
- def once(
- self, event: Literal["socketerror"], f: typing.Callable[["str"], "None"]
- ) -> None:
- """
- Fired when the websocket has an error."""
- def once(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().once(event=event, f=f)
- @property
- def url(self) -> str:
- """WebSocket.url
- Contains the URL of the WebSocket.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- def expect_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager:
- """WebSocket.expect_event
- Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
- value. Will throw an error if the webSocket is closed before the event is fired. Returns the event data value.
- Parameters
- ----------
- event : str
- Event name, same one would pass into `webSocket.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_event(
- event=event, predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def wait_for_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> typing.Any:
- """WebSocket.wait_for_event
- **NOTE** In most cases, you should use `web_socket.expect_event()`.
- Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
- and waits for `predicate(event)` to return a truthy value. Will throw an error if the socket is closed before the
- `event` is fired.
- Parameters
- ----------
- event : str
- Event name, same one typically passed into `*.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.wait_for_event(
- event=event,
- predicate=self._wrap_handler(predicate),
- timeout=timeout,
- )
- )
- )
- def is_closed(self) -> bool:
- """WebSocket.is_closed
- Indicates that the web socket has been closed.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.is_closed())
- mapping.register(WebSocketImpl, WebSocket)
- class WebSocketRoute(SyncBase):
- @property
- def url(self) -> str:
- """WebSocketRoute.url
- URL of the WebSocket created in the page.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- def close(
- self, *, code: typing.Optional[int] = None, reason: typing.Optional[str] = None
- ) -> None:
- """WebSocketRoute.close
- Closes one side of the WebSocket connection.
- Parameters
- ----------
- code : Union[int, None]
- Optional [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code).
- reason : Union[str, None]
- Optional [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.close(code=code, reason=reason))
- )
- def connect_to_server(self) -> "WebSocketRoute":
- """WebSocketRoute.connect_to_server
- By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This
- method connects to the actual WebSocket server, and returns the server-side `WebSocketRoute` instance, giving the
- ability to send and receive messages from the server.
- Once connected to the server:
- - Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless
- `web_socket_route.on_message()` is called on the server-side `WebSocketRoute`.
- - Messages sent by the [`WebSocket.send()`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) call
- in the page will be **automatically forwarded** to the server, unless `web_socket_route.on_message()` is
- called on the original `WebSocketRoute`.
- See examples at the top for more details.
- Returns
- -------
- WebSocketRoute
- """
- return mapping.from_impl(self._impl_obj.connect_to_server())
- def send(self, message: typing.Union[str, bytes]) -> None:
- """WebSocketRoute.send
- Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called
- on the result of `web_socket_route.connect_to_server()`, sends the message to the server. See examples at the
- top for more details.
- Parameters
- ----------
- message : Union[bytes, str]
- Message to send.
- """
- return mapping.from_maybe_impl(self._impl_obj.send(message=message))
- def on_message(
- self, handler: typing.Callable[[typing.Union[str, bytes]], typing.Any]
- ) -> None:
- """WebSocketRoute.on_message
- This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.
- When called on the original WebSocket route, this method handles messages sent from the page. You can handle this
- messages by responding to them with `web_socket_route.send()`, forwarding them to the server-side connection
- returned by `web_socket_route.connect_to_server()` or do something else.
- Once this method is called, messages are not automatically forwarded to the server or to the page - you should do
- that manually by calling `web_socket_route.send()`. See examples at the top for more details.
- Calling this method again will override the handler with a new one.
- Parameters
- ----------
- handler : Callable[[Union[bytes, str]], Any]
- Function that will handle messages.
- """
- return mapping.from_maybe_impl(
- self._impl_obj.on_message(handler=self._wrap_handler(handler))
- )
- def on_close(
- self,
- handler: typing.Callable[
- [typing.Optional[int], typing.Optional[str]], typing.Any
- ],
- ) -> None:
- """WebSocketRoute.on_close
- Allows to handle [`WebSocket.close`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close).
- By default, closing one side of the connection, either in the page or on the server, will close the other side.
- However, when `web_socket_route.on_close()` handler is set up, the default forwarding of closure is disabled,
- and handler should take care of it.
- Parameters
- ----------
- handler : Callable[[Union[int, None], Union[str, None]], Any]
- Function that will handle WebSocket closure. Received an optional
- [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code) and an optional
- [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).
- """
- return mapping.from_maybe_impl(
- self._impl_obj.on_close(handler=self._wrap_handler(handler))
- )
- mapping.register(WebSocketRouteImpl, WebSocketRoute)
- class Keyboard(SyncBase):
- def down(self, key: str) -> None:
- """Keyboard.down
- Dispatches a `keydown` event.
- `key` can specify the intended
- [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- to generate the text for. A superset of the `key` values can be found
- [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- etc.
- Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
- Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- texts.
- If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that
- modifier active. To release the modifier key, use `keyboard.up()`.
- After the key is pressed once, subsequent calls to `keyboard.down()` will have
- [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,
- use `keyboard.up()`.
- **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
- Parameters
- ----------
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.down(key=key)))
- def up(self, key: str) -> None:
- """Keyboard.up
- Dispatches a `keyup` event.
- Parameters
- ----------
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.up(key=key)))
- def insert_text(self, text: str) -> None:
- """Keyboard.insert_text
- Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
- **Usage**
- ```py
- page.keyboard.insert_text(\"嗨\")
- ```
- **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper
- case.
- Parameters
- ----------
- text : str
- Sets input to the specified text value.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.insert_text(text=text))
- )
- def type(self, text: str, *, delay: typing.Optional[float] = None) -> None:
- """Keyboard.type
- **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
- there is special keyboard handling on the page - in this case use `locator.press_sequentially()`.
- Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
- To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
- **Usage**
- ```py
- page.keyboard.type(\"Hello\") # types instantly
- page.keyboard.type(\"World\", delay=100) # types slower, like a user
- ```
- **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.
- **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.
- Parameters
- ----------
- text : str
- A text to type into a focused element.
- delay : Union[float, None]
- Time to wait between key presses in milliseconds. Defaults to 0.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.type(text=text, delay=delay))
- )
- def press(self, key: str, *, delay: typing.Optional[float] = None) -> None:
- """Keyboard.press
- **NOTE** In most cases, you should use `locator.press()` instead.
- `key` can specify the intended
- [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- to generate the text for. A superset of the `key` values can be found
- [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- etc.
- Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
- Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- texts.
- Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
- specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- **Usage**
- ```py
- page = browser.new_page()
- page.goto(\"https://keycode.info\")
- page.keyboard.press(\"a\")
- page.screenshot(path=\"a.png\")
- page.keyboard.press(\"ArrowLeft\")
- page.screenshot(path=\"arrow_left.png\")
- page.keyboard.press(\"Shift+O\")
- page.screenshot(path=\"o.png\")
- browser.close()
- ```
- Shortcut for `keyboard.down()` and `keyboard.up()`.
- Parameters
- ----------
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- delay : Union[float, None]
- Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.press(key=key, delay=delay))
- )
- mapping.register(KeyboardImpl, Keyboard)
- class Mouse(SyncBase):
- def move(self, x: float, y: float, *, steps: typing.Optional[int] = None) -> None:
- """Mouse.move
- Dispatches a `mousemove` event.
- Parameters
- ----------
- x : float
- X coordinate relative to the main frame's viewport in CSS pixels.
- y : float
- Y coordinate relative to the main frame's viewport in CSS pixels.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
- position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.move(x=x, y=y, steps=steps))
- )
- def down(
- self,
- *,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- ) -> None:
- """Mouse.down
- Dispatches a `mousedown` event.
- Parameters
- ----------
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.down(button=button, clickCount=click_count))
- )
- def up(
- self,
- *,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- ) -> None:
- """Mouse.up
- Dispatches a `mouseup` event.
- Parameters
- ----------
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.up(button=button, clickCount=click_count))
- )
- def click(
- self,
- x: float,
- y: float,
- *,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- ) -> None:
- """Mouse.click
- Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`.
- Parameters
- ----------
- x : float
- X coordinate relative to the main frame's viewport in CSS pixels.
- y : float
- Y coordinate relative to the main frame's viewport in CSS pixels.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.click(
- x=x, y=y, delay=delay, button=button, clickCount=click_count
- )
- )
- )
- def dblclick(
- self,
- x: float,
- y: float,
- *,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- ) -> None:
- """Mouse.dblclick
- Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`, `mouse.down()` and
- `mouse.up()`.
- Parameters
- ----------
- x : float
- X coordinate relative to the main frame's viewport in CSS pixels.
- y : float
- Y coordinate relative to the main frame's viewport in CSS pixels.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.dblclick(x=x, y=y, delay=delay, button=button))
- )
- def wheel(self, delta_x: float, delta_y: float) -> None:
- """Mouse.wheel
- Dispatches a `wheel` event. This method is usually used to manually scroll the page. See
- [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
- **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling
- to finish before returning.
- Parameters
- ----------
- delta_x : float
- Pixels to scroll horizontally.
- delta_y : float
- Pixels to scroll vertically.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.wheel(deltaX=delta_x, deltaY=delta_y))
- )
- mapping.register(MouseImpl, Mouse)
- class Touchscreen(SyncBase):
- def tap(self, x: float, y: float) -> None:
- """Touchscreen.tap
- Dispatches a `touchstart` and `touchend` event with a single touch at the position (`x`,`y`).
- **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
- Parameters
- ----------
- x : float
- X coordinate relative to the main frame's viewport in CSS pixels.
- y : float
- Y coordinate relative to the main frame's viewport in CSS pixels.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.tap(x=x, y=y)))
- mapping.register(TouchscreenImpl, Touchscreen)
- class JSHandle(SyncBase):
- def evaluate(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """JSHandle.evaluate
- Returns the return value of `expression`.
- This method passes this handle as the first argument to `expression`.
- If `expression` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
- value.
- **Usage**
- ```py
- tweet_handle = page.query_selector(\".tweet .retweets\")
- assert tweet_handle.evaluate(\"node => node.innerText\") == \"10 retweets\"
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
- )
- )
- def evaluate_handle(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> "JSHandle":
- """JSHandle.evaluate_handle
- Returns the return value of `expression` as a `JSHandle`.
- This method passes this handle as the first argument to `expression`.
- The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
- returns `JSHandle`.
- If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
- wait for the promise to resolve and return its value.
- See `page.evaluate_handle()` for more details.
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.evaluate_handle(
- expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def get_property(self, property_name: str) -> "JSHandle":
- """JSHandle.get_property
- Fetches a single property from the referenced object.
- Parameters
- ----------
- property_name : str
- property to get
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(self._impl_obj.get_property(propertyName=property_name))
- )
- def get_properties(self) -> typing.Dict[str, "JSHandle"]:
- """JSHandle.get_properties
- The method returns a map with **own property names** as keys and JSHandle instances for the property values.
- **Usage**
- ```py
- handle = page.evaluate_handle(\"({ window, document })\")
- properties = handle.get_properties()
- window_handle = properties.get(\"window\")
- document_handle = properties.get(\"document\")
- handle.dispose()
- ```
- Returns
- -------
- Dict[str, JSHandle]
- """
- return mapping.from_impl_dict(self._sync(self._impl_obj.get_properties()))
- def as_element(self) -> typing.Optional["ElementHandle"]:
- """JSHandle.as_element
- Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.as_element())
- def dispose(self) -> None:
- """JSHandle.dispose
- The `jsHandle.dispose` method stops referencing the element handle.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.dispose()))
- def json_value(self) -> typing.Any:
- """JSHandle.json_value
- Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
- **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw
- an error if the object has circular references.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.json_value()))
- mapping.register(JSHandleImpl, JSHandle)
- class ElementHandle(JSHandle):
- def as_element(self) -> typing.Optional["ElementHandle"]:
- """ElementHandle.as_element
- Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.as_element())
- def owner_frame(self) -> typing.Optional["Frame"]:
- """ElementHandle.owner_frame
- Returns the frame containing the given element.
- Returns
- -------
- Union[Frame, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.owner_frame()))
- def content_frame(self) -> typing.Optional["Frame"]:
- """ElementHandle.content_frame
- Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
- Returns
- -------
- Union[Frame, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.content_frame()))
- def get_attribute(self, name: str) -> typing.Optional[str]:
- """ElementHandle.get_attribute
- Returns element attribute value.
- Parameters
- ----------
- name : str
- Attribute name to get the value for.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.get_attribute(name=name))
- )
- def text_content(self) -> typing.Optional[str]:
- """ElementHandle.text_content
- Returns the `node.textContent`.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.text_content()))
- def inner_text(self) -> str:
- """ElementHandle.inner_text
- Returns the `element.innerText`.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.inner_text()))
- def inner_html(self) -> str:
- """ElementHandle.inner_html
- Returns the `element.innerHTML`.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.inner_html()))
- def is_checked(self) -> bool:
- """ElementHandle.is_checked
- Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.is_checked()))
- def is_disabled(self) -> bool:
- """ElementHandle.is_disabled
- Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.is_disabled()))
- def is_editable(self) -> bool:
- """ElementHandle.is_editable
- Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.is_editable()))
- def is_enabled(self) -> bool:
- """ElementHandle.is_enabled
- Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.is_enabled()))
- def is_hidden(self) -> bool:
- """ElementHandle.is_hidden
- Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.is_hidden()))
- def is_visible(self) -> bool:
- """ElementHandle.is_visible
- Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.is_visible()))
- def dispatch_event(
- self, type: str, event_init: typing.Optional[typing.Dict] = None
- ) -> None:
- """ElementHandle.dispatch_event
- The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
- `click` is dispatched. This is equivalent to calling
- [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
- **Usage**
- ```py
- element_handle.dispatch_event(\"click\")
- ```
- Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
- properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
- Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
- - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
- - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
- - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
- - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
- - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
- - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
- - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
- - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
- ```py
- # note you can only create data_transfer in chromium and firefox
- data_transfer = page.evaluate_handle(\"new DataTransfer()\")
- element_handle.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
- ```
- Parameters
- ----------
- type : str
- DOM event type: `"click"`, `"dragstart"`, etc.
- event_init : Union[Dict, None]
- Optional event-specific initialization properties.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dispatch_event(
- type=type, eventInit=mapping.to_impl(event_init)
- )
- )
- )
- def scroll_into_view_if_needed(
- self, *, timeout: typing.Optional[float] = None
- ) -> None:
- """ElementHandle.scroll_into_view_if_needed
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
- it is completely visible as defined by
- [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
- Throws when `elementHandle` does not point to an element
- [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
- See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.scroll_into_view_if_needed(timeout=timeout))
- )
- def hover(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.hover
- This method hovers over the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.hover(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- force=force,
- trial=trial,
- )
- )
- )
- def click(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """ElementHandle.click
- This method clicks the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
- 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
- position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.click(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- clickCount=click_count,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- steps=steps,
- )
- )
- )
- def dblclick(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """ElementHandle.dblclick
- This method double clicks the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
- position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dblclick(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- steps=steps,
- )
- )
- )
- def select_option(
- self,
- value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- *,
- index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
- label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- element: typing.Optional[
- typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
- ] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> typing.List[str]:
- """ElementHandle.select_option
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
- the `<select>` element and selects these options.
- If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
- instead.
- Returns the array of option values that have been successfully selected.
- Triggers a `change` and `input` event once all the provided options have been selected.
- **Usage**
- ```py
- # Single selection matching the value or label
- handle.select_option(\"blue\")
- # single selection matching both the label
- handle.select_option(label=\"blue\")
- # multiple selection
- handle.select_option(value=[\"red\", \"green\", \"blue\"])
- ```
- Parameters
- ----------
- value : Union[Sequence[str], str, None]
- Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- index : Union[Sequence[int], int, None]
- Options to select by index. Optional.
- label : Union[Sequence[str], str, None]
- Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- element : Union[ElementHandle, Sequence[ElementHandle], None]
- Option elements to select. Optional.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.select_option(
- value=mapping.to_impl(value),
- index=mapping.to_impl(index),
- label=mapping.to_impl(label),
- element=mapping.to_impl(element),
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def tap(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.tap
- This method taps the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.tap(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def fill(
- self,
- value: str,
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.fill
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
- `input` event after filling. Note that you can pass an empty string to clear the input field.
- If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- error. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
- instead.
- To send fine-grained keyboard events, use `locator.press_sequentially()`.
- Parameters
- ----------
- value : str
- Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.fill(
- value=value, timeout=timeout, noWaitAfter=no_wait_after, force=force
- )
- )
- )
- def select_text(
- self,
- *,
- force: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """ElementHandle.select_text
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
- text content.
- If the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
- the control instead.
- Parameters
- ----------
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.select_text(force=force, timeout=timeout))
- )
- def input_value(self, *, timeout: typing.Optional[float] = None) -> str:
- """ElementHandle.input_value
- Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
- Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
- control.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.input_value(timeout=timeout))
- )
- def set_input_files(
- self,
- files: typing.Union[
- str,
- pathlib.Path,
- FilePayload,
- typing.Sequence[typing.Union[str, pathlib.Path]],
- typing.Sequence[FilePayload],
- ],
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.set_input_files
- Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
- they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
- with a `[webkitdirectory]` attribute, only a single directory path is supported.
- This method expects `ElementHandle` to point to an
- [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
- Parameters
- ----------
- files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_input_files(
- files=mapping.to_impl(files),
- timeout=timeout,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def focus(self) -> None:
- """ElementHandle.focus
- Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.focus()))
- def type(
- self,
- text: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.type
- Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
- text.
- To press a special key, like `Control` or `ArrowDown`, use `element_handle.press()`.
- **Usage**
- Parameters
- ----------
- text : str
- A text to type into a focused element.
- delay : Union[float, None]
- Time to wait between key presses in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.type(
- text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
- )
- )
- )
- def press(
- self,
- key: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.press
- Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
- `key` can specify the intended
- [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- to generate the text for. A superset of the `key` values can be found
- [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- etc.
- Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- `ControlOrMeta`.
- Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- texts.
- Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
- specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- Parameters
- ----------
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- delay : Union[float, None]
- Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.press(
- key=key, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
- )
- )
- )
- def set_checked(
- self,
- checked: bool,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.set_checked
- This method checks or unchecks an element by performing the following steps:
- 1. Ensure that element is a checkbox or a radio input. If not, this method throws.
- 1. If the element already has the right checked state, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked or unchecked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- checked : bool
- Whether to check or uncheck the checkbox.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_checked(
- checked=checked,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def check(
- self,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.check
- This method checks the element by performing the following steps:
- 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- checked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked. If not, this method throws.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.check(
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def uncheck(
- self,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """ElementHandle.uncheck
- This method checks the element by performing the following steps:
- 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- unchecked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now unchecked. If not, this method throws.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.uncheck(
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def bounding_box(self) -> typing.Optional[FloatRect]:
- """ElementHandle.bounding_box
- This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
- calculated relative to the main frame viewport - which is usually the same as the browser window.
- Scrolling affects the returned bounding box, similarly to
- [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
- That means `x` and/or `y` may be negative.
- Elements from child frames return the bounding box relative to the main frame, unlike the
- [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
- Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
- following snippet should click the center of the element.
- **Usage**
- ```py
- box = element_handle.bounding_box()
- page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
- ```
- Returns
- -------
- Union[{x: float, y: float, width: float, height: float}, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.bounding_box()))
- def screenshot(
- self,
- *,
- timeout: typing.Optional[float] = None,
- type: typing.Optional[Literal["jpeg", "png"]] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- quality: typing.Optional[int] = None,
- omit_background: typing.Optional[bool] = None,
- animations: typing.Optional[Literal["allow", "disabled"]] = None,
- caret: typing.Optional[Literal["hide", "initial"]] = None,
- scale: typing.Optional[Literal["css", "device"]] = None,
- mask: typing.Optional[typing.Sequence["Locator"]] = None,
- mask_color: typing.Optional[str] = None,
- style: typing.Optional[str] = None,
- ) -> bytes:
- """ElementHandle.screenshot
- This method captures a screenshot of the page, clipped to the size and position of this particular element. If the
- element is covered by other elements, it will not be actually visible on the screenshot. If the element is a
- scrollable container, only the currently scrolled content will be visible on the screenshot.
- This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
- a screenshot. If the element is detached from DOM, the method throws an error.
- Returns the buffer with the captured screenshot.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- type : Union["jpeg", "png", None]
- Specify screenshot type, defaults to `png`.
- path : Union[pathlib.Path, str, None]
- The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
- relative path, then it is resolved relative to the current working directory. If no path is provided, the image
- won't be saved to the disk.
- quality : Union[int, None]
- The quality of the image, between 0-100. Not applicable to `png` images.
- omit_background : Union[bool, None]
- Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
- Defaults to `false`.
- animations : Union["allow", "disabled", None]
- When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
- treatment depending on their duration:
- - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
- - infinite animations are canceled to initial state, and then played over after the screenshot.
- Defaults to `"allow"` that leaves animations untouched.
- caret : Union["hide", "initial", None]
- When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
- changed. Defaults to `"hide"`.
- scale : Union["css", "device", None]
- When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
- will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
- screenshots of high-dpi devices will be twice as large or even larger.
- Defaults to `"device"`.
- mask : Union[Sequence[Locator], None]
- Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
- box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
- invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
- that.
- mask_color : Union[str, None]
- Specify the color of the overlay box for masked elements, in
- [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
- style : Union[str, None]
- Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
- elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
- the Shadow DOM and applies to the inner frames.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.screenshot(
- timeout=timeout,
- type=type,
- path=path,
- quality=quality,
- omitBackground=omit_background,
- animations=animations,
- caret=caret,
- scale=scale,
- mask=mapping.to_impl(mask),
- maskColor=mask_color,
- style=style,
- )
- )
- )
- def query_selector(self, selector: str) -> typing.Optional["ElementHandle"]:
- """ElementHandle.query_selector
- The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
- the selector, returns `null`.
- Parameters
- ----------
- selector : str
- A selector to query for.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.query_selector(selector=selector))
- )
- def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
- """ElementHandle.query_selector_all
- The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
- the selector, returns empty array.
- Parameters
- ----------
- selector : str
- A selector to query for.
- Returns
- -------
- List[ElementHandle]
- """
- return mapping.from_impl_list(
- self._sync(self._impl_obj.query_selector_all(selector=selector))
- )
- def eval_on_selector(
- self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """ElementHandle.eval_on_selector
- Returns the return value of `expression`.
- The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
- first argument to `expression`. If no elements match the selector, the method throws an error.
- If `expression` returns a [Promise], then `element_handle.eval_on_selector()` would wait for the promise to
- resolve and return its value.
- **Usage**
- ```py
- tweet_handle = page.query_selector(\".tweet\")
- assert tweet_handle.eval_on_selector(\".like\", \"node => node.innerText\") == \"100\"
- assert tweet_handle.eval_on_selector(\".retweets\", \"node => node.innerText\") == \"10\"
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.eval_on_selector(
- selector=selector, expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def eval_on_selector_all(
- self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """ElementHandle.eval_on_selector_all
- Returns the return value of `expression`.
- The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
- of matched elements as a first argument to `expression`.
- If `expression` returns a [Promise], then `element_handle.eval_on_selector_all()` would wait for the promise to
- resolve and return its value.
- **Usage**
- ```html
- <div class=\"feed\">
- <div class=\"tweet\">Hello!</div>
- <div class=\"tweet\">Hi!</div>
- </div>
- ```
- ```py
- feed_handle = page.query_selector(\".feed\")
- assert feed_handle.eval_on_selector_all(\".tweet\", \"nodes => nodes.map(n => n.innerText)\") == [\"hello!\", \"hi!\"]
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.eval_on_selector_all(
- selector=selector, expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def wait_for_element_state(
- self,
- state: Literal[
- "disabled", "editable", "enabled", "hidden", "stable", "visible"
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """ElementHandle.wait_for_element_state
- Returns when the element satisfies the `state`.
- Depending on the `state` parameter, this method waits for one of the [actionability](https://playwright.dev/python/docs/actionability) checks to
- pass. This method throws when the element is detached while waiting, unless waiting for the `\"hidden\"` state.
- - `\"visible\"` Wait until the element is [visible](https://playwright.dev/python/docs/actionability#visible).
- - `\"hidden\"` Wait until the element is [not visible](https://playwright.dev/python/docs/actionability#visible) or not attached. Note that
- waiting for hidden does not throw when the element detaches.
- - `\"stable\"` Wait until the element is both [visible](https://playwright.dev/python/docs/actionability#visible) and
- [stable](https://playwright.dev/python/docs/actionability#stable).
- - `\"enabled\"` Wait until the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
- - `\"disabled\"` Wait until the element is [not enabled](https://playwright.dev/python/docs/actionability#enabled).
- - `\"editable\"` Wait until the element is [editable](https://playwright.dev/python/docs/actionability#editable).
- If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
- Parameters
- ----------
- state : Union["disabled", "editable", "enabled", "hidden", "stable", "visible"]
- A state to wait for, see below for more details.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.wait_for_element_state(state=state, timeout=timeout)
- )
- )
- def wait_for_selector(
- self,
- selector: str,
- *,
- state: typing.Optional[
- Literal["attached", "detached", "hidden", "visible"]
- ] = None,
- timeout: typing.Optional[float] = None,
- strict: typing.Optional[bool] = None,
- ) -> typing.Optional["ElementHandle"]:
- """ElementHandle.wait_for_selector
- Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
- `detached`.
- Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
- or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
- method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
- function will throw.
- **Usage**
- ```py
- page.set_content(\"<div><span></span></div>\")
- div = page.query_selector(\"div\")
- # waiting for the \"span\" selector relative to the div.
- span = div.wait_for_selector(\"span\", state=\"attached\")
- ```
- **NOTE** This method does not work across navigations, use `page.wait_for_selector()` instead.
- Parameters
- ----------
- selector : str
- A selector to query for.
- state : Union["attached", "detached", "hidden", "visible", None]
- Defaults to `'visible'`. Can be either:
- - `'attached'` - wait for element to be present in DOM.
- - `'detached'` - wait for element to not be present in DOM.
- - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
- without any content or with `display:none` has an empty bounding box and is not considered visible.
- - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
- `visibility:hidden`. This is opposite to the `'visible'` option.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(
- self._sync(
- self._impl_obj.wait_for_selector(
- selector=selector, state=state, timeout=timeout, strict=strict
- )
- )
- )
- mapping.register(ElementHandleImpl, ElementHandle)
- class FileChooser(SyncBase):
- @property
- def page(self) -> "Page":
- """FileChooser.page
- Returns page this file chooser belongs to.
- Returns
- -------
- Page
- """
- return mapping.from_impl(self._impl_obj.page)
- @property
- def element(self) -> "ElementHandle":
- """FileChooser.element
- Returns input element associated with this file chooser.
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(self._impl_obj.element)
- def is_multiple(self) -> bool:
- """FileChooser.is_multiple
- Returns whether this file chooser accepts multiple files.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.is_multiple())
- def set_files(
- self,
- files: typing.Union[
- str,
- pathlib.Path,
- FilePayload,
- typing.Sequence[typing.Union[str, pathlib.Path]],
- typing.Sequence[FilePayload],
- ],
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """FileChooser.set_files
- Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,
- then they are resolved relative to the current working directory. For empty array, clears the selected files.
- Parameters
- ----------
- files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_files(
- files=mapping.to_impl(files),
- timeout=timeout,
- noWaitAfter=no_wait_after,
- )
- )
- )
- mapping.register(FileChooserImpl, FileChooser)
- class Frame(SyncBase):
- @property
- def page(self) -> "Page":
- """Frame.page
- Returns the page containing this frame.
- Returns
- -------
- Page
- """
- return mapping.from_impl(self._impl_obj.page)
- @property
- def name(self) -> str:
- """Frame.name
- Returns frame's name attribute as specified in the tag.
- If the name is empty, returns the id attribute instead.
- **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed
- later.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.name)
- @property
- def url(self) -> str:
- """Frame.url
- Returns frame's url.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- @property
- def parent_frame(self) -> typing.Optional["Frame"]:
- """Frame.parent_frame
- Parent frame, if any. Detached frames and main frames return `null`.
- Returns
- -------
- Union[Frame, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.parent_frame)
- @property
- def child_frames(self) -> typing.List["Frame"]:
- """Frame.child_frames
- Returns
- -------
- List[Frame]
- """
- return mapping.from_impl_list(self._impl_obj.child_frames)
- def goto(
- self,
- url: str,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- referer: typing.Optional[str] = None,
- ) -> typing.Optional["Response"]:
- """Frame.goto
- Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
- the last redirect.
- The method will throw an error if:
- - there's an SSL error (e.g. in case of self-signed certificates).
- - target URL is invalid.
- - the `timeout` is exceeded during navigation.
- - the remote server does not respond or is unreachable.
- - the main resource failed to load.
- The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
- \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
- `response.status()`.
- **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
- to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
- **NOTE** Headless mode doesn't support navigation to a PDF document. See the
- [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
- Parameters
- ----------
- url : str
- URL to navigate frame to. The url should include scheme, e.g. `https://`.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- referer : Union[str, None]
- Referer header value. If provided it will take preference over the referer header value set by
- `page.set_extra_http_headers()`.
- Returns
- -------
- Union[Response, None]
- """
- return mapping.from_impl_nullable(
- self._sync(
- self._impl_obj.goto(
- url=url, timeout=timeout, waitUntil=wait_until, referer=referer
- )
- )
- )
- def expect_navigation(
- self,
- *,
- url: typing.Optional[
- typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
- ] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Response"]:
- """Frame.expect_navigation
- Waits for the frame navigation and returns the main resource response. In case of multiple redirects, the
- navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
- navigation due to History API usage, the navigation will resolve with `null`.
- **Usage**
- This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly
- cause the frame to navigate. Consider this example:
- ```py
- with frame.expect_navigation():
- frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
- # Resolves after navigation has finished
- ```
- **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
- is considered a navigation.
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str, None]
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- equal to the string.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- Returns
- -------
- EventContextManager[Response]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_navigation(
- url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
- ).future,
- )
- def wait_for_url(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- *,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Frame.wait_for_url
- Waits for the frame to navigate to the given URL.
- **Usage**
- ```py
- frame.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
- frame.wait_for_url(\"**/target.html\")
- ```
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- equal to the string.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.wait_for_url(
- url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
- )
- )
- )
- def wait_for_load_state(
- self,
- state: typing.Optional[
- Literal["domcontentloaded", "load", "networkidle"]
- ] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Frame.wait_for_load_state
- Waits for the required load state to be reached.
- This returns when the frame reaches a required load state, `load` by default. The navigation must have been
- committed when this method is called. If current document has already reached the required state, resolves
- immediately.
- **NOTE** Most of the time, this method is not needed because Playwright
- [auto-waits before every action](https://playwright.dev/python/docs/actionability).
- **Usage**
- ```py
- frame.click(\"button\") # click triggers navigation.
- frame.wait_for_load_state() # the promise resolves after \"load\" event.
- ```
- Parameters
- ----------
- state : Union["domcontentloaded", "load", "networkidle", None]
- Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
- document, the method resolves immediately. Can be one of:
- - `'load'` - wait for the `load` event to be fired.
- - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
- - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
- this method for testing, rely on web assertions to assess readiness instead.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.wait_for_load_state(state=state, timeout=timeout))
- )
- def frame_element(self) -> "ElementHandle":
- """Frame.frame_element
- Returns the `frame` or `iframe` element handle which corresponds to this frame.
- This is an inverse of `element_handle.content_frame()`. Note that returned handle actually belongs to the
- parent frame.
- This method throws an error if the frame has been detached before `frameElement()` returns.
- **Usage**
- ```py
- frame_element = frame.frame_element()
- content_frame = frame_element.content_frame()
- assert frame == content_frame
- ```
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(self._sync(self._impl_obj.frame_element()))
- def evaluate(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """Frame.evaluate
- Returns the return value of `expression`.
- If the function passed to the `frame.evaluate()` returns a [Promise], then `frame.evaluate()` would
- wait for the promise to resolve and return its value.
- If the function passed to the `frame.evaluate()` returns a non-[Serializable] value, then
- `frame.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
- are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
- **Usage**
- ```py
- result = frame.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
- print(result) # prints \"56\"
- ```
- A string can also be passed in instead of a function.
- ```py
- print(frame.evaluate(\"1 + 2\")) # prints \"3\"
- x = 10
- print(frame.evaluate(f\"1 + {x}\")) # prints \"11\"
- ```
- `ElementHandle` instances can be passed as an argument to the `frame.evaluate()`:
- ```py
- body_handle = frame.evaluate(\"document.body\")
- html = frame.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
- body_handle.dispose()
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
- )
- )
- def evaluate_handle(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> "JSHandle":
- """Frame.evaluate_handle
- Returns the return value of `expression` as a `JSHandle`.
- The only difference between `frame.evaluate()` and `frame.evaluate_handle()` is that
- `frame.evaluate_handle()` returns `JSHandle`.
- If the function, passed to the `frame.evaluate_handle()`, returns a [Promise], then
- `frame.evaluate_handle()` would wait for the promise to resolve and return its value.
- **Usage**
- ```py
- a_window_handle = frame.evaluate_handle(\"Promise.resolve(window)\")
- a_window_handle # handle for the window object.
- ```
- A string can also be passed in instead of a function.
- ```py
- a_handle = page.evaluate_handle(\"document\") # handle for the \"document\"
- ```
- `JSHandle` instances can be passed as an argument to the `frame.evaluate_handle()`:
- ```py
- a_handle = page.evaluate_handle(\"document.body\")
- result_handle = page.evaluate_handle(\"body => body.innerHTML\", a_handle)
- print(result_handle.json_value())
- result_handle.dispose()
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.evaluate_handle(
- expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def query_selector(
- self, selector: str, *, strict: typing.Optional[bool] = None
- ) -> typing.Optional["ElementHandle"]:
- """Frame.query_selector
- Returns the ElementHandle pointing to the frame element.
- **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects and web-first assertions instead.
- The method finds an element matching the specified selector within the frame. If no elements match the selector,
- returns `null`.
- Parameters
- ----------
- selector : str
- A selector to query for.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.query_selector(selector=selector, strict=strict))
- )
- def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
- """Frame.query_selector_all
- Returns the ElementHandles pointing to the frame elements.
- **NOTE** The use of `ElementHandle` is discouraged, use `Locator` objects instead.
- The method finds all elements matching the specified selector within the frame. If no elements match the selector,
- returns empty array.
- Parameters
- ----------
- selector : str
- A selector to query for.
- Returns
- -------
- List[ElementHandle]
- """
- return mapping.from_impl_list(
- self._sync(self._impl_obj.query_selector_all(selector=selector))
- )
- def wait_for_selector(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- state: typing.Optional[
- Literal["attached", "detached", "hidden", "visible"]
- ] = None,
- ) -> typing.Optional["ElementHandle"]:
- """Frame.wait_for_selector
- Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
- `detached`.
- **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
- objects and web-first assertions make the code wait-for-selector-free.
- Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
- at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
- If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
- **Usage**
- This method works across navigations:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- chromium = playwright.chromium
- browser = chromium.launch()
- page = browser.new_page()
- for current_url in [\"https://google.com\", \"https://bbc.com\"]:
- page.goto(current_url, wait_until=\"domcontentloaded\")
- element = page.main_frame.wait_for_selector(\"img\")
- print(\"Loaded image: \" + str(element.get_attribute(\"src\")))
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- state : Union["attached", "detached", "hidden", "visible", None]
- Defaults to `'visible'`. Can be either:
- - `'attached'` - wait for element to be present in DOM.
- - `'detached'` - wait for element to not be present in DOM.
- - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
- without any content or with `display:none` has an empty bounding box and is not considered visible.
- - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
- `visibility:hidden`. This is opposite to the `'visible'` option.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(
- self._sync(
- self._impl_obj.wait_for_selector(
- selector=selector, strict=strict, timeout=timeout, state=state
- )
- )
- )
- def is_checked(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Frame.is_checked
- Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_checked(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_disabled(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Frame.is_disabled
- Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_disabled(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_editable(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Frame.is_editable
- Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_editable(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_enabled(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Frame.is_enabled
- Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_enabled(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_hidden(self, selector: str, *, strict: typing.Optional[bool] = None) -> bool:
- """Frame.is_hidden
- Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
- does not match any elements is considered hidden.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_hidden(selector=selector, strict=strict))
- )
- def is_visible(
- self, selector: str, *, strict: typing.Optional[bool] = None
- ) -> bool:
- """Frame.is_visible
- Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
- is considered not visible.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_visible(selector=selector, strict=strict))
- )
- def dispatch_event(
- self,
- selector: str,
- type: str,
- event_init: typing.Optional[typing.Dict] = None,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Frame.dispatch_event
- The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
- `click` is dispatched. This is equivalent to calling
- [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
- **Usage**
- ```py
- frame.dispatch_event(\"button#submit\", \"click\")
- ```
- Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
- properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
- Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
- - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
- - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
- - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
- - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
- - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
- - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
- - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
- - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
- ```py
- # note you can only create data_transfer in chromium and firefox
- data_transfer = frame.evaluate_handle(\"new DataTransfer()\")
- frame.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
- ```
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- type : str
- DOM event type: `"click"`, `"dragstart"`, etc.
- event_init : Union[Dict, None]
- Optional event-specific initialization properties.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dispatch_event(
- selector=selector,
- type=type,
- eventInit=mapping.to_impl(event_init),
- strict=strict,
- timeout=timeout,
- )
- )
- )
- def eval_on_selector(
- self,
- selector: str,
- expression: str,
- arg: typing.Optional[typing.Any] = None,
- *,
- strict: typing.Optional[bool] = None,
- ) -> typing.Any:
- """Frame.eval_on_selector
- Returns the return value of `expression`.
- The method finds an element matching the specified selector within the frame and passes it as a first argument to
- `expression`. If no elements match the selector, the method throws an error.
- If `expression` returns a [Promise], then `frame.eval_on_selector()` would wait for the promise to resolve
- and return its value.
- **Usage**
- ```py
- search_value = frame.eval_on_selector(\"#search\", \"el => el.value\")
- preload_href = frame.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
- html = frame.eval_on_selector(\".main-container\", \"(e, suffix) => e.outerHTML + suffix\", \"hello\")
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.eval_on_selector(
- selector=selector,
- expression=expression,
- arg=mapping.to_impl(arg),
- strict=strict,
- )
- )
- )
- def eval_on_selector_all(
- self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """Frame.eval_on_selector_all
- Returns the return value of `expression`.
- The method finds all elements matching the specified selector within the frame and passes an array of matched
- elements as a first argument to `expression`.
- If `expression` returns a [Promise], then `frame.eval_on_selector_all()` would wait for the promise to resolve
- and return its value.
- **Usage**
- ```py
- divs_counts = frame.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.eval_on_selector_all(
- selector=selector, expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def content(self) -> str:
- """Frame.content
- Gets the full HTML contents of the frame, including the doctype.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.content()))
- def set_content(
- self,
- html: str,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- ) -> None:
- """Frame.set_content
- This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
- inheriting all its specific characteristics and behaviors.
- Parameters
- ----------
- html : str
- HTML markup to assign to the page.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_content(
- html=html, timeout=timeout, waitUntil=wait_until
- )
- )
- )
- def is_detached(self) -> bool:
- """Frame.is_detached
- Returns `true` if the frame has been detached, or `false` otherwise.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.is_detached())
- def add_script_tag(
- self,
- *,
- url: typing.Optional[str] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- content: typing.Optional[str] = None,
- type: typing.Optional[str] = None,
- ) -> "ElementHandle":
- """Frame.add_script_tag
- Returns the added tag when the script's onload fires or when the script content was injected into frame.
- Adds a `<script>` tag into the page with the desired url or content.
- Parameters
- ----------
- url : Union[str, None]
- URL of a script to be added.
- path : Union[pathlib.Path, str, None]
- Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
- to the current working directory.
- content : Union[str, None]
- Raw JavaScript content to be injected into frame.
- type : Union[str, None]
- Script type. Use 'module' in order to load a JavaScript ES6 module. See
- [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.add_script_tag(
- url=url, path=path, content=content, type=type
- )
- )
- )
- def add_style_tag(
- self,
- *,
- url: typing.Optional[str] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- content: typing.Optional[str] = None,
- ) -> "ElementHandle":
- """Frame.add_style_tag
- Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
- Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
- content.
- Parameters
- ----------
- url : Union[str, None]
- URL of the `<link>` tag.
- path : Union[pathlib.Path, str, None]
- Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
- current working directory.
- content : Union[str, None]
- Raw CSS content to be injected into frame.
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.add_style_tag(url=url, path=path, content=content)
- )
- )
- def click(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.click
- This method clicks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
- 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.click(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- clickCount=click_count,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def dblclick(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.dblclick
- This method double clicks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to double click in the center of the element, or the specified `position`. if
- the first click of the `dblclick()` triggers a navigation event, this method will throw.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dblclick(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def tap(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.tap
- This method taps an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.tap(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def fill(
- self,
- selector: str,
- value: str,
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> None:
- """Frame.fill
- This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
- focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
- to clear the input field.
- If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- error. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
- instead.
- To send fine-grained keyboard events, use `locator.press_sequentially()`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- value : str
- Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.fill(
- selector=selector,
- value=value,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- strict=strict,
- force=force,
- )
- )
- )
- def locator(
- self,
- selector: str,
- *,
- has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has: typing.Optional["Locator"] = None,
- has_not: typing.Optional["Locator"] = None,
- ) -> "Locator":
- """Frame.locator
- The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
- to the element immediately before performing an action, so a series of actions on the same locator can in fact be
- performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
- [Learn more about locators](https://playwright.dev/python/docs/locators).
- [Learn more about locators](https://playwright.dev/python/docs/locators).
- Parameters
- ----------
- selector : str
- A selector to use when resolving DOM element.
- has_text : Union[Pattern[str], str, None]
- Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- `<article><div>Playwright</div></article>`.
- has_not_text : Union[Pattern[str], str, None]
- Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- When passed a [string], matching is case-insensitive and searches for a substring.
- has : Union[Locator, None]
- Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- the document root. For example, you can find `content` that has `div` in
- `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- has_not : Union[Locator, None]
- Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.locator(
- selector=selector,
- hasText=has_text,
- hasNotText=has_not_text,
- has=has._impl_obj if has else None,
- hasNot=has_not._impl_obj if has_not else None,
- )
- )
- def get_by_alt_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Frame.get_by_alt_text
- Allows locating elements by their alt text.
- **Usage**
- For example, this method will find the image by alt text \"Playwright logo\":
- ```html
- <img alt='Playwright logo'>
- ```
- ```py
- page.get_by_alt_text(\"Playwright logo\").click()
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
- def get_by_label(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Frame.get_by_label
- Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
- `aria-label` attribute.
- **Usage**
- For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
- ```html
- <input aria-label=\"Username\">
- <label for=\"password-input\">Password:</label>
- <input id=\"password-input\">
- ```
- ```py
- page.get_by_label(\"Username\").fill(\"john\")
- page.get_by_label(\"Password\").fill(\"secret\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
- def get_by_placeholder(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Frame.get_by_placeholder
- Allows locating input elements by the placeholder text.
- **Usage**
- For example, consider the following DOM structure.
- ```html
- <input type=\"email\" placeholder=\"name@example.com\" />
- ```
- You can fill the input after locating it by the placeholder text:
- ```py
- page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_placeholder(text=text, exact=exact)
- )
- def get_by_role(
- self,
- role: Literal[
- "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",
- ],
- *,
- checked: typing.Optional[bool] = None,
- disabled: typing.Optional[bool] = None,
- expanded: typing.Optional[bool] = None,
- include_hidden: typing.Optional[bool] = None,
- level: typing.Optional[int] = None,
- name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- pressed: typing.Optional[bool] = None,
- selected: typing.Optional[bool] = None,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Frame.get_by_role
- Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
- [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- **Usage**
- Consider the following DOM structure.
- ```html
- <h3>Sign up</h3>
- <label>
- <input type=\"checkbox\" /> Subscribe
- </label>
- <br/>
- <button>Submit</button>
- ```
- You can locate each element by it's implicit role:
- ```py
- expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
- page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
- page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
- ```
- **Details**
- Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
- about the ARIA guidelines.
- Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
- that is recognized by the role selector. You can find all the
- [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
- duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
- Parameters
- ----------
- 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"]
- Required aria role.
- checked : Union[bool, None]
- An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
- Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
- disabled : Union[bool, None]
- An attribute that is usually set by `aria-disabled` or `disabled`.
- **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
- [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
- expanded : Union[bool, None]
- An attribute that is usually set by `aria-expanded`.
- Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
- include_hidden : Union[bool, None]
- Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
- [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
- Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
- level : Union[int, None]
- A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
- for `<h1>-<h6>` elements.
- Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
- name : Union[Pattern[str], str, None]
- Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
- case-insensitive and searches for a substring, use `exact` to control this behavior.
- Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- pressed : Union[bool, None]
- An attribute that is usually set by `aria-pressed`.
- Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
- selected : Union[bool, None]
- An attribute that is usually set by `aria-selected`.
- Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
- exact : Union[bool, None]
- Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_role(
- role=role,
- checked=checked,
- disabled=disabled,
- expanded=expanded,
- includeHidden=include_hidden,
- level=level,
- name=name,
- pressed=pressed,
- selected=selected,
- exact=exact,
- )
- )
- def get_by_test_id(
- self, test_id: typing.Union[str, typing.Pattern[str]]
- ) -> "Locator":
- """Frame.get_by_test_id
- Locate element by the test id.
- **Usage**
- Consider the following DOM structure.
- ```html
- <button data-testid=\"directions\">Itinéraire</button>
- ```
- You can locate the element by it's test id:
- ```py
- page.get_by_test_id(\"directions\").click()
- ```
- **Details**
- By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
- configure a different test id attribute if necessary.
- Parameters
- ----------
- test_id : Union[Pattern[str], str]
- Id to locate the element by.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
- def get_by_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Frame.get_by_text
- Allows locating elements that contain given text.
- See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
- filter by the text content.
- **Usage**
- Consider the following DOM structure:
- ```html
- <div>Hello <span>world</span></div>
- <div>Hello</div>
- ```
- You can locate by text substring, exact string, or a regular expression:
- ```py
- # Matches <span>
- page.get_by_text(\"world\")
- # Matches first <div>
- page.get_by_text(\"Hello world\")
- # Matches second <div>
- page.get_by_text(\"Hello\", exact=True)
- # Matches both <div>s
- page.get_by_text(re.compile(\"Hello\"))
- # Matches second <div>
- page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
- ```
- **Details**
- Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
- one, turns line breaks into spaces and ignores leading and trailing whitespace.
- Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
- example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
- def get_by_title(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Frame.get_by_title
- Allows locating elements by their title attribute.
- **Usage**
- Consider the following DOM structure.
- ```html
- <span title='Issues count'>25 issues</span>
- ```
- You can check the issues count after locating it by the title text:
- ```py
- expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
- def frame_locator(self, selector: str) -> "FrameLocator":
- """Frame.frame_locator
- When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
- in that iframe.
- **Usage**
- Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
- id=\"my-frame\">`:
- ```py
- locator = frame.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
- locator.click()
- ```
- Parameters
- ----------
- selector : str
- A selector to use when resolving DOM element.
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
- def focus(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Frame.focus
- This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
- method waits until a matching element appears in the DOM.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.focus(selector=selector, strict=strict, timeout=timeout)
- )
- )
- def text_content(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> typing.Optional[str]:
- """Frame.text_content
- Returns `element.textContent`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.text_content(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def inner_text(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> str:
- """Frame.inner_text
- Returns `element.innerText`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.inner_text(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def inner_html(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> str:
- """Frame.inner_html
- Returns `element.innerHTML`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.inner_html(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def get_attribute(
- self,
- selector: str,
- name: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> typing.Optional[str]:
- """Frame.get_attribute
- Returns element attribute value.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- name : str
- Attribute name to get the value for.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.get_attribute(
- selector=selector, name=name, strict=strict, timeout=timeout
- )
- )
- )
- def hover(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.hover
- This method hovers over an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.hover(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- force=force,
- strict=strict,
- trial=trial,
- )
- )
- )
- def drag_and_drop(
- self,
- source: str,
- target: str,
- *,
- source_position: typing.Optional[Position] = None,
- target_position: typing.Optional[Position] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- trial: typing.Optional[bool] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """Frame.drag_and_drop
- Parameters
- ----------
- source : str
- A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
- be used.
- target : str
- A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
- will be used.
- source_position : Union[{x: float, y: float}, None]
- Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
- specified, some visible point of the element is used.
- target_position : Union[{x: float, y: float}, None]
- Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
- specified, some visible point of the element is used.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
- of the drag. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.drag_and_drop(
- source=source,
- target=target,
- sourcePosition=source_position,
- targetPosition=target_position,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- timeout=timeout,
- trial=trial,
- steps=steps,
- )
- )
- )
- def select_option(
- self,
- selector: str,
- value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- *,
- index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
- label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- element: typing.Optional[
- typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
- ] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> typing.List[str]:
- """Frame.select_option
- This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
- until all specified options are present in the `<select>` element and selects these options.
- If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
- instead.
- Returns the array of option values that have been successfully selected.
- Triggers a `change` and `input` event once all the provided options have been selected.
- **Usage**
- ```py
- # Single selection matching the value or label
- frame.select_option(\"select#colors\", \"blue\")
- # single selection matching both the label
- frame.select_option(\"select#colors\", label=\"blue\")
- # multiple selection
- frame.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- value : Union[Sequence[str], str, None]
- Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- index : Union[Sequence[int], int, None]
- Options to select by index. Optional.
- label : Union[Sequence[str], str, None]
- Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- element : Union[ElementHandle, Sequence[ElementHandle], None]
- Option elements to select. Optional.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.select_option(
- selector=selector,
- value=mapping.to_impl(value),
- index=mapping.to_impl(index),
- label=mapping.to_impl(label),
- element=mapping.to_impl(element),
- timeout=timeout,
- noWaitAfter=no_wait_after,
- strict=strict,
- force=force,
- )
- )
- )
- def input_value(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> str:
- """Frame.input_value
- Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
- Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
- control.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.input_value(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def set_input_files(
- self,
- selector: str,
- files: typing.Union[
- str,
- pathlib.Path,
- FilePayload,
- typing.Sequence[typing.Union[str, pathlib.Path]],
- typing.Sequence[FilePayload],
- ],
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Frame.set_input_files
- Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
- they are resolved relative to the current working directory. For empty array, clears the selected files.
- This method expects `selector` to point to an
- [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_input_files(
- selector=selector,
- files=mapping.to_impl(files),
- strict=strict,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def type(
- self,
- selector: str,
- text: str,
- *,
- delay: typing.Optional[float] = None,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Frame.type
- Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used
- to send fine-grained keyboard events. To fill values in form fields, use `frame.fill()`.
- To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
- **Usage**
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- text : str
- A text to type into a focused element.
- delay : Union[float, None]
- Time to wait between key presses in milliseconds. Defaults to 0.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.type(
- selector=selector,
- text=text,
- delay=delay,
- strict=strict,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def press(
- self,
- selector: str,
- key: str,
- *,
- delay: typing.Optional[float] = None,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Frame.press
- `key` can specify the intended
- [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- to generate the text for. A superset of the `key` values can be found
- [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- etc.
- Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
- Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- texts.
- Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
- specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- delay : Union[float, None]
- Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.press(
- selector=selector,
- key=key,
- delay=delay,
- strict=strict,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def check(
- self,
- selector: str,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.check
- This method checks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
- already checked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.check(
- selector=selector,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def uncheck(
- self,
- selector: str,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.uncheck
- This method checks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
- already unchecked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now unchecked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.uncheck(
- selector=selector,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def wait_for_timeout(self, timeout: float) -> None:
- """Frame.wait_for_timeout
- Waits for the given `timeout` in milliseconds.
- Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
- to be flaky. Use signals such as network events, selectors becoming visible and others instead.
- Parameters
- ----------
- timeout : float
- A timeout to wait for
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.wait_for_timeout(timeout=timeout))
- )
- def wait_for_function(
- self,
- expression: str,
- *,
- arg: typing.Optional[typing.Any] = None,
- timeout: typing.Optional[float] = None,
- polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
- ) -> "JSHandle":
- """Frame.wait_for_function
- Returns when the `expression` returns a truthy value, returns that value.
- **Usage**
- The `frame.wait_for_function()` can be used to observe viewport size change:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- webkit = playwright.webkit
- browser = webkit.launch()
- page = browser.new_page()
- page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
- page.main_frame.wait_for_function(\"() => window.x > 0\")
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- To pass an argument to the predicate of `frame.waitForFunction` function:
- ```py
- selector = \".foo\"
- frame.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()` or
- `page.set_default_timeout()` methods.
- polling : Union["raf", float, None]
- If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
- is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
- `raf`.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.wait_for_function(
- expression=expression,
- arg=mapping.to_impl(arg),
- timeout=timeout,
- polling=polling,
- )
- )
- )
- def title(self) -> str:
- """Frame.title
- Returns the page title.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.title()))
- def set_checked(
- self,
- selector: str,
- checked: bool,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Frame.set_checked
- This method checks or unchecks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- 1. If the element already has the right checked state, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked or unchecked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- checked : bool
- Whether to check or uncheck the checkbox.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_checked(
- selector=selector,
- checked=checked,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- mapping.register(FrameImpl, Frame)
- class FrameLocator(SyncBase):
- @property
- def first(self) -> "FrameLocator":
- """FrameLocator.first
- Returns locator to the first matching frame.
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.first)
- @property
- def last(self) -> "FrameLocator":
- """FrameLocator.last
- Returns locator to the last matching frame.
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.last)
- @property
- def owner(self) -> "Locator":
- """FrameLocator.owner
- Returns a `Locator` object pointing to the same `iframe` as this frame locator.
- Useful when you have a `FrameLocator` object obtained somewhere, and later on would like to interact with the
- `iframe` element.
- For a reverse operation, use `locator.content_frame()`.
- **Usage**
- ```py
- frame_locator = page.locator(\"iframe[name=\\\"embedded\\\"]\").content_frame
- # ...
- locator = frame_locator.owner
- expect(locator).to_be_visible()
- ```
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.owner)
- def locator(
- self,
- selector_or_locator: typing.Union["Locator", str],
- *,
- has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has: typing.Optional["Locator"] = None,
- has_not: typing.Optional["Locator"] = None,
- ) -> "Locator":
- """FrameLocator.locator
- The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
- options, similar to `locator.filter()` method.
- [Learn more about locators](https://playwright.dev/python/docs/locators).
- Parameters
- ----------
- selector_or_locator : Union[Locator, str]
- A selector or locator to use when resolving DOM element.
- has_text : Union[Pattern[str], str, None]
- Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- `<article><div>Playwright</div></article>`.
- has_not_text : Union[Pattern[str], str, None]
- Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- When passed a [string], matching is case-insensitive and searches for a substring.
- has : Union[Locator, None]
- Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- the document root. For example, you can find `content` that has `div` in
- `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- has_not : Union[Locator, None]
- Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.locator(
- selectorOrLocator=selector_or_locator,
- hasText=has_text,
- hasNotText=has_not_text,
- has=has._impl_obj if has else None,
- hasNot=has_not._impl_obj if has_not else None,
- )
- )
- def get_by_alt_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """FrameLocator.get_by_alt_text
- Allows locating elements by their alt text.
- **Usage**
- For example, this method will find the image by alt text \"Playwright logo\":
- ```html
- <img alt='Playwright logo'>
- ```
- ```py
- page.get_by_alt_text(\"Playwright logo\").click()
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
- def get_by_label(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """FrameLocator.get_by_label
- Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
- `aria-label` attribute.
- **Usage**
- For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
- ```html
- <input aria-label=\"Username\">
- <label for=\"password-input\">Password:</label>
- <input id=\"password-input\">
- ```
- ```py
- page.get_by_label(\"Username\").fill(\"john\")
- page.get_by_label(\"Password\").fill(\"secret\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
- def get_by_placeholder(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """FrameLocator.get_by_placeholder
- Allows locating input elements by the placeholder text.
- **Usage**
- For example, consider the following DOM structure.
- ```html
- <input type=\"email\" placeholder=\"name@example.com\" />
- ```
- You can fill the input after locating it by the placeholder text:
- ```py
- page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_placeholder(text=text, exact=exact)
- )
- def get_by_role(
- self,
- role: Literal[
- "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",
- ],
- *,
- checked: typing.Optional[bool] = None,
- disabled: typing.Optional[bool] = None,
- expanded: typing.Optional[bool] = None,
- include_hidden: typing.Optional[bool] = None,
- level: typing.Optional[int] = None,
- name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- pressed: typing.Optional[bool] = None,
- selected: typing.Optional[bool] = None,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """FrameLocator.get_by_role
- Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
- [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- **Usage**
- Consider the following DOM structure.
- ```html
- <h3>Sign up</h3>
- <label>
- <input type=\"checkbox\" /> Subscribe
- </label>
- <br/>
- <button>Submit</button>
- ```
- You can locate each element by it's implicit role:
- ```py
- expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
- page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
- page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
- ```
- **Details**
- Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
- about the ARIA guidelines.
- Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
- that is recognized by the role selector. You can find all the
- [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
- duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
- Parameters
- ----------
- 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"]
- Required aria role.
- checked : Union[bool, None]
- An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
- Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
- disabled : Union[bool, None]
- An attribute that is usually set by `aria-disabled` or `disabled`.
- **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
- [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
- expanded : Union[bool, None]
- An attribute that is usually set by `aria-expanded`.
- Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
- include_hidden : Union[bool, None]
- Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
- [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
- Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
- level : Union[int, None]
- A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
- for `<h1>-<h6>` elements.
- Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
- name : Union[Pattern[str], str, None]
- Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
- case-insensitive and searches for a substring, use `exact` to control this behavior.
- Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- pressed : Union[bool, None]
- An attribute that is usually set by `aria-pressed`.
- Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
- selected : Union[bool, None]
- An attribute that is usually set by `aria-selected`.
- Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
- exact : Union[bool, None]
- Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_role(
- role=role,
- checked=checked,
- disabled=disabled,
- expanded=expanded,
- includeHidden=include_hidden,
- level=level,
- name=name,
- pressed=pressed,
- selected=selected,
- exact=exact,
- )
- )
- def get_by_test_id(
- self, test_id: typing.Union[str, typing.Pattern[str]]
- ) -> "Locator":
- """FrameLocator.get_by_test_id
- Locate element by the test id.
- **Usage**
- Consider the following DOM structure.
- ```html
- <button data-testid=\"directions\">Itinéraire</button>
- ```
- You can locate the element by it's test id:
- ```py
- page.get_by_test_id(\"directions\").click()
- ```
- **Details**
- By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
- configure a different test id attribute if necessary.
- Parameters
- ----------
- test_id : Union[Pattern[str], str]
- Id to locate the element by.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
- def get_by_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """FrameLocator.get_by_text
- Allows locating elements that contain given text.
- See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
- filter by the text content.
- **Usage**
- Consider the following DOM structure:
- ```html
- <div>Hello <span>world</span></div>
- <div>Hello</div>
- ```
- You can locate by text substring, exact string, or a regular expression:
- ```py
- # Matches <span>
- page.get_by_text(\"world\")
- # Matches first <div>
- page.get_by_text(\"Hello world\")
- # Matches second <div>
- page.get_by_text(\"Hello\", exact=True)
- # Matches both <div>s
- page.get_by_text(re.compile(\"Hello\"))
- # Matches second <div>
- page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
- ```
- **Details**
- Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
- one, turns line breaks into spaces and ignores leading and trailing whitespace.
- Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
- example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
- def get_by_title(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """FrameLocator.get_by_title
- Allows locating elements by their title attribute.
- **Usage**
- Consider the following DOM structure.
- ```html
- <span title='Issues count'>25 issues</span>
- ```
- You can check the issues count after locating it by the title text:
- ```py
- expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
- def frame_locator(self, selector: str) -> "FrameLocator":
- """FrameLocator.frame_locator
- When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
- in that iframe.
- Parameters
- ----------
- selector : str
- A selector to use when resolving DOM element.
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
- def nth(self, index: int) -> "FrameLocator":
- """FrameLocator.nth
- Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.
- Parameters
- ----------
- index : int
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.nth(index=index))
- mapping.register(FrameLocatorImpl, FrameLocator)
- class Worker(SyncBase):
- @typing.overload
- def on(
- self, event: Literal["close"], f: typing.Callable[["Worker"], "None"]
- ) -> None:
- """
- Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
- terminated."""
- @typing.overload
- def on(
- self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
- ) -> None:
- """
- Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
- """
- def on(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().on(event=event, f=f)
- @typing.overload
- def once(
- self, event: Literal["close"], f: typing.Callable[["Worker"], "None"]
- ) -> None:
- """
- Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
- terminated."""
- @typing.overload
- def once(
- self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
- ) -> None:
- """
- Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.
- """
- def once(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().once(event=event, f=f)
- @property
- def url(self) -> str:
- """Worker.url
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- def evaluate(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """Worker.evaluate
- Returns the return value of `expression`.
- If the function passed to the `worker.evaluate()` returns a [Promise], then `worker.evaluate()`
- would wait for the promise to resolve and return its value.
- If the function passed to the `worker.evaluate()` returns a non-[Serializable] value, then
- `worker.evaluate()` returns `undefined`. Playwright also supports transferring some additional values that
- are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
- )
- )
- def evaluate_handle(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> "JSHandle":
- """Worker.evaluate_handle
- Returns the return value of `expression` as a `JSHandle`.
- The only difference between `worker.evaluate()` and `worker.evaluate_handle()` is that
- `worker.evaluate_handle()` returns `JSHandle`.
- If the function passed to the `worker.evaluate_handle()` returns a [Promise], then
- `worker.evaluate_handle()` would wait for the promise to resolve and return its value.
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.evaluate_handle(
- expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def expect_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager:
- """Worker.expect_event
- Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
- value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
- **Usage**
- ```py
- with worker.expect_event(\"console\") as event_info:
- worker.evaluate(\"console.log(42)\")
- message = event_info.value
- ```
- Parameters
- ----------
- event : str
- Event name, same one typically passed into `*.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_event(
- event=event, predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- mapping.register(WorkerImpl, Worker)
- class Selectors(SyncBase):
- def register(
- self,
- name: str,
- script: typing.Optional[str] = None,
- *,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- content_script: typing.Optional[bool] = None,
- ) -> None:
- """Selectors.register
- Selectors must be registered before creating the page.
- **Usage**
- An example of registering selector engine that queries elements based on a tag name:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- tag_selector = \"\"\"
- {
- // Returns the first element matching given selector in the root's subtree.
- query(root, selector) {
- return root.querySelector(selector);
- },
- // Returns all elements matching given selector in the root's subtree.
- queryAll(root, selector) {
- return Array.from(root.querySelectorAll(selector));
- }
- }\"\"\"
- # Register the engine. Selectors will be prefixed with \"tag=\".
- playwright.selectors.register(\"tag\", tag_selector)
- browser = playwright.chromium.launch()
- page = browser.new_page()
- page.set_content('<div><button>Click me</button></div>')
- # Use the selector prefixed with its name.
- button = page.locator('tag=button')
- # Combine it with built-in locators.
- page.locator('tag=div').get_by_text('Click me').click()
- # Can use it in any methods supporting selectors.
- button_count = page.locator('tag=button').count()
- print(button_count)
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- name : str
- Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only
- contain `[a-zA-Z0-9_]` characters.
- script : Union[str, None]
- Raw script content.
- path : Union[pathlib.Path, str, None]
- Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
- directory.
- content_script : Union[bool, None]
- Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same
- DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content
- script is not guaranteed when this engine is used together with other registered engines.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.register(
- name=name, script=script, path=path, contentScript=content_script
- )
- )
- )
- def set_test_id_attribute(self, attribute_name: str) -> None:
- """Selectors.set_test_id_attribute
- Defines custom attribute name to be used in `page.get_by_test_id()`. `data-testid` is used by default.
- Parameters
- ----------
- attribute_name : str
- Test id attribute name.
- """
- return mapping.from_maybe_impl(
- self._impl_obj.set_test_id_attribute(attributeName=attribute_name)
- )
- mapping.register(SelectorsImpl, Selectors)
- class Clock(SyncBase):
- def install(
- self,
- *,
- time: typing.Optional[typing.Union[float, str, datetime.datetime]] = None,
- ) -> None:
- """Clock.install
- Install fake implementations for the following time-related functions:
- - `Date`
- - `setTimeout`
- - `clearTimeout`
- - `setInterval`
- - `clearInterval`
- - `requestAnimationFrame`
- - `cancelAnimationFrame`
- - `requestIdleCallback`
- - `cancelIdleCallback`
- - `performance`
- Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,
- and control the behavior of time-dependent functions. See `clock.run_for()` and
- `clock.fast_forward()` for more information.
- Parameters
- ----------
- time : Union[datetime.datetime, float, str, None]
- Time to initialize with, current system time by default.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.install(time=time)))
- def fast_forward(self, ticks: typing.Union[int, str]) -> None:
- """Clock.fast_forward
- Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user
- closing the laptop lid for a while and reopening it later, after given time.
- **Usage**
- ```py
- page.clock.fast_forward(1000)
- page.clock.fast_forward(\"30:00\")
- ```
- Parameters
- ----------
- ticks : Union[int, str]
- Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
- "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.fast_forward(ticks=ticks))
- )
- def pause_at(self, time: typing.Union[float, str, datetime.datetime]) -> None:
- """Clock.pause_at
- Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired
- unless `clock.run_for()`, `clock.fast_forward()`, `clock.pause_at()` or
- `clock.resume()` is called.
- Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it
- at the specified time and pausing.
- **Usage**
- ```py
- page.clock.pause_at(datetime.datetime(2020, 2, 2))
- page.clock.pause_at(\"2020-02-02\")
- ```
- For best results, install the clock before navigating the page and set it to a time slightly before the intended
- test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.
- Once the page has fully loaded, you can safely use `clock.pause_at()` to pause the clock.
- ```py
- # Initialize clock with some time before the test time and let the page load
- # naturally. `Date.now` will progress as the timers fire.
- page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0))
- page.goto(\"http://localhost:3333\")
- page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0))
- ```
- Parameters
- ----------
- time : Union[datetime.datetime, float, str]
- Time to pause at.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.pause_at(time=time)))
- def resume(self) -> None:
- """Clock.resume
- Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.resume()))
- def run_for(self, ticks: typing.Union[int, str]) -> None:
- """Clock.run_for
- Advance the clock, firing all the time-related callbacks.
- **Usage**
- ```py
- page.clock.run_for(1000);
- page.clock.run_for(\"30:00\")
- ```
- Parameters
- ----------
- ticks : Union[int, str]
- Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
- "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.run_for(ticks=ticks)))
- def set_fixed_time(self, time: typing.Union[float, str, datetime.datetime]) -> None:
- """Clock.set_fixed_time
- Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.
- Use this method for simple scenarios where you only need to test with a predefined time. For more advanced
- scenarios, use `clock.install()` instead. Read docs on [clock emulation](https://playwright.dev/python/docs/clock) to learn more.
- **Usage**
- ```py
- page.clock.set_fixed_time(datetime.datetime.now())
- page.clock.set_fixed_time(datetime.datetime(2020, 2, 2))
- page.clock.set_fixed_time(\"2020-02-02\")
- ```
- Parameters
- ----------
- time : Union[datetime.datetime, float, str]
- Time to be set.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.set_fixed_time(time=time))
- )
- def set_system_time(
- self, time: typing.Union[float, str, datetime.datetime]
- ) -> None:
- """Clock.set_system_time
- Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for
- example switching from summer to winter time, or changing time zones.
- **Usage**
- ```py
- page.clock.set_system_time(datetime.datetime.now())
- page.clock.set_system_time(datetime.datetime(2020, 2, 2))
- page.clock.set_system_time(\"2020-02-02\")
- ```
- Parameters
- ----------
- time : Union[datetime.datetime, float, str]
- Time to be set.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.set_system_time(time=time))
- )
- mapping.register(ClockImpl, Clock)
- class ConsoleMessage(SyncBase):
- @property
- def type(
- self,
- ) -> typing.Union[
- Literal["assert"],
- Literal["clear"],
- Literal["count"],
- Literal["debug"],
- Literal["dir"],
- Literal["dirxml"],
- Literal["endGroup"],
- Literal["error"],
- Literal["info"],
- Literal["log"],
- Literal["profile"],
- Literal["profileEnd"],
- Literal["startGroup"],
- Literal["startGroupCollapsed"],
- Literal["table"],
- Literal["time"],
- Literal["timeEnd"],
- Literal["trace"],
- Literal["warning"],
- ]:
- """ConsoleMessage.type
- Returns
- -------
- Union["assert", "clear", "count", "debug", "dir", "dirxml", "endGroup", "error", "info", "log", "profile", "profileEnd", "startGroup", "startGroupCollapsed", "table", "time", "timeEnd", "trace", "warning"]
- """
- return mapping.from_maybe_impl(self._impl_obj.type)
- @property
- def text(self) -> str:
- """ConsoleMessage.text
- The text of the console message.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.text)
- @property
- def args(self) -> typing.List["JSHandle"]:
- """ConsoleMessage.args
- List of arguments passed to a `console` function call. See also `page.on('console')`.
- Returns
- -------
- List[JSHandle]
- """
- return mapping.from_impl_list(self._impl_obj.args)
- @property
- def location(self) -> SourceLocation:
- """ConsoleMessage.location
- Returns
- -------
- {url: str, lineNumber: int, columnNumber: int}
- """
- return mapping.from_impl(self._impl_obj.location)
- @property
- def page(self) -> typing.Optional["Page"]:
- """ConsoleMessage.page
- The page that produced this console message, if any.
- Returns
- -------
- Union[Page, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.page)
- @property
- def worker(self) -> typing.Optional["Worker"]:
- """ConsoleMessage.worker
- The web worker or service worker that produced this console message, if any. Note that console messages from web
- workers also have non-null `console_message.page()`.
- Returns
- -------
- Union[Worker, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.worker)
- mapping.register(ConsoleMessageImpl, ConsoleMessage)
- class Dialog(SyncBase):
- @property
- def type(self) -> str:
- """Dialog.type
- Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.type)
- @property
- def message(self) -> str:
- """Dialog.message
- A message displayed in the dialog.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.message)
- @property
- def default_value(self) -> str:
- """Dialog.default_value
- If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.default_value)
- @property
- def page(self) -> typing.Optional["Page"]:
- """Dialog.page
- The page that initiated this dialog, if available.
- Returns
- -------
- Union[Page, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.page)
- def accept(self, prompt_text: typing.Optional[str] = None) -> None:
- """Dialog.accept
- Returns when the dialog has been accepted.
- Parameters
- ----------
- prompt_text : Union[str, None]
- A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.accept(promptText=prompt_text))
- )
- def dismiss(self) -> None:
- """Dialog.dismiss
- Returns when the dialog has been dismissed.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.dismiss()))
- mapping.register(DialogImpl, Dialog)
- class Download(SyncBase):
- @property
- def page(self) -> "Page":
- """Download.page
- Get the page that the download belongs to.
- Returns
- -------
- Page
- """
- return mapping.from_impl(self._impl_obj.page)
- @property
- def url(self) -> str:
- """Download.url
- Returns downloaded url.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- @property
- def suggested_filename(self) -> str:
- """Download.suggested_filename
- Returns suggested filename for this download. It is typically computed by the browser from the
- [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response
- header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).
- Different browsers can use different logic for computing it.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.suggested_filename)
- def delete(self) -> None:
- """Download.delete
- Deletes the downloaded file. Will wait for the download to finish if necessary.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.delete()))
- def failure(self) -> typing.Optional[str]:
- """Download.failure
- Returns download error if any. Will wait for the download to finish if necessary.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.failure()))
- def path(self) -> pathlib.Path:
- """Download.path
- Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method
- will wait for the download to finish if necessary. The method throws when connected remotely.
- Note that the download's file name is a random GUID, use `download.suggested_filename()` to get suggested
- file name.
- Returns
- -------
- pathlib.Path
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.path()))
- def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
- """Download.save_as
- Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.
- Will wait for the download to finish if necessary.
- **Usage**
- ```py
- download.save_as(\"/path/to/save/at/\" + download.suggested_filename)
- ```
- Parameters
- ----------
- path : Union[pathlib.Path, str]
- Path where the download should be copied.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.save_as(path=path)))
- def cancel(self) -> None:
- """Download.cancel
- Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,
- `download.failure()` would resolve to `'canceled'`.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.cancel()))
- mapping.register(DownloadImpl, Download)
- class Video(SyncBase):
- def path(self) -> pathlib.Path:
- """Video.path
- Returns the file system path this video will be recorded to. The video is guaranteed to be written to the
- filesystem upon closing the browser context. This method throws when connected remotely.
- Returns
- -------
- pathlib.Path
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.path()))
- def save_as(self, path: typing.Union[str, pathlib.Path]) -> None:
- """Video.save_as
- Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or
- after the page has closed. This method waits until the page is closed and the video is fully saved.
- Parameters
- ----------
- path : Union[pathlib.Path, str]
- Path where the video should be saved.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.save_as(path=path)))
- def delete(self) -> None:
- """Video.delete
- Deletes the video file. Will wait for the video to finish if necessary.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.delete()))
- mapping.register(VideoImpl, Video)
- class Page(SyncContextManager):
- @typing.overload
- def on(self, event: Literal["close"], f: typing.Callable[["Page"], "None"]) -> None:
- """
- Emitted when the page closes."""
- @typing.overload
- def on(
- self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
- ) -> None:
- """
- Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
- The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
- **Usage**
- ```py
- def print_args(msg):
- for arg in msg.args:
- print(arg.json_value())
- page.on(\"console\", print_args)
- page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
- ```"""
- @typing.overload
- def on(self, event: Literal["crash"], f: typing.Callable[["Page"], "None"]) -> None:
- """
- Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
- crashes, ongoing and subsequent operations will throw.
- The most common way to deal with crashes is to catch an exception:
- ```py
- try:
- # crash might happen during a click.
- page.click(\"button\")
- # or while waiting for an event.
- page.wait_for_event(\"popup\")
- except Error as e:
- pass
- # when the page crashes, exception message contains \"crash\".
- ```"""
- @typing.overload
- def on(
- self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
- ) -> None:
- """
- Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
- either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
- [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
- and actions like click will never finish.
- **Usage**
- ```python
- page.on(\"dialog\", lambda dialog: dialog.accept())
- ```
- **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
- automatically dismissed."""
- @typing.overload
- def on(
- self, event: Literal["domcontentloaded"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- Emitted when the JavaScript
- [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
- """
- @typing.overload
- def on(
- self, event: Literal["download"], f: typing.Callable[["Download"], "None"]
- ) -> None:
- """
- Emitted when attachment download started. User can access basic file operations on downloaded content via the
- passed `Download` instance."""
- @typing.overload
- def on(
- self, event: Literal["filechooser"], f: typing.Callable[["FileChooser"], "None"]
- ) -> None:
- """
- Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
- respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
- ```py
- page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
- ```"""
- @typing.overload
- def on(
- self, event: Literal["frameattached"], f: typing.Callable[["Frame"], "None"]
- ) -> None:
- """
- Emitted when a frame is attached."""
- @typing.overload
- def on(
- self, event: Literal["framedetached"], f: typing.Callable[["Frame"], "None"]
- ) -> None:
- """
- Emitted when a frame is detached."""
- @typing.overload
- def on(
- self, event: Literal["framenavigated"], f: typing.Callable[["Frame"], "None"]
- ) -> None:
- """
- Emitted when a frame is navigated to a new url."""
- @typing.overload
- def on(self, event: Literal["load"], f: typing.Callable[["Page"], "None"]) -> None:
- """
- Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
- """
- @typing.overload
- def on(
- self, event: Literal["pageerror"], f: typing.Callable[["Error"], "None"]
- ) -> None:
- """
- Emitted when an uncaught exception happens within the page.
- ```py
- # Log all uncaught errors to the terminal
- page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
- # Navigate to a page with an exception.
- page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
- ```"""
- @typing.overload
- def on(self, event: Literal["popup"], f: typing.Callable[["Page"], "None"]) -> None:
- """
- Emitted when the page opens a new tab or window. This event is emitted in addition to the
- `browser_context.on('page')`, but only for popups relevant to this page.
- The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
- popup with `window.open('http://example.com')`, this event will fire when the network request to
- \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
- to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
- instead of similar methods on the `Page`.
- ```py
- with page.expect_event(\"popup\") as page_info:
- page.get_by_text(\"open the popup\").click()
- popup = page_info.value
- print(popup.evaluate(\"location.href\"))
- ```
- **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
- need it in most cases)."""
- @typing.overload
- def on(
- self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
- see `page.route()` or `browser_context.route()`."""
- @typing.overload
- def on(
- self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request fails, for example by timing out.
- ```python
- page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
- ```
- **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
- will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
- only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
- net::ERR_FAILED."""
- @typing.overload
- def on(
- self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request finishes successfully after downloading the response body. For a successful response, the
- sequence of events is `request`, `response` and `requestfinished`."""
- @typing.overload
- def on(
- self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
- ) -> None:
- """
- Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
- events is `request`, `response` and `requestfinished`."""
- @typing.overload
- def on(
- self, event: Literal["websocket"], f: typing.Callable[["WebSocket"], "None"]
- ) -> None:
- """
- Emitted when `WebSocket` request is sent."""
- @typing.overload
- def on(
- self, event: Literal["worker"], f: typing.Callable[["Worker"], "None"]
- ) -> None:
- """
- Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
- by the page."""
- def on(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().on(event=event, f=f)
- @typing.overload
- def once(
- self, event: Literal["close"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- Emitted when the page closes."""
- @typing.overload
- def once(
- self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
- ) -> None:
- """
- Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
- The arguments passed into `console.log` are available on the `ConsoleMessage` event handler argument.
- **Usage**
- ```py
- def print_args(msg):
- for arg in msg.args:
- print(arg.json_value())
- page.on(\"console\", print_args)
- page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
- ```"""
- @typing.overload
- def once(
- self, event: Literal["crash"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page
- crashes, ongoing and subsequent operations will throw.
- The most common way to deal with crashes is to catch an exception:
- ```py
- try:
- # crash might happen during a click.
- page.click(\"button\")
- # or while waiting for an event.
- page.wait_for_event(\"popup\")
- except Error as e:
- pass
- # when the page crashes, exception message contains \"crash\".
- ```"""
- @typing.overload
- def once(
- self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
- ) -> None:
- """
- Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
- either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
- [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
- and actions like click will never finish.
- **Usage**
- ```python
- page.on(\"dialog\", lambda dialog: dialog.accept())
- ```
- **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
- automatically dismissed."""
- @typing.overload
- def once(
- self, event: Literal["domcontentloaded"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- Emitted when the JavaScript
- [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
- """
- @typing.overload
- def once(
- self, event: Literal["download"], f: typing.Callable[["Download"], "None"]
- ) -> None:
- """
- Emitted when attachment download started. User can access basic file operations on downloaded content via the
- passed `Download` instance."""
- @typing.overload
- def once(
- self, event: Literal["filechooser"], f: typing.Callable[["FileChooser"], "None"]
- ) -> None:
- """
- Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
- respond to it via setting the input files using `file_chooser.set_files()` that can be uploaded after that.
- ```py
- page.on(\"filechooser\", lambda file_chooser: file_chooser.set_files(\"/tmp/myfile.pdf\"))
- ```"""
- @typing.overload
- def once(
- self, event: Literal["frameattached"], f: typing.Callable[["Frame"], "None"]
- ) -> None:
- """
- Emitted when a frame is attached."""
- @typing.overload
- def once(
- self, event: Literal["framedetached"], f: typing.Callable[["Frame"], "None"]
- ) -> None:
- """
- Emitted when a frame is detached."""
- @typing.overload
- def once(
- self, event: Literal["framenavigated"], f: typing.Callable[["Frame"], "None"]
- ) -> None:
- """
- Emitted when a frame is navigated to a new url."""
- @typing.overload
- def once(
- self, event: Literal["load"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
- """
- @typing.overload
- def once(
- self, event: Literal["pageerror"], f: typing.Callable[["Error"], "None"]
- ) -> None:
- """
- Emitted when an uncaught exception happens within the page.
- ```py
- # Log all uncaught errors to the terminal
- page.on(\"pageerror\", lambda exc: print(f\"uncaught exception: {exc}\"))
- # Navigate to a page with an exception.
- page.goto(\"data:text/html,<script>throw new Error('test')</script>\")
- ```"""
- @typing.overload
- def once(
- self, event: Literal["popup"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- Emitted when the page opens a new tab or window. This event is emitted in addition to the
- `browser_context.on('page')`, but only for popups relevant to this page.
- The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
- popup with `window.open('http://example.com')`, this event will fire when the network request to
- \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
- to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
- instead of similar methods on the `Page`.
- ```py
- with page.expect_event(\"popup\") as page_info:
- page.get_by_text(\"open the popup\").click()
- popup = page_info.value
- print(popup.evaluate(\"location.href\"))
- ```
- **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
- need it in most cases)."""
- @typing.overload
- def once(
- self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests,
- see `page.route()` or `browser_context.route()`."""
- @typing.overload
- def once(
- self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request fails, for example by timing out.
- ```python
- page.on(\"requestfailed\", lambda request: print(request.url + \" \" + request.failure.error_text))
- ```
- **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
- will complete with `page.on('request_finished')` event and not with `page.on('request_failed')`. A request will
- only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error
- net::ERR_FAILED."""
- @typing.overload
- def once(
- self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request finishes successfully after downloading the response body. For a successful response, the
- sequence of events is `request`, `response` and `requestfinished`."""
- @typing.overload
- def once(
- self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
- ) -> None:
- """
- Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
- events is `request`, `response` and `requestfinished`."""
- @typing.overload
- def once(
- self, event: Literal["websocket"], f: typing.Callable[["WebSocket"], "None"]
- ) -> None:
- """
- Emitted when `WebSocket` request is sent."""
- @typing.overload
- def once(
- self, event: Literal["worker"], f: typing.Callable[["Worker"], "None"]
- ) -> None:
- """
- Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned
- by the page."""
- def once(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().once(event=event, f=f)
- @property
- def keyboard(self) -> "Keyboard":
- """Page.keyboard
- Returns
- -------
- Keyboard
- """
- return mapping.from_impl(self._impl_obj.keyboard)
- @property
- def mouse(self) -> "Mouse":
- """Page.mouse
- Returns
- -------
- Mouse
- """
- return mapping.from_impl(self._impl_obj.mouse)
- @property
- def touchscreen(self) -> "Touchscreen":
- """Page.touchscreen
- Returns
- -------
- Touchscreen
- """
- return mapping.from_impl(self._impl_obj.touchscreen)
- @property
- def context(self) -> "BrowserContext":
- """Page.context
- Get the browser context that the page belongs to.
- Returns
- -------
- BrowserContext
- """
- return mapping.from_impl(self._impl_obj.context)
- @property
- def clock(self) -> "Clock":
- """Page.clock
- Playwright has ability to mock clock and passage of time.
- Returns
- -------
- Clock
- """
- return mapping.from_impl(self._impl_obj.clock)
- @property
- def main_frame(self) -> "Frame":
- """Page.main_frame
- The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
- Returns
- -------
- Frame
- """
- return mapping.from_impl(self._impl_obj.main_frame)
- @property
- def frames(self) -> typing.List["Frame"]:
- """Page.frames
- An array of all frames attached to the page.
- Returns
- -------
- List[Frame]
- """
- return mapping.from_impl_list(self._impl_obj.frames)
- @property
- def url(self) -> str:
- """Page.url
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- @property
- def viewport_size(self) -> typing.Optional[ViewportSize]:
- """Page.viewport_size
- Returns
- -------
- Union[{width: int, height: int}, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.viewport_size)
- @property
- def workers(self) -> typing.List["Worker"]:
- """Page.workers
- This method returns all of the dedicated
- [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
- **NOTE** This does not contain ServiceWorkers
- Returns
- -------
- List[Worker]
- """
- return mapping.from_impl_list(self._impl_obj.workers)
- @property
- def request(self) -> "APIRequestContext":
- """Page.request
- API testing helper associated with this page. This method returns the same instance as
- `browser_context.request` on the page's context. See `browser_context.request` for more
- details.
- Returns
- -------
- APIRequestContext
- """
- return mapping.from_impl(self._impl_obj.request)
- @property
- def video(self) -> typing.Optional["Video"]:
- """Page.video
- Video object associated with this page.
- Returns
- -------
- Union[Video, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.video)
- def opener(self) -> typing.Optional["Page"]:
- """Page.opener
- Returns the opener for popup pages and `null` for others. If the opener has been closed already the returns `null`.
- Returns
- -------
- Union[Page, None]
- """
- return mapping.from_impl_nullable(self._sync(self._impl_obj.opener()))
- def frame(
- self,
- name: typing.Optional[str] = None,
- *,
- url: typing.Optional[
- typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
- ] = None,
- ) -> typing.Optional["Frame"]:
- """Page.frame
- Returns frame matching the specified criteria. Either `name` or `url` must be specified.
- **Usage**
- ```py
- frame = page.frame(url=r\".*domain.*\")
- ```
- Parameters
- ----------
- name : Union[str, None]
- Frame name specified in the `iframe`'s `name` attribute. Optional.
- url : Union[Callable[[str], bool], Pattern[str], str, None]
- A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object. Optional.
- Returns
- -------
- Union[Frame, None]
- """
- return mapping.from_impl_nullable(
- self._impl_obj.frame(name=name, url=self._wrap_handler(url))
- )
- def set_default_navigation_timeout(self, timeout: float) -> None:
- """Page.set_default_navigation_timeout
- This setting will change the default maximum navigation time for the following methods and related shortcuts:
- - `page.go_back()`
- - `page.go_forward()`
- - `page.goto()`
- - `page.reload()`
- - `page.set_content()`
- - `page.expect_navigation()`
- - `page.wait_for_url()`
- **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`,
- `browser_context.set_default_timeout()` and `browser_context.set_default_navigation_timeout()`.
- Parameters
- ----------
- timeout : float
- Maximum navigation time in milliseconds
- """
- return mapping.from_maybe_impl(
- self._impl_obj.set_default_navigation_timeout(timeout=timeout)
- )
- def set_default_timeout(self, timeout: float) -> None:
- """Page.set_default_timeout
- This setting will change the default maximum time for all the methods accepting `timeout` option.
- **NOTE** `page.set_default_navigation_timeout()` takes priority over `page.set_default_timeout()`.
- Parameters
- ----------
- timeout : float
- Maximum time in milliseconds. Pass `0` to disable timeout.
- """
- return mapping.from_maybe_impl(
- self._impl_obj.set_default_timeout(timeout=timeout)
- )
- def query_selector(
- self, selector: str, *, strict: typing.Optional[bool] = None
- ) -> typing.Optional["ElementHandle"]:
- """Page.query_selector
- The method finds an element matching the specified selector within the page. If no elements match the selector, the
- return value resolves to `null`. To wait for an element on the page, use `locator.wait_for()`.
- Parameters
- ----------
- selector : str
- A selector to query for.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.query_selector(selector=selector, strict=strict))
- )
- def query_selector_all(self, selector: str) -> typing.List["ElementHandle"]:
- """Page.query_selector_all
- The method finds all elements matching the specified selector within the page. If no elements match the selector,
- the return value resolves to `[]`.
- Parameters
- ----------
- selector : str
- A selector to query for.
- Returns
- -------
- List[ElementHandle]
- """
- return mapping.from_impl_list(
- self._sync(self._impl_obj.query_selector_all(selector=selector))
- )
- def wait_for_selector(
- self,
- selector: str,
- *,
- timeout: typing.Optional[float] = None,
- state: typing.Optional[
- Literal["attached", "detached", "hidden", "visible"]
- ] = None,
- strict: typing.Optional[bool] = None,
- ) -> typing.Optional["ElementHandle"]:
- """Page.wait_for_selector
- Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
- `detached`.
- **NOTE** Playwright automatically waits for element to be ready before performing an action. Using `Locator`
- objects and web-first assertions makes the code wait-for-selector-free.
- Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If
- at the moment of calling the method `selector` already satisfies the condition, the method will return immediately.
- If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
- **Usage**
- This method works across navigations:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- chromium = playwright.chromium
- browser = chromium.launch()
- page = browser.new_page()
- for current_url in [\"https://google.com\", \"https://bbc.com\"]:
- page.goto(current_url, wait_until=\"domcontentloaded\")
- element = page.wait_for_selector(\"img\")
- print(\"Loaded image: \" + str(element.get_attribute(\"src\")))
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- state : Union["attached", "detached", "hidden", "visible", None]
- Defaults to `'visible'`. Can be either:
- - `'attached'` - wait for element to be present in DOM.
- - `'detached'` - wait for element to not be present in DOM.
- - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
- without any content or with `display:none` has an empty bounding box and is not considered visible.
- - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
- `visibility:hidden`. This is opposite to the `'visible'` option.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- Union[ElementHandle, None]
- """
- return mapping.from_impl_nullable(
- self._sync(
- self._impl_obj.wait_for_selector(
- selector=selector, timeout=timeout, state=state, strict=strict
- )
- )
- )
- def is_checked(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Page.is_checked
- Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_checked(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_disabled(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Page.is_disabled
- Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_disabled(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_editable(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Page.is_editable
- Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable).
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_editable(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_enabled(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Page.is_enabled
- Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_enabled(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_hidden(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Page.is_hidden
- Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that
- does not match any elements is considered hidden.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Deprecated: This option is ignored. `page.is_hidden()` does not wait for the↵element to become hidden and returns immediately.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_hidden(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def is_visible(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> bool:
- """Page.is_visible
- Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible). `selector` that does not match any elements
- is considered not visible.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Deprecated: This option is ignored. `page.is_visible()` does not wait↵for the element to become visible and returns immediately.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.is_visible(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def dispatch_event(
- self,
- selector: str,
- type: str,
- event_init: typing.Optional[typing.Dict] = None,
- *,
- timeout: typing.Optional[float] = None,
- strict: typing.Optional[bool] = None,
- ) -> None:
- """Page.dispatch_event
- The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
- `click` is dispatched. This is equivalent to calling
- [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
- **Usage**
- ```py
- page.dispatch_event(\"button#submit\", \"click\")
- ```
- Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
- properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
- Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
- - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
- - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
- - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
- - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
- - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
- - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
- - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
- - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
- ```py
- # note you can only create data_transfer in chromium and firefox
- data_transfer = page.evaluate_handle(\"new DataTransfer()\")
- page.dispatch_event(\"#source\", \"dragstart\", { \"dataTransfer\": data_transfer })
- ```
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- type : str
- DOM event type: `"click"`, `"dragstart"`, etc.
- event_init : Union[Dict, None]
- Optional event-specific initialization properties.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dispatch_event(
- selector=selector,
- type=type,
- eventInit=mapping.to_impl(event_init),
- timeout=timeout,
- strict=strict,
- )
- )
- )
- def evaluate(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """Page.evaluate
- Returns the value of the `expression` invocation.
- If the function passed to the `page.evaluate()` returns a [Promise], then `page.evaluate()` would
- wait for the promise to resolve and return its value.
- If the function passed to the `page.evaluate()` returns a non-[Serializable] value, then
- `page.evaluate()` resolves to `undefined`. Playwright also supports transferring some additional values
- that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
- **Usage**
- Passing argument to `expression`:
- ```py
- result = page.evaluate(\"([x, y]) => Promise.resolve(x * y)\", [7, 8])
- print(result) # prints \"56\"
- ```
- A string can also be passed in instead of a function:
- ```py
- print(page.evaluate(\"1 + 2\")) # prints \"3\"
- x = 10
- print(page.evaluate(f\"1 + {x}\")) # prints \"11\"
- ```
- `ElementHandle` instances can be passed as an argument to the `page.evaluate()`:
- ```py
- body_handle = page.evaluate(\"document.body\")
- html = page.evaluate(\"([body, suffix]) => body.innerHTML + suffix\", [body_handle, \"hello\"])
- body_handle.dispose()
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.evaluate(expression=expression, arg=mapping.to_impl(arg))
- )
- )
- def evaluate_handle(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> "JSHandle":
- """Page.evaluate_handle
- Returns the value of the `expression` invocation as a `JSHandle`.
- The only difference between `page.evaluate()` and `page.evaluate_handle()` is that
- `page.evaluate_handle()` returns `JSHandle`.
- If the function passed to the `page.evaluate_handle()` returns a [Promise], then
- `page.evaluate_handle()` would wait for the promise to resolve and return its value.
- **Usage**
- ```py
- a_window_handle = page.evaluate_handle(\"Promise.resolve(window)\")
- a_window_handle # handle for the window object.
- ```
- A string can also be passed in instead of a function:
- ```py
- a_handle = page.evaluate_handle(\"document\") # handle for the \"document\"
- ```
- `JSHandle` instances can be passed as an argument to the `page.evaluate_handle()`:
- ```py
- a_handle = page.evaluate_handle(\"document.body\")
- result_handle = page.evaluate_handle(\"body => body.innerHTML\", a_handle)
- print(result_handle.json_value())
- result_handle.dispose()
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.evaluate_handle(
- expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def eval_on_selector(
- self,
- selector: str,
- expression: str,
- arg: typing.Optional[typing.Any] = None,
- *,
- strict: typing.Optional[bool] = None,
- ) -> typing.Any:
- """Page.eval_on_selector
- The method finds an element matching the specified selector within the page and passes it as a first argument to
- `expression`. If no elements match the selector, the method throws an error. Returns the value of `expression`.
- If `expression` returns a [Promise], then `page.eval_on_selector()` would wait for the promise to resolve and
- return its value.
- **Usage**
- ```py
- search_value = page.eval_on_selector(\"#search\", \"el => el.value\")
- preload_href = page.eval_on_selector(\"link[rel=preload]\", \"el => el.href\")
- html = page.eval_on_selector(\".main-container\", \"(e, suffix) => e.outer_html + suffix\", \"hello\")
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.eval_on_selector(
- selector=selector,
- expression=expression,
- arg=mapping.to_impl(arg),
- strict=strict,
- )
- )
- )
- def eval_on_selector_all(
- self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """Page.eval_on_selector_all
- The method finds all elements matching the specified selector within the page and passes an array of matched
- elements as a first argument to `expression`. Returns the result of `expression` invocation.
- If `expression` returns a [Promise], then `page.eval_on_selector_all()` would wait for the promise to resolve
- and return its value.
- **Usage**
- ```py
- div_counts = page.eval_on_selector_all(\"div\", \"(divs, min) => divs.length >= min\", 10)
- ```
- Parameters
- ----------
- selector : str
- A selector to query for.
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.eval_on_selector_all(
- selector=selector, expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def add_script_tag(
- self,
- *,
- url: typing.Optional[str] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- content: typing.Optional[str] = None,
- type: typing.Optional[str] = None,
- ) -> "ElementHandle":
- """Page.add_script_tag
- Adds a `<script>` tag into the page with the desired url or content. Returns the added tag when the script's onload
- fires or when the script content was injected into frame.
- Parameters
- ----------
- url : Union[str, None]
- URL of a script to be added.
- path : Union[pathlib.Path, str, None]
- Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative
- to the current working directory.
- content : Union[str, None]
- Raw JavaScript content to be injected into frame.
- type : Union[str, None]
- Script type. Use 'module' in order to load a JavaScript ES6 module. See
- [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.add_script_tag(
- url=url, path=path, content=content, type=type
- )
- )
- )
- def add_style_tag(
- self,
- *,
- url: typing.Optional[str] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- content: typing.Optional[str] = None,
- ) -> "ElementHandle":
- """Page.add_style_tag
- Adds a `<link rel=\"stylesheet\">` tag into the page with the desired url or a `<style type=\"text/css\">` tag with the
- content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
- Parameters
- ----------
- url : Union[str, None]
- URL of the `<link>` tag.
- path : Union[pathlib.Path, str, None]
- Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the
- current working directory.
- content : Union[str, None]
- Raw CSS content to be injected into frame.
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.add_style_tag(url=url, path=path, content=content)
- )
- )
- def expose_function(self, name: str, callback: typing.Callable) -> None:
- """Page.expose_function
- The method adds a function called `name` on the `window` object of every frame in the page. When called, the
- function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
- If the `callback` returns a [Promise], it will be awaited.
- See `browser_context.expose_function()` for context-wide exposed function.
- **NOTE** Functions installed via `page.expose_function()` survive navigations.
- **Usage**
- An example of adding a `sha256` function to the page:
- ```py
- import hashlib
- from playwright.sync_api import sync_playwright, Playwright
- def sha256(text):
- m = hashlib.sha256()
- m.update(bytes(text, \"utf8\"))
- return m.hexdigest()
- def run(playwright: Playwright):
- webkit = playwright.webkit
- browser = webkit.launch(headless=False)
- page = browser.new_page()
- page.expose_function(\"sha256\", sha256)
- page.set_content(\"\"\"
- <script>
- async function onClick() {
- document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
- }
- </script>
- <button onclick=\"onClick()\">Click me</button>
- <div></div>
- \"\"\")
- page.click(\"button\")
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- name : str
- Name of the function on the window object
- callback : Callable
- Callback function which will be called in Playwright's context.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.expose_function(
- name=name, callback=self._wrap_handler(callback)
- )
- )
- )
- def expose_binding(
- self,
- name: str,
- callback: typing.Callable,
- *,
- handle: typing.Optional[bool] = None,
- ) -> None:
- """Page.expose_binding
- The method adds a function called `name` on the `window` object of every frame in this page. When called, the
- function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the
- `callback` returns a [Promise], it will be awaited.
- The first argument of the `callback` function contains information about the caller: `{ browserContext:
- BrowserContext, page: Page, frame: Frame }`.
- See `browser_context.expose_binding()` for the context-wide version.
- **NOTE** Functions installed via `page.expose_binding()` survive navigations.
- **Usage**
- An example of exposing page URL to all frames in a page:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- webkit = playwright.webkit
- browser = webkit.launch(headless=False)
- context = browser.new_context()
- page = context.new_page()
- page.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
- page.set_content(\"\"\"
- <script>
- async function onClick() {
- document.querySelector('div').textContent = await window.pageURL();
- }
- </script>
- <button onclick=\"onClick()\">Click me</button>
- <div></div>
- \"\"\")
- page.click(\"button\")
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- name : str
- Name of the function on the window object.
- callback : Callable
- Callback function that will be called in the Playwright's context.
- handle : Union[bool, None]
- Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
- supported. When passing by value, multiple arguments are supported.
- Deprecated: This option will be removed in the future.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.expose_binding(
- name=name, callback=self._wrap_handler(callback), handle=handle
- )
- )
- )
- def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
- """Page.set_extra_http_headers
- The extra HTTP headers will be sent with every request the page initiates.
- **NOTE** `page.set_extra_http_headers()` does not guarantee the order of headers in the outgoing requests.
- Parameters
- ----------
- headers : Dict[str, str]
- An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_extra_http_headers(headers=mapping.to_impl(headers))
- )
- )
- def content(self) -> str:
- """Page.content
- Gets the full HTML contents of the page, including the doctype.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.content()))
- def set_content(
- self,
- html: str,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- ) -> None:
- """Page.set_content
- This method internally calls [document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write),
- inheriting all its specific characteristics and behaviors.
- Parameters
- ----------
- html : str
- HTML markup to assign to the page.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_content(
- html=html, timeout=timeout, waitUntil=wait_until
- )
- )
- )
- def goto(
- self,
- url: str,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- referer: typing.Optional[str] = None,
- ) -> typing.Optional["Response"]:
- """Page.goto
- Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first
- non-redirect response.
- The method will throw an error if:
- - there's an SSL error (e.g. in case of self-signed certificates).
- - target URL is invalid.
- - the `timeout` is exceeded during navigation.
- - the remote server does not respond or is unreachable.
- - the main resource failed to load.
- The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404
- \"Not Found\" and 500 \"Internal Server Error\". The status code for such responses can be retrieved by calling
- `response.status()`.
- **NOTE** The method either throws an error or returns a main resource response. The only exceptions are navigation
- to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
- **NOTE** Headless mode doesn't support navigation to a PDF document. See the
- [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
- Parameters
- ----------
- url : str
- URL to navigate page to. The url should include scheme, e.g. `https://`. When a `baseURL` via the context options
- was provided and the passed URL is a path, it gets merged via the
- [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- referer : Union[str, None]
- Referer header value. If provided it will take preference over the referer header value set by
- `page.set_extra_http_headers()`.
- Returns
- -------
- Union[Response, None]
- """
- return mapping.from_impl_nullable(
- self._sync(
- self._impl_obj.goto(
- url=url, timeout=timeout, waitUntil=wait_until, referer=referer
- )
- )
- )
- def reload(
- self,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- ) -> typing.Optional["Response"]:
- """Page.reload
- This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the
- main resource response. In case of multiple redirects, the navigation will resolve with the response of the last
- redirect.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- Returns
- -------
- Union[Response, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.reload(timeout=timeout, waitUntil=wait_until))
- )
- def wait_for_load_state(
- self,
- state: typing.Optional[
- Literal["domcontentloaded", "load", "networkidle"]
- ] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Page.wait_for_load_state
- Returns when the required load state has been reached.
- This resolves when the page reaches a required load state, `load` by default. The navigation must have been
- committed when this method is called. If current document has already reached the required state, resolves
- immediately.
- **NOTE** Most of the time, this method is not needed because Playwright
- [auto-waits before every action](https://playwright.dev/python/docs/actionability).
- **Usage**
- ```py
- page.get_by_role(\"button\").click() # click triggers navigation.
- page.wait_for_load_state() # the promise resolves after \"load\" event.
- ```
- ```py
- with page.expect_popup() as page_info:
- page.get_by_role(\"button\").click() # click triggers a popup.
- popup = page_info.value
- # Wait for the \"DOMContentLoaded\" event.
- popup.wait_for_load_state(\"domcontentloaded\")
- print(popup.title()) # popup is ready to use.
- ```
- Parameters
- ----------
- state : Union["domcontentloaded", "load", "networkidle", None]
- Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current
- document, the method resolves immediately. Can be one of:
- - `'load'` - wait for the `load` event to be fired.
- - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
- - `'networkidle'` - **DISCOURAGED** wait until there are no network connections for at least `500` ms. Don't use
- this method for testing, rely on web assertions to assess readiness instead.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.wait_for_load_state(state=state, timeout=timeout))
- )
- def wait_for_url(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- *,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Page.wait_for_url
- Waits for the main frame to navigate to the given URL.
- **Usage**
- ```py
- page.click(\"a.delayed-navigation\") # clicking the link will indirectly cause a navigation
- page.wait_for_url(\"**/target.html\")
- ```
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- equal to the string.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.wait_for_url(
- url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
- )
- )
- )
- def wait_for_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> typing.Any:
- """Page.wait_for_event
- **NOTE** In most cases, you should use `page.expect_event()`.
- Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
- and waits for `predicate(event)` to return a truthy value. Will throw an error if the page is closed before the
- `event` is fired.
- Parameters
- ----------
- event : str
- Event name, same one typically passed into `*.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.wait_for_event(
- event=event,
- predicate=self._wrap_handler(predicate),
- timeout=timeout,
- )
- )
- )
- def go_back(
- self,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- ) -> typing.Optional["Response"]:
- """Page.go_back
- Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
- the last redirect. If cannot go back, returns `null`.
- Navigate to the previous page in history.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- Returns
- -------
- Union[Response, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.go_back(timeout=timeout, waitUntil=wait_until))
- )
- def go_forward(
- self,
- *,
- timeout: typing.Optional[float] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- ) -> typing.Optional["Response"]:
- """Page.go_forward
- Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of
- the last redirect. If cannot go forward, returns `null`.
- Navigate to the next page in history.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- Returns
- -------
- Union[Response, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.go_forward(timeout=timeout, waitUntil=wait_until))
- )
- def request_gc(self) -> None:
- """Page.request_gc
- Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will
- be collected.
- This is useful to help detect memory leaks. For example, if your page has a large object `'suspect'` that might be
- leaked, you can check that it does not leak by using a
- [`WeakRef`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef).
- ```py
- # 1. In your page, save a WeakRef for the \"suspect\".
- page.evaluate(\"globalThis.suspectWeakRef = new WeakRef(suspect)\")
- # 2. Request garbage collection.
- page.request_gc()
- # 3. Check that weak ref does not deref to the original object.
- assert page.evaluate(\"!globalThis.suspectWeakRef.deref()\")
- ```
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.request_gc()))
- def emulate_media(
- self,
- *,
- media: typing.Optional[Literal["null", "print", "screen"]] = None,
- color_scheme: typing.Optional[
- Literal["dark", "light", "no-preference", "null"]
- ] = None,
- reduced_motion: typing.Optional[
- Literal["no-preference", "null", "reduce"]
- ] = None,
- forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
- contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
- ) -> None:
- """Page.emulate_media
- This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media
- feature, using the `colorScheme` argument.
- **Usage**
- ```py
- page.evaluate(\"matchMedia('screen').matches\")
- # → True
- page.evaluate(\"matchMedia('print').matches\")
- # → False
- page.emulate_media(media=\"print\")
- page.evaluate(\"matchMedia('screen').matches\")
- # → False
- page.evaluate(\"matchMedia('print').matches\")
- # → True
- page.emulate_media()
- page.evaluate(\"matchMedia('screen').matches\")
- # → True
- page.evaluate(\"matchMedia('print').matches\")
- # → False
- ```
- ```py
- page.emulate_media(color_scheme=\"dark\")
- page.evaluate(\"matchMedia('(prefers-color-scheme: dark)').matches\")
- # → True
- page.evaluate(\"matchMedia('(prefers-color-scheme: light)').matches\")
- # → False
- ```
- Parameters
- ----------
- media : Union["null", "print", "screen", None]
- Changes the CSS media type of the page. The only allowed values are `'Screen'`, `'Print'` and `'Null'`. Passing
- `'Null'` disables CSS media emulation.
- color_scheme : Union["dark", "light", "no-preference", "null", None]
- Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
- media feature, supported values are `'light'` and `'dark'`. Passing `'Null'` disables color scheme emulation.
- `'no-preference'` is deprecated.
- reduced_motion : Union["no-preference", "null", "reduce", None]
- Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. Passing
- `null` disables reduced motion emulation.
- forced_colors : Union["active", "none", "null", None]
- contrast : Union["more", "no-preference", "null", None]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.emulate_media(
- media=media,
- colorScheme=color_scheme,
- reducedMotion=reduced_motion,
- forcedColors=forced_colors,
- contrast=contrast,
- )
- )
- )
- def set_viewport_size(self, viewport_size: ViewportSize) -> None:
- """Page.set_viewport_size
- In the case of multiple pages in a single browser, each page can have its own viewport size. However,
- `browser.new_context()` allows to set viewport size (and more) for all pages in the context at once.
- `page.set_viewport_size()` will resize the page. A lot of websites don't expect phones to change size, so you
- should set the viewport size before navigating to the page. `page.set_viewport_size()` will also reset
- `screen` size, use `browser.new_context()` with `screen` and `viewport` parameters if you need better
- control of these properties.
- **Usage**
- ```py
- page = browser.new_page()
- page.set_viewport_size({\"width\": 640, \"height\": 480})
- page.goto(\"https://example.com\")
- ```
- Parameters
- ----------
- viewport_size : {width: int, height: int}
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.set_viewport_size(viewportSize=viewport_size))
- )
- def bring_to_front(self) -> None:
- """Page.bring_to_front
- Brings page to front (activates tab).
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.bring_to_front()))
- def add_init_script(
- self,
- script: typing.Optional[str] = None,
- *,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- ) -> None:
- """Page.add_init_script
- Adds a script which would be evaluated in one of the following scenarios:
- - Whenever the page is navigated.
- - Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the
- newly attached frame.
- The script is evaluated after the document was created but before any of its scripts were run. This is useful to
- amend the JavaScript environment, e.g. to seed `Math.random`.
- **Usage**
- An example of overriding `Math.random` before the page loads:
- ```py
- # in your playwright script, assuming the preload.js file is in same directory
- page.add_init_script(path=\"./preload.js\")
- ```
- **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
- `page.add_init_script()` is not defined.
- Parameters
- ----------
- script : Union[str, None]
- Script to be evaluated in all pages in the browser context. Optional.
- path : Union[pathlib.Path, str, None]
- Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
- directory. Optional.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.add_init_script(script=script, path=path))
- )
- def route(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- handler: typing.Union[
- typing.Callable[["Route"], typing.Any],
- typing.Callable[["Route", "Request"], typing.Any],
- ],
- *,
- times: typing.Optional[int] = None,
- ) -> None:
- """Page.route
- Routing provides the capability to modify network requests that are made by a page.
- Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or
- aborted.
- **NOTE** The handler will only be called for the first url if the response is a redirect.
- **NOTE** `page.route()` will not intercept requests intercepted by Service Worker. See
- [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
- using request interception by setting `serviceWorkers` to `'block'`.
- **NOTE** `page.route()` will not intercept the first request of a popup page. Use
- `browser_context.route()` instead.
- **Usage**
- An example of a naive handler that aborts all image requests:
- ```py
- page = browser.new_page()
- page.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
- page.goto(\"https://example.com\")
- browser.close()
- ```
- or the same snippet using a regex pattern instead:
- ```py
- page = browser.new_page()
- page.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
- page.goto(\"https://example.com\")
- browser.close()
- ```
- It is possible to examine the request to decide the route action. For example, mocking all requests that contain
- some post data, and leaving all other requests as is:
- ```py
- def handle_route(route: Route):
- if (\"my-string\" in route.request.post_data):
- route.fulfill(body=\"mocked-data\")
- else:
- route.continue_()
- page.route(\"/api/**\", handle_route)
- ```
- Page routes take precedence over browser context routes (set up with `browser_context.route()`) when request
- matches both handlers.
- To remove a route with its handler you can use `page.unroute()`.
- **NOTE** Enabling routing disables http cache.
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
- the context options and the provided URL is a string that does not start with `*`, it is resolved using the
- [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
- handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
- handler function to route the request.
- times : Union[int, None]
- How often a route should be used. By default it will be used every time.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.route(
- url=self._wrap_handler(url),
- handler=self._wrap_handler(handler),
- times=times,
- )
- )
- )
- def unroute(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- handler: typing.Optional[
- typing.Union[
- typing.Callable[["Route"], typing.Any],
- typing.Callable[["Route", "Request"], typing.Any],
- ]
- ] = None,
- ) -> None:
- """Page.unroute
- Removes a route created with `page.route()`. When `handler` is not specified, removes all routes for the
- `url`.
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
- handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
- Optional handler function to route the request.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.unroute(
- url=self._wrap_handler(url), handler=self._wrap_handler(handler)
- )
- )
- )
- def route_web_socket(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- handler: typing.Callable[["WebSocketRoute"], typing.Any],
- ) -> None:
- """Page.route_web_socket
- This method allows to modify websocket connections that are made by the page.
- Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
- method before navigating the page.
- **Usage**
- Below is an example of a simple mock that responds to a single message. See `WebSocketRoute` for more details and
- examples.
- ```py
- def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
- if message == \"request\":
- ws.send(\"response\")
- def handler(ws: WebSocketRoute):
- ws.on_message(lambda message: message_handler(ws, message))
- page.route_web_socket(\"/ws\", handler)
- ```
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
- `baseURL` context option.
- handler : Callable[[WebSocketRoute], Any]
- Handler function to route the WebSocket.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.route_web_socket(
- url=self._wrap_handler(url), handler=self._wrap_handler(handler)
- )
- )
- )
- def unroute_all(
- self,
- *,
- behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
- ) -> None:
- """Page.unroute_all
- Removes all routes created with `page.route()` and `page.route_from_har()`.
- Parameters
- ----------
- behavior : Union["default", "ignoreErrors", "wait", None]
- Specifies whether to wait for already running handlers and what to do if they throw errors:
- - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
- result in unhandled error
- - `'wait'` - wait for current handler calls (if any) to finish
- - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
- after unrouting are silently caught
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.unroute_all(behavior=behavior))
- )
- def route_from_har(
- self,
- har: typing.Union[pathlib.Path, str],
- *,
- url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- not_found: typing.Optional[Literal["abort", "fallback"]] = None,
- update: typing.Optional[bool] = None,
- update_content: typing.Optional[Literal["attach", "embed"]] = None,
- update_mode: typing.Optional[Literal["full", "minimal"]] = None,
- ) -> None:
- """Page.route_from_har
- If specified the network requests that are made in the page will be served from the HAR file. Read more about
- [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
- Playwright will not serve requests intercepted by Service Worker from the HAR file. See
- [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
- using request interception by setting `serviceWorkers` to `'block'`.
- Parameters
- ----------
- har : Union[pathlib.Path, str]
- Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
- relative path, then it is resolved relative to the current working directory.
- url : Union[Pattern[str], str, None]
- A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
- pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
- not_found : Union["abort", "fallback", None]
- - If set to 'abort' any request not found in the HAR file will be aborted.
- - If set to 'fallback' missing requests will be sent to the network.
- Defaults to abort.
- update : Union[bool, None]
- If specified, updates the given HAR with the actual network information instead of serving from file. The file is
- written to disk when `browser_context.close()` is called.
- update_content : Union["attach", "embed", None]
- Optional setting to control resource content management. If `attach` is specified, resources are persisted as
- separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
- update_mode : Union["full", "minimal", None]
- When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
- `minimal`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.route_from_har(
- har=har,
- url=url,
- notFound=not_found,
- update=update,
- updateContent=update_content,
- updateMode=update_mode,
- )
- )
- )
- def screenshot(
- self,
- *,
- timeout: typing.Optional[float] = None,
- type: typing.Optional[Literal["jpeg", "png"]] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- quality: typing.Optional[int] = None,
- omit_background: typing.Optional[bool] = None,
- full_page: typing.Optional[bool] = None,
- clip: typing.Optional[FloatRect] = None,
- animations: typing.Optional[Literal["allow", "disabled"]] = None,
- caret: typing.Optional[Literal["hide", "initial"]] = None,
- scale: typing.Optional[Literal["css", "device"]] = None,
- mask: typing.Optional[typing.Sequence["Locator"]] = None,
- mask_color: typing.Optional[str] = None,
- style: typing.Optional[str] = None,
- ) -> bytes:
- """Page.screenshot
- Returns the buffer with the captured screenshot.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- type : Union["jpeg", "png", None]
- Specify screenshot type, defaults to `png`.
- path : Union[pathlib.Path, str, None]
- The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
- relative path, then it is resolved relative to the current working directory. If no path is provided, the image
- won't be saved to the disk.
- quality : Union[int, None]
- The quality of the image, between 0-100. Not applicable to `png` images.
- omit_background : Union[bool, None]
- Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
- Defaults to `false`.
- full_page : Union[bool, None]
- When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to
- `false`.
- clip : Union[{x: float, y: float, width: float, height: float}, None]
- An object which specifies clipping of the resulting image.
- animations : Union["allow", "disabled", None]
- When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
- treatment depending on their duration:
- - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
- - infinite animations are canceled to initial state, and then played over after the screenshot.
- Defaults to `"allow"` that leaves animations untouched.
- caret : Union["hide", "initial", None]
- When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
- changed. Defaults to `"hide"`.
- scale : Union["css", "device", None]
- When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
- will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
- screenshots of high-dpi devices will be twice as large or even larger.
- Defaults to `"device"`.
- mask : Union[Sequence[Locator], None]
- Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
- box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
- invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
- that.
- mask_color : Union[str, None]
- Specify the color of the overlay box for masked elements, in
- [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
- style : Union[str, None]
- Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
- elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
- the Shadow DOM and applies to the inner frames.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.screenshot(
- timeout=timeout,
- type=type,
- path=path,
- quality=quality,
- omitBackground=omit_background,
- fullPage=full_page,
- clip=clip,
- animations=animations,
- caret=caret,
- scale=scale,
- mask=mapping.to_impl(mask),
- maskColor=mask_color,
- style=style,
- )
- )
- )
- def title(self) -> str:
- """Page.title
- Returns the page's title.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.title()))
- def close(
- self,
- *,
- run_before_unload: typing.Optional[bool] = None,
- reason: typing.Optional[str] = None,
- ) -> None:
- """Page.close
- If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If
- `runBeforeUnload` is `true` the method will run unload handlers, but will **not** wait for the page to close.
- By default, `page.close()` **does not** run `beforeunload` handlers.
- **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned and should be handled
- manually via `page.on('dialog')` event.
- Parameters
- ----------
- run_before_unload : Union[bool, None]
- Defaults to `false`. Whether to run the
- [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) page handlers.
- reason : Union[str, None]
- The reason to be reported to the operations interrupted by the page closure.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.close(runBeforeUnload=run_before_unload, reason=reason)
- )
- )
- def is_closed(self) -> bool:
- """Page.is_closed
- Indicates that the page has been closed.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.is_closed())
- def click(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- ) -> None:
- """Page.click
- This method clicks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
- 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.click(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- clickCount=click_count,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- strict=strict,
- )
- )
- )
- def dblclick(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Page.dblclick
- This method double clicks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dblclick(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def tap(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Page.tap
- This method taps an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `page.tap()` the method will throw if `hasTouch` option of the browser context is false.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.tap(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def fill(
- self,
- selector: str,
- value: str,
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> None:
- """Page.fill
- This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks,
- focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string
- to clear the input field.
- If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- error. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
- instead.
- To send fine-grained keyboard events, use `locator.press_sequentially()`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- value : str
- Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.fill(
- selector=selector,
- value=value,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- strict=strict,
- force=force,
- )
- )
- )
- def locator(
- self,
- selector: str,
- *,
- has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has: typing.Optional["Locator"] = None,
- has_not: typing.Optional["Locator"] = None,
- ) -> "Locator":
- """Page.locator
- The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved
- to the element immediately before performing an action, so a series of actions on the same locator can in fact be
- performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
- [Learn more about locators](https://playwright.dev/python/docs/locators).
- Parameters
- ----------
- selector : str
- A selector to use when resolving DOM element.
- has_text : Union[Pattern[str], str, None]
- Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- `<article><div>Playwright</div></article>`.
- has_not_text : Union[Pattern[str], str, None]
- Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- When passed a [string], matching is case-insensitive and searches for a substring.
- has : Union[Locator, None]
- Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- the document root. For example, you can find `content` that has `div` in
- `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- has_not : Union[Locator, None]
- Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.locator(
- selector=selector,
- hasText=has_text,
- hasNotText=has_not_text,
- has=has._impl_obj if has else None,
- hasNot=has_not._impl_obj if has_not else None,
- )
- )
- def get_by_alt_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Page.get_by_alt_text
- Allows locating elements by their alt text.
- **Usage**
- For example, this method will find the image by alt text \"Playwright logo\":
- ```html
- <img alt='Playwright logo'>
- ```
- ```py
- page.get_by_alt_text(\"Playwright logo\").click()
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
- def get_by_label(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Page.get_by_label
- Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
- `aria-label` attribute.
- **Usage**
- For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
- ```html
- <input aria-label=\"Username\">
- <label for=\"password-input\">Password:</label>
- <input id=\"password-input\">
- ```
- ```py
- page.get_by_label(\"Username\").fill(\"john\")
- page.get_by_label(\"Password\").fill(\"secret\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
- def get_by_placeholder(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Page.get_by_placeholder
- Allows locating input elements by the placeholder text.
- **Usage**
- For example, consider the following DOM structure.
- ```html
- <input type=\"email\" placeholder=\"name@example.com\" />
- ```
- You can fill the input after locating it by the placeholder text:
- ```py
- page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_placeholder(text=text, exact=exact)
- )
- def get_by_role(
- self,
- role: Literal[
- "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",
- ],
- *,
- checked: typing.Optional[bool] = None,
- disabled: typing.Optional[bool] = None,
- expanded: typing.Optional[bool] = None,
- include_hidden: typing.Optional[bool] = None,
- level: typing.Optional[int] = None,
- name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- pressed: typing.Optional[bool] = None,
- selected: typing.Optional[bool] = None,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Page.get_by_role
- Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
- [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- **Usage**
- Consider the following DOM structure.
- ```html
- <h3>Sign up</h3>
- <label>
- <input type=\"checkbox\" /> Subscribe
- </label>
- <br/>
- <button>Submit</button>
- ```
- You can locate each element by it's implicit role:
- ```py
- expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
- page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
- page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
- ```
- **Details**
- Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
- about the ARIA guidelines.
- Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
- that is recognized by the role selector. You can find all the
- [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
- duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
- Parameters
- ----------
- 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"]
- Required aria role.
- checked : Union[bool, None]
- An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
- Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
- disabled : Union[bool, None]
- An attribute that is usually set by `aria-disabled` or `disabled`.
- **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
- [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
- expanded : Union[bool, None]
- An attribute that is usually set by `aria-expanded`.
- Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
- include_hidden : Union[bool, None]
- Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
- [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
- Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
- level : Union[int, None]
- A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
- for `<h1>-<h6>` elements.
- Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
- name : Union[Pattern[str], str, None]
- Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
- case-insensitive and searches for a substring, use `exact` to control this behavior.
- Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- pressed : Union[bool, None]
- An attribute that is usually set by `aria-pressed`.
- Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
- selected : Union[bool, None]
- An attribute that is usually set by `aria-selected`.
- Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
- exact : Union[bool, None]
- Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_role(
- role=role,
- checked=checked,
- disabled=disabled,
- expanded=expanded,
- includeHidden=include_hidden,
- level=level,
- name=name,
- pressed=pressed,
- selected=selected,
- exact=exact,
- )
- )
- def get_by_test_id(
- self, test_id: typing.Union[str, typing.Pattern[str]]
- ) -> "Locator":
- """Page.get_by_test_id
- Locate element by the test id.
- **Usage**
- Consider the following DOM structure.
- ```html
- <button data-testid=\"directions\">Itinéraire</button>
- ```
- You can locate the element by it's test id:
- ```py
- page.get_by_test_id(\"directions\").click()
- ```
- **Details**
- By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
- configure a different test id attribute if necessary.
- Parameters
- ----------
- test_id : Union[Pattern[str], str]
- Id to locate the element by.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
- def get_by_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Page.get_by_text
- Allows locating elements that contain given text.
- See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
- filter by the text content.
- **Usage**
- Consider the following DOM structure:
- ```html
- <div>Hello <span>world</span></div>
- <div>Hello</div>
- ```
- You can locate by text substring, exact string, or a regular expression:
- ```py
- # Matches <span>
- page.get_by_text(\"world\")
- # Matches first <div>
- page.get_by_text(\"Hello world\")
- # Matches second <div>
- page.get_by_text(\"Hello\", exact=True)
- # Matches both <div>s
- page.get_by_text(re.compile(\"Hello\"))
- # Matches second <div>
- page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
- ```
- **Details**
- Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
- one, turns line breaks into spaces and ignores leading and trailing whitespace.
- Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
- example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
- def get_by_title(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Page.get_by_title
- Allows locating elements by their title attribute.
- **Usage**
- Consider the following DOM structure.
- ```html
- <span title='Issues count'>25 issues</span>
- ```
- You can check the issues count after locating it by the title text:
- ```py
- expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
- def frame_locator(self, selector: str) -> "FrameLocator":
- """Page.frame_locator
- When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
- in that iframe.
- **Usage**
- Following snippet locates element with text \"Submit\" in the iframe with id `my-frame`, like `<iframe
- id=\"my-frame\">`:
- ```py
- locator = page.frame_locator(\"#my-iframe\").get_by_text(\"Submit\")
- locator.click()
- ```
- Parameters
- ----------
- selector : str
- A selector to use when resolving DOM element.
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
- def focus(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Page.focus
- This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the
- method waits until a matching element appears in the DOM.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.focus(selector=selector, strict=strict, timeout=timeout)
- )
- )
- def text_content(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> typing.Optional[str]:
- """Page.text_content
- Returns `element.textContent`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.text_content(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def inner_text(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> str:
- """Page.inner_text
- Returns `element.innerText`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.inner_text(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def inner_html(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> str:
- """Page.inner_html
- Returns `element.innerHTML`.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.inner_html(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def get_attribute(
- self,
- selector: str,
- name: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> typing.Optional[str]:
- """Page.get_attribute
- Returns element attribute value.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- name : str
- Attribute name to get the value for.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.get_attribute(
- selector=selector, name=name, strict=strict, timeout=timeout
- )
- )
- )
- def hover(
- self,
- selector: str,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Page.hover
- This method hovers over an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.hover(
- selector=selector,
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- force=force,
- strict=strict,
- trial=trial,
- )
- )
- )
- def drag_and_drop(
- self,
- source: str,
- target: str,
- *,
- source_position: typing.Optional[Position] = None,
- target_position: typing.Optional[Position] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """Page.drag_and_drop
- This method drags the source element to the target element. It will first move to the source element, perform a
- `mousedown`, then move to the target element and perform a `mouseup`.
- **Usage**
- ```py
- page.drag_and_drop(\"#source\", \"#target\")
- # or specify exact positions relative to the top-left corners of the elements:
- page.drag_and_drop(
- \"#source\",
- \"#target\",
- source_position={\"x\": 34, \"y\": 7},
- target_position={\"x\": 10, \"y\": 20}
- )
- ```
- Parameters
- ----------
- source : str
- A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will
- be used.
- target : str
- A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first
- will be used.
- source_position : Union[{x: float, y: float}, None]
- Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
- specified, some visible point of the element is used.
- target_position : Union[{x: float, y: float}, None]
- Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
- specified, some visible point of the element is used.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
- of the drag. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.drag_and_drop(
- source=source,
- target=target,
- sourcePosition=source_position,
- targetPosition=target_position,
- force=force,
- noWaitAfter=no_wait_after,
- timeout=timeout,
- strict=strict,
- trial=trial,
- steps=steps,
- )
- )
- )
- def select_option(
- self,
- selector: str,
- value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- *,
- index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
- label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- element: typing.Optional[
- typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
- ] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- ) -> typing.List[str]:
- """Page.select_option
- This method waits for an element matching `selector`, waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits
- until all specified options are present in the `<select>` element and selects these options.
- If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
- instead.
- Returns the array of option values that have been successfully selected.
- Triggers a `change` and `input` event once all the provided options have been selected.
- **Usage**
- ```py
- # Single selection matching the value or label
- page.select_option(\"select#colors\", \"blue\")
- # single selection matching both the label
- page.select_option(\"select#colors\", label=\"blue\")
- # multiple selection
- page.select_option(\"select#colors\", value=[\"red\", \"green\", \"blue\"])
- ```
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- value : Union[Sequence[str], str, None]
- Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- index : Union[Sequence[int], int, None]
- Options to select by index. Optional.
- label : Union[Sequence[str], str, None]
- Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- element : Union[ElementHandle, Sequence[ElementHandle], None]
- Option elements to select. Optional.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.select_option(
- selector=selector,
- value=mapping.to_impl(value),
- index=mapping.to_impl(index),
- label=mapping.to_impl(label),
- element=mapping.to_impl(element),
- timeout=timeout,
- noWaitAfter=no_wait_after,
- force=force,
- strict=strict,
- )
- )
- )
- def input_value(
- self,
- selector: str,
- *,
- strict: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> str:
- """Page.input_value
- Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
- Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
- control.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.input_value(
- selector=selector, strict=strict, timeout=timeout
- )
- )
- )
- def set_input_files(
- self,
- selector: str,
- files: typing.Union[
- str,
- pathlib.Path,
- FilePayload,
- typing.Sequence[typing.Union[str, pathlib.Path]],
- typing.Sequence[FilePayload],
- ],
- *,
- timeout: typing.Optional[float] = None,
- strict: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Page.set_input_files
- Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
- they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
- with a `[webkitdirectory]` attribute, only a single directory path is supported.
- This method expects `selector` to point to an
- [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_input_files(
- selector=selector,
- files=mapping.to_impl(files),
- timeout=timeout,
- strict=strict,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def type(
- self,
- selector: str,
- text: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- ) -> None:
- """Page.type
- Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to
- send fine-grained keyboard events. To fill values in form fields, use `page.fill()`.
- To press a special key, like `Control` or `ArrowDown`, use `keyboard.press()`.
- **Usage**
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- text : str
- A text to type into a focused element.
- delay : Union[float, None]
- Time to wait between key presses in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.type(
- selector=selector,
- text=text,
- delay=delay,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- strict=strict,
- )
- )
- )
- def press(
- self,
- selector: str,
- key: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- ) -> None:
- """Page.press
- Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
- `key` can specify the intended
- [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- to generate the text for. A superset of the `key` values can be found
- [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- etc.
- Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
- Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- texts.
- Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
- specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- **Usage**
- ```py
- page = browser.new_page()
- page.goto(\"https://keycode.info\")
- page.press(\"body\", \"A\")
- page.screenshot(path=\"a.png\")
- page.press(\"body\", \"ArrowLeft\")
- page.screenshot(path=\"arrow_left.png\")
- page.press(\"body\", \"Shift+O\")
- page.screenshot(path=\"o.png\")
- browser.close()
- ```
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- delay : Union[float, None]
- Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.press(
- selector=selector,
- key=key,
- delay=delay,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- strict=strict,
- )
- )
- )
- def check(
- self,
- selector: str,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Page.check
- This method checks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
- already checked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.check(
- selector=selector,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def uncheck(
- self,
- selector: str,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Page.uncheck
- This method unchecks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is
- already unchecked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now unchecked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.uncheck(
- selector=selector,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def wait_for_timeout(self, timeout: float) -> None:
- """Page.wait_for_timeout
- Waits for the given `timeout` in milliseconds.
- Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going
- to be flaky. Use signals such as network events, selectors becoming visible and others instead.
- **Usage**
- ```py
- # wait for 1 second
- page.wait_for_timeout(1000)
- ```
- Parameters
- ----------
- timeout : float
- A timeout to wait for
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.wait_for_timeout(timeout=timeout))
- )
- def wait_for_function(
- self,
- expression: str,
- *,
- arg: typing.Optional[typing.Any] = None,
- timeout: typing.Optional[float] = None,
- polling: typing.Optional[typing.Union[float, Literal["raf"]]] = None,
- ) -> "JSHandle":
- """Page.wait_for_function
- Returns when the `expression` returns a truthy value. It resolves to a JSHandle of the truthy value.
- **Usage**
- The `page.wait_for_function()` can be used to observe viewport size change:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- webkit = playwright.webkit
- browser = webkit.launch()
- page = browser.new_page()
- page.evaluate(\"window.x = 0; setTimeout(() => { window.x = 100 }, 1000);\")
- page.wait_for_function(\"() => window.x > 0\")
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- To pass an argument to the predicate of `page.wait_for_function()` function:
- ```py
- selector = \".foo\"
- page.wait_for_function(\"selector => !!document.querySelector(selector)\", selector)
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()` or
- `page.set_default_timeout()` methods.
- polling : Union["raf", float, None]
- If `polling` is `'raf'`, then `expression` is constantly executed in `requestAnimationFrame` callback. If `polling`
- is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to
- `raf`.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.wait_for_function(
- expression=expression,
- arg=mapping.to_impl(arg),
- timeout=timeout,
- polling=polling,
- )
- )
- )
- def pause(self) -> None:
- """Page.pause
- Pauses script execution. Playwright will stop executing the script and wait for the user to either press the
- 'Resume' button in the page overlay or to call `playwright.resume()` in the DevTools console.
- User can inspect selectors or perform manual steps while paused. Resume will continue running the original script
- from the place it was paused.
- **NOTE** This method requires Playwright to be started in a headed mode, with a falsy `headless` option.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.pause()))
- def pdf(
- self,
- *,
- scale: typing.Optional[float] = None,
- display_header_footer: typing.Optional[bool] = None,
- header_template: typing.Optional[str] = None,
- footer_template: typing.Optional[str] = None,
- print_background: typing.Optional[bool] = None,
- landscape: typing.Optional[bool] = None,
- page_ranges: typing.Optional[str] = None,
- format: typing.Optional[str] = None,
- width: typing.Optional[typing.Union[str, float]] = None,
- height: typing.Optional[typing.Union[str, float]] = None,
- prefer_css_page_size: typing.Optional[bool] = None,
- margin: typing.Optional[PdfMargins] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- outline: typing.Optional[bool] = None,
- tagged: typing.Optional[bool] = None,
- ) -> bytes:
- """Page.pdf
- Returns the PDF buffer.
- `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
- `page.emulate_media()` before calling `page.pdf()`:
- **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
- [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust)
- property to force rendering of exact colors.
- **Usage**
- ```py
- # generates a pdf with \"screen\" media type.
- page.emulate_media(media=\"screen\")
- page.pdf(path=\"page.pdf\")
- ```
- The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as
- pixels.
- A few examples:
- - `page.pdf({width: 100})` - prints with width set to 100 pixels
- - `page.pdf({width: '100px'})` - prints with width set to 100 pixels
- - `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
- All possible units are:
- - `px` - pixel
- - `in` - inch
- - `cm` - centimeter
- - `mm` - millimeter
- The `format` options are:
- - `Letter`: 8.5in x 11in
- - `Legal`: 8.5in x 14in
- - `Tabloid`: 11in x 17in
- - `Ledger`: 17in x 11in
- - `A0`: 33.1in x 46.8in
- - `A1`: 23.4in x 33.1in
- - `A2`: 16.54in x 23.4in
- - `A3`: 11.7in x 16.54in
- - `A4`: 8.27in x 11.7in
- - `A5`: 5.83in x 8.27in
- - `A6`: 4.13in x 5.83in
- **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations: > 1. Script tags inside
- templates are not evaluated. > 2. Page styles are not visible inside templates.
- Parameters
- ----------
- scale : Union[float, None]
- Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
- display_header_footer : Union[bool, None]
- Display header and footer. Defaults to `false`.
- header_template : Union[str, None]
- HTML template for the print header. Should be valid HTML markup with following classes used to inject printing
- values into them:
- - `'date'` formatted print date
- - `'title'` document title
- - `'url'` document location
- - `'pageNumber'` current page number
- - `'totalPages'` total pages in the document
- footer_template : Union[str, None]
- HTML template for the print footer. Should use the same format as the `headerTemplate`.
- print_background : Union[bool, None]
- Print background graphics. Defaults to `false`.
- landscape : Union[bool, None]
- Paper orientation. Defaults to `false`.
- page_ranges : Union[str, None]
- Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
- format : Union[str, None]
- Paper format. If set, takes priority over `width` or `height` options. Defaults to 'Letter'.
- width : Union[float, str, None]
- Paper width, accepts values labeled with units.
- height : Union[float, str, None]
- Paper height, accepts values labeled with units.
- prefer_css_page_size : Union[bool, None]
- Give any CSS `@page` size declared in the page priority over what is declared in `width` and `height` or `format`
- options. Defaults to `false`, which will scale the content to fit the paper size.
- margin : Union[{top: Union[float, str, None], right: Union[float, str, None], bottom: Union[float, str, None], left: Union[float, str, None]}, None]
- Paper margins, defaults to none.
- path : Union[pathlib.Path, str, None]
- The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to the current working
- directory. If no path is provided, the PDF won't be saved to the disk.
- outline : Union[bool, None]
- Whether or not to embed the document outline into the PDF. Defaults to `false`.
- tagged : Union[bool, None]
- Whether or not to generate tagged (accessible) PDF. Defaults to `false`.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.pdf(
- scale=scale,
- displayHeaderFooter=display_header_footer,
- headerTemplate=header_template,
- footerTemplate=footer_template,
- printBackground=print_background,
- landscape=landscape,
- pageRanges=page_ranges,
- format=format,
- width=width,
- height=height,
- preferCSSPageSize=prefer_css_page_size,
- margin=margin,
- path=path,
- outline=outline,
- tagged=tagged,
- )
- )
- )
- def expect_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager:
- """Page.expect_event
- Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
- value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
- **Usage**
- ```py
- with page.expect_event(\"framenavigated\") as event_info:
- page.get_by_role(\"button\")
- frame = event_info.value
- ```
- Parameters
- ----------
- event : str
- Event name, same one typically passed into `*.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_event(
- event=event, predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_console_message(
- self,
- predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["ConsoleMessage"]:
- """Page.expect_console_message
- Performs action and waits for a `ConsoleMessage` to be logged by in the page. If predicate is provided, it passes
- `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to return a truthy value.
- Will throw an error if the page is closed before the `page.on('console')` event is fired.
- Parameters
- ----------
- predicate : Union[Callable[[ConsoleMessage], bool], None]
- Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[ConsoleMessage]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_console_message(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_download(
- self,
- predicate: typing.Optional[typing.Callable[["Download"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Download"]:
- """Page.expect_download
- Performs action and waits for a new `Download`. If predicate is provided, it passes `Download` value into the
- `predicate` function and waits for `predicate(download)` to return a truthy value. Will throw an error if the page
- is closed before the download event is fired.
- Parameters
- ----------
- predicate : Union[Callable[[Download], bool], None]
- Receives the `Download` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[Download]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_download(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_file_chooser(
- self,
- predicate: typing.Optional[typing.Callable[["FileChooser"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["FileChooser"]:
- """Page.expect_file_chooser
- Performs action and waits for a new `FileChooser` to be created. If predicate is provided, it passes `FileChooser`
- value into the `predicate` function and waits for `predicate(fileChooser)` to return a truthy value. Will throw an
- error if the page is closed before the file chooser is opened.
- Parameters
- ----------
- predicate : Union[Callable[[FileChooser], bool], None]
- Receives the `FileChooser` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[FileChooser]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_file_chooser(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_navigation(
- self,
- *,
- url: typing.Optional[
- typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]
- ] = None,
- wait_until: typing.Optional[
- Literal["commit", "domcontentloaded", "load", "networkidle"]
- ] = None,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Response"]:
- """Page.expect_navigation
- Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the
- navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
- navigation due to History API usage, the navigation will resolve with `null`.
- **Usage**
- This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will
- indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from
- a `setTimeout`. Consider this example:
- ```py
- with page.expect_navigation():
- # This action triggers the navigation after a timeout.
- page.get_by_text(\"Navigate after timeout\").click()
- # Resolves after navigation has finished
- ```
- **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
- is considered a navigation.
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str, None]
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- equal to the string.
- wait_until : Union["commit", "domcontentloaded", "load", "networkidle", None]
- When to consider operation succeeded, defaults to `load`. Events can be either:
- - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- - `'load'` - consider operation to be finished when the `load` event is fired.
- - `'networkidle'` - **DISCOURAGED** consider operation to be finished when there are no network connections for
- at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
- - `'commit'` - consider operation to be finished when network response is received and the document started
- loading.
- timeout : Union[float, None]
- Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_navigation_timeout()`,
- `browser_context.set_default_timeout()`, `page.set_default_navigation_timeout()` or
- `page.set_default_timeout()` methods.
- Returns
- -------
- EventContextManager[Response]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_navigation(
- url=self._wrap_handler(url), waitUntil=wait_until, timeout=timeout
- ).future,
- )
- def expect_popup(
- self,
- predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Page"]:
- """Page.expect_popup
- Performs action and waits for a popup `Page`. If predicate is provided, it passes [Popup] value into the
- `predicate` function and waits for `predicate(page)` to return a truthy value. Will throw an error if the page is
- closed before the popup event is fired.
- Parameters
- ----------
- predicate : Union[Callable[[Page], bool], None]
- Receives the `Page` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[Page]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_popup(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_request(
- self,
- url_or_predicate: typing.Union[
- str, typing.Pattern[str], typing.Callable[["Request"], bool]
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Request"]:
- """Page.expect_request
- Waits for the matching request and returns it. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more
- details about events.
- **Usage**
- ```py
- with page.expect_request(\"http://example.com/resource\") as first:
- page.get_by_text(\"trigger request\").click()
- first_request = first.value
- # or with a lambda
- with page.expect_request(lambda request: request.url == \"http://example.com\" and request.method == \"get\") as second:
- page.get_by_text(\"trigger request\").click()
- second_request = second.value
- ```
- Parameters
- ----------
- url_or_predicate : Union[Callable[[Request], bool], Pattern[str], str]
- Request URL string, regex or predicate receiving `Request` object. When a `baseURL` via the context options was
- provided and the passed URL is a path, it gets merged via the
- [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
- timeout : Union[float, None]
- Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
- be changed by using the `page.set_default_timeout()` method.
- Returns
- -------
- EventContextManager[Request]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_request(
- urlOrPredicate=self._wrap_handler(url_or_predicate), timeout=timeout
- ).future,
- )
- def expect_request_finished(
- self,
- predicate: typing.Optional[typing.Callable[["Request"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Request"]:
- """Page.expect_request_finished
- Performs action and waits for a `Request` to finish loading. If predicate is provided, it passes `Request` value
- into the `predicate` function and waits for `predicate(request)` to return a truthy value. Will throw an error if
- the page is closed before the `page.on('request_finished')` event is fired.
- Parameters
- ----------
- predicate : Union[Callable[[Request], bool], None]
- Receives the `Request` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[Request]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_request_finished(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_response(
- self,
- url_or_predicate: typing.Union[
- str, typing.Pattern[str], typing.Callable[["Response"], bool]
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Response"]:
- """Page.expect_response
- Returns the matched response. See [waiting for event](https://playwright.dev/python/docs/events#waiting-for-event) for more details about
- events.
- **Usage**
- ```py
- with page.expect_response(\"https://example.com/resource\") as response_info:
- page.get_by_text(\"trigger response\").click()
- response = response_info.value
- return response.ok
- # or with a lambda
- with page.expect_response(lambda response: response.url == \"https://example.com\" and response.status == 200 and response.request.method == \"get\") as response_info:
- page.get_by_text(\"trigger response\").click()
- response = response_info.value
- return response.ok
- ```
- Parameters
- ----------
- url_or_predicate : Union[Callable[[Response], bool], Pattern[str], str]
- Request URL string, regex or predicate receiving `Response` object. When a `baseURL` via the context options was
- provided and the passed URL is a path, it gets merged via the
- [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
- timeout : Union[float, None]
- Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- EventContextManager[Response]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_response(
- urlOrPredicate=self._wrap_handler(url_or_predicate), timeout=timeout
- ).future,
- )
- def expect_websocket(
- self,
- predicate: typing.Optional[typing.Callable[["WebSocket"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["WebSocket"]:
- """Page.expect_websocket
- Performs action and waits for a new `WebSocket`. If predicate is provided, it passes `WebSocket` value into the
- `predicate` function and waits for `predicate(webSocket)` to return a truthy value. Will throw an error if the page
- is closed before the WebSocket event is fired.
- Parameters
- ----------
- predicate : Union[Callable[[WebSocket], bool], None]
- Receives the `WebSocket` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[WebSocket]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_websocket(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_worker(
- self,
- predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Worker"]:
- """Page.expect_worker
- Performs action and waits for a new `Worker`. If predicate is provided, it passes `Worker` value into the
- `predicate` function and waits for `predicate(worker)` to return a truthy value. Will throw an error if the page is
- closed before the worker event is fired.
- Parameters
- ----------
- predicate : Union[Callable[[Worker], bool], None]
- Receives the `Worker` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[Worker]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_worker(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def set_checked(
- self,
- selector: str,
- checked: bool,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- strict: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Page.set_checked
- This method checks or unchecks an element matching `selector` by performing the following steps:
- 1. Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- 1. If the element already has the right checked state, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked or unchecked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- selector : str
- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be
- used.
- checked : bool
- Whether to check or uncheck the checkbox.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- strict : Union[bool, None]
- When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- element, the call throws an exception.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_checked(
- selector=selector,
- checked=checked,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- strict=strict,
- trial=trial,
- )
- )
- )
- def add_locator_handler(
- self,
- locator: "Locator",
- handler: typing.Union[
- typing.Callable[["Locator"], typing.Any], typing.Callable[[], typing.Any]
- ],
- *,
- no_wait_after: typing.Optional[bool] = None,
- times: typing.Optional[int] = None,
- ) -> None:
- """Page.add_locator_handler
- When testing a web page, sometimes unexpected overlays like a \"Sign up\" dialog appear and block actions you want to
- automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making
- them tricky to handle in automated tests.
- This method lets you set up a special function, called a handler, that activates when it detects that overlay is
- visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
- Things to keep in mind:
- - When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as
- a part of your normal test flow, instead of using `page.add_locator_handler()`.
- - Playwright checks for the overlay every time before executing or retrying an action that requires an
- [actionability check](https://playwright.dev/python/docs/actionability), or before performing an auto-waiting assertion check. When overlay
- is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the
- handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't
- perform any actions, the handler will not be triggered.
- - After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible
- anymore. You can opt-out of this behavior with `noWaitAfter`.
- - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler.
- If your handler takes too long, it might cause timeouts.
- - You can register multiple handlers. However, only a single handler will be running at a time. Make sure the
- actions within a handler don't depend on another handler.
- **NOTE** Running the handler will alter your page state mid-test. For example it will change the currently focused
- element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on
- the focus and mouse state being unchanged.
- For example, consider a test that calls `locator.focus()` followed by `keyboard.press()`. If your
- handler clicks a button between these two actions, the focused element most likely will be wrong, and key press
- will happen on the unexpected element. Use `locator.press()` instead to avoid this problem.
- Another example is a series of mouse actions, where `mouse.move()` is followed by `mouse.down()`.
- Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down.
- Prefer self-contained actions like `locator.click()` that do not rely on the state being unchanged by a
- handler.
- **Usage**
- An example that closes a \"Sign up to the newsletter\" dialog when it appears:
- ```py
- # Setup the handler.
- async def handler():
- await page.get_by_role(\"button\", name=\"No thanks\").click()
- await page.add_locator_handler(page.get_by_text(\"Sign up to the newsletter\"), handler)
- # Write the test as usual.
- await page.goto(\"https://example.com\")
- await page.get_by_role(\"button\", name=\"Start here\").click()
- ```
- An example that skips the \"Confirm your security details\" page when it is shown:
- ```py
- # Setup the handler.
- async def handler():
- await page.get_by_role(\"button\", name=\"Remind me later\").click()
- await page.add_locator_handler(page.get_by_text(\"Confirm your security details\"), handler)
- # Write the test as usual.
- await page.goto(\"https://example.com\")
- await page.get_by_role(\"button\", name=\"Start here\").click()
- ```
- An example with a custom callback on every actionability check. It uses a `<body>` locator that is always visible,
- so the handler is called before every actionability check. It is important to specify `noWaitAfter`, because the
- handler does not hide the `<body>` element.
- ```py
- # Setup the handler.
- async def handler():
- await page.evaluate(\"window.removeObstructionsForTestIfNeeded()\")
- await page.add_locator_handler(page.locator(\"body\"), handler, no_wait_after=True)
- # Write the test as usual.
- await page.goto(\"https://example.com\")
- await page.get_by_role(\"button\", name=\"Start here\").click()
- ```
- Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
- invocations by setting `times`:
- ```py
- async def handler(locator):
- await locator.click()
- await page.add_locator_handler(page.get_by_label(\"Close\"), handler, times=1)
- ```
- Parameters
- ----------
- locator : Locator
- Locator that triggers the handler.
- handler : Union[Callable[[Locator], Any], Callable[[], Any]]
- Function that should be run once `locator` appears. This function should get rid of the element that blocks actions
- like click.
- no_wait_after : Union[bool, None]
- By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then
- Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of
- this behavior, so that overlay can stay visible after the handler has run.
- times : Union[int, None]
- Specifies the maximum number of times this handler should be called. Unlimited by default.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.add_locator_handler(
- locator=locator._impl_obj,
- handler=self._wrap_handler(handler),
- noWaitAfter=no_wait_after,
- times=times,
- )
- )
- )
- def remove_locator_handler(self, locator: "Locator") -> None:
- """Page.remove_locator_handler
- Removes all locator handlers added by `page.add_locator_handler()` for a specific locator.
- Parameters
- ----------
- locator : Locator
- Locator passed to `page.add_locator_handler()`.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.remove_locator_handler(locator=locator._impl_obj))
- )
- def requests(self) -> typing.List["Request"]:
- """Page.requests
- Returns up to (currently) 100 last network request from this page. See `page.on('request')` for more details.
- Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory
- growth as new requests come in. Once collected, retrieving most information about the request is impossible.
- Note that requests reported through the `page.on('request')` request are not collected, so there is a trade off
- between efficient memory usage with `page.requests()` and the amount of available information reported
- through `page.on('request')`.
- Returns
- -------
- List[Request]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.requests()))
- def console_messages(self) -> typing.List["ConsoleMessage"]:
- """Page.console_messages
- Returns up to (currently) 200 last console messages from this page. See `page.on('console')` for more details.
- Returns
- -------
- List[ConsoleMessage]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.console_messages()))
- def page_errors(self) -> typing.List["Error"]:
- """Page.page_errors
- Returns up to (currently) 200 last page errors from this page. See `page.on('page_error')` for more details.
- Returns
- -------
- List[Error]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.page_errors()))
- mapping.register(PageImpl, Page)
- class WebError(SyncBase):
- @property
- def page(self) -> typing.Optional["Page"]:
- """WebError.page
- The page that produced this unhandled exception, if any.
- Returns
- -------
- Union[Page, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.page)
- @property
- def error(self) -> "Error":
- """WebError.error
- Unhandled error that was thrown.
- Returns
- -------
- Error
- """
- return mapping.from_impl(self._impl_obj.error)
- mapping.register(WebErrorImpl, WebError)
- class BrowserContext(SyncContextManager):
- @typing.overload
- def on(
- self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- This event is not emitted."""
- @typing.overload
- def on(
- self, event: Literal["close"], f: typing.Callable[["BrowserContext"], "None"]
- ) -> None:
- """
- Emitted when Browser context gets closed. This might happen because of one of the following:
- - Browser context is closed.
- - Browser application is closed or crashed.
- - The `browser.close()` method was called."""
- @typing.overload
- def on(
- self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
- ) -> None:
- """
- Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
- The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
- **Usage**
- ```py
- def print_args(msg):
- for arg in msg.args:
- print(arg.json_value())
- context.on(\"console\", print_args)
- page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
- ```"""
- @typing.overload
- def on(
- self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
- ) -> None:
- """
- Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
- either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
- [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
- and actions like click will never finish.
- **Usage**
- ```python
- context.on(\"dialog\", lambda dialog: dialog.accept())
- ```
- **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
- automatically dismissed."""
- @typing.overload
- def on(self, event: Literal["page"], f: typing.Callable[["Page"], "None"]) -> None:
- """
- The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
- will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
- specific page.
- The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
- popup with `window.open('http://example.com')`, this event will fire when the network request to
- \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
- to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
- instead of similar methods on the `Page`.
- ```py
- with context.expect_page() as page_info:
- page.get_by_text(\"open new page\").click(),
- page = page_info.value
- print(page.evaluate(\"location.href\"))
- ```
- **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
- need it in most cases)."""
- @typing.overload
- def on(
- self, event: Literal["weberror"], f: typing.Callable[["WebError"], "None"]
- ) -> None:
- """
- Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
- page, use `page.on('page_error')` instead."""
- @typing.overload
- def on(
- self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
- only listen for requests from a particular page, use `page.on('request')`.
- In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
- """
- @typing.overload
- def on(
- self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
- use `page.on('request_failed')`.
- **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
- will complete with `browser_context.on('request_finished')` event and not with
- `browser_context.on('request_failed')`."""
- @typing.overload
- def on(
- self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request finishes successfully after downloading the response body. For a successful response, the
- sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
- particular page, use `page.on('request_finished')`."""
- @typing.overload
- def on(
- self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
- ) -> None:
- """
- Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
- events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
- `page.on('response')`."""
- @typing.overload
- def on(
- self, event: Literal["serviceworker"], f: typing.Callable[["Worker"], "None"]
- ) -> None:
- """
- **NOTE** Service workers are only supported on Chromium-based browsers.
- Emitted when new service worker is created in the context."""
- def on(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().on(event=event, f=f)
- @typing.overload
- def once(
- self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- This event is not emitted."""
- @typing.overload
- def once(
- self, event: Literal["close"], f: typing.Callable[["BrowserContext"], "None"]
- ) -> None:
- """
- Emitted when Browser context gets closed. This might happen because of one of the following:
- - Browser context is closed.
- - Browser application is closed or crashed.
- - The `browser.close()` method was called."""
- @typing.overload
- def once(
- self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"]
- ) -> None:
- """
- Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
- The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.
- **Usage**
- ```py
- def print_args(msg):
- for arg in msg.args:
- print(arg.json_value())
- context.on(\"console\", print_args)
- page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
- ```"""
- @typing.overload
- def once(
- self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"]
- ) -> None:
- """
- Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
- either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
- [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
- and actions like click will never finish.
- **Usage**
- ```python
- context.on(\"dialog\", lambda dialog: dialog.accept())
- ```
- **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
- automatically dismissed."""
- @typing.overload
- def once(
- self, event: Literal["page"], f: typing.Callable[["Page"], "None"]
- ) -> None:
- """
- The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
- will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
- specific page.
- The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
- popup with `window.open('http://example.com')`, this event will fire when the network request to
- \"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
- to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
- instead of similar methods on the `Page`.
- ```py
- with context.expect_page() as page_info:
- page.get_by_text(\"open new page\").click(),
- page = page_info.value
- print(page.evaluate(\"location.href\"))
- ```
- **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
- need it in most cases)."""
- @typing.overload
- def once(
- self, event: Literal["weberror"], f: typing.Callable[["WebError"], "None"]
- ) -> None:
- """
- Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
- page, use `page.on('page_error')` instead."""
- @typing.overload
- def once(
- self, event: Literal["request"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
- only listen for requests from a particular page, use `page.on('request')`.
- In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.
- """
- @typing.overload
- def once(
- self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
- use `page.on('request_failed')`.
- **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
- will complete with `browser_context.on('request_finished')` event and not with
- `browser_context.on('request_failed')`."""
- @typing.overload
- def once(
- self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"]
- ) -> None:
- """
- Emitted when a request finishes successfully after downloading the response body. For a successful response, the
- sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
- particular page, use `page.on('request_finished')`."""
- @typing.overload
- def once(
- self, event: Literal["response"], f: typing.Callable[["Response"], "None"]
- ) -> None:
- """
- Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
- events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
- `page.on('response')`."""
- @typing.overload
- def once(
- self, event: Literal["serviceworker"], f: typing.Callable[["Worker"], "None"]
- ) -> None:
- """
- **NOTE** Service workers are only supported on Chromium-based browsers.
- Emitted when new service worker is created in the context."""
- def once(self, event: str, f: typing.Callable[..., None]) -> None:
- return super().once(event=event, f=f)
- @property
- def pages(self) -> typing.List["Page"]:
- """BrowserContext.pages
- Returns all open pages in the context.
- Returns
- -------
- List[Page]
- """
- return mapping.from_impl_list(self._impl_obj.pages)
- @property
- def browser(self) -> typing.Optional["Browser"]:
- """BrowserContext.browser
- Gets the browser instance that owns the context. Returns `null` if the context is created outside of normal
- browser, e.g. Android or Electron.
- Returns
- -------
- Union[Browser, None]
- """
- return mapping.from_impl_nullable(self._impl_obj.browser)
- @property
- def background_pages(self) -> typing.List["Page"]:
- """BrowserContext.background_pages
- Returns an empty list.
- Returns
- -------
- List[Page]
- """
- return mapping.from_impl_list(self._impl_obj.background_pages)
- @property
- def service_workers(self) -> typing.List["Worker"]:
- """BrowserContext.service_workers
- **NOTE** Service workers are only supported on Chromium-based browsers.
- All existing service workers in the context.
- Returns
- -------
- List[Worker]
- """
- return mapping.from_impl_list(self._impl_obj.service_workers)
- @property
- def tracing(self) -> "Tracing":
- """BrowserContext.tracing
- Returns
- -------
- Tracing
- """
- return mapping.from_impl(self._impl_obj.tracing)
- @property
- def request(self) -> "APIRequestContext":
- """BrowserContext.request
- API testing helper associated with this context. Requests made with this API will use context cookies.
- Returns
- -------
- APIRequestContext
- """
- return mapping.from_impl(self._impl_obj.request)
- @property
- def clock(self) -> "Clock":
- """BrowserContext.clock
- Playwright has ability to mock clock and passage of time.
- Returns
- -------
- Clock
- """
- return mapping.from_impl(self._impl_obj.clock)
- def set_default_navigation_timeout(self, timeout: float) -> None:
- """BrowserContext.set_default_navigation_timeout
- This setting will change the default maximum navigation time for the following methods and related shortcuts:
- - `page.go_back()`
- - `page.go_forward()`
- - `page.goto()`
- - `page.reload()`
- - `page.set_content()`
- - `page.expect_navigation()`
- **NOTE** `page.set_default_navigation_timeout()` and `page.set_default_timeout()` take priority over
- `browser_context.set_default_navigation_timeout()`.
- Parameters
- ----------
- timeout : float
- Maximum navigation time in milliseconds
- """
- return mapping.from_maybe_impl(
- self._impl_obj.set_default_navigation_timeout(timeout=timeout)
- )
- def set_default_timeout(self, timeout: float) -> None:
- """BrowserContext.set_default_timeout
- This setting will change the default maximum time for all the methods accepting `timeout` option.
- **NOTE** `page.set_default_navigation_timeout()`, `page.set_default_timeout()` and
- `browser_context.set_default_navigation_timeout()` take priority over
- `browser_context.set_default_timeout()`.
- Parameters
- ----------
- timeout : float
- Maximum time in milliseconds. Pass `0` to disable timeout.
- """
- return mapping.from_maybe_impl(
- self._impl_obj.set_default_timeout(timeout=timeout)
- )
- def new_page(self) -> "Page":
- """BrowserContext.new_page
- Creates a new page in the browser context.
- Returns
- -------
- Page
- """
- return mapping.from_impl(self._sync(self._impl_obj.new_page()))
- def cookies(
- self, urls: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None
- ) -> typing.List[Cookie]:
- """BrowserContext.cookies
- If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
- URLs are returned.
- Parameters
- ----------
- urls : Union[Sequence[str], str, None]
- Optional list of URLs.
- Returns
- -------
- List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}]
- """
- return mapping.from_impl_list(
- self._sync(self._impl_obj.cookies(urls=mapping.to_impl(urls)))
- )
- def add_cookies(self, cookies: typing.Sequence[SetCookieParam]) -> None:
- """BrowserContext.add_cookies
- Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies
- can be obtained via `browser_context.cookies()`.
- **Usage**
- ```py
- browser_context.add_cookies([cookie_object1, cookie_object2])
- ```
- Parameters
- ----------
- 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]}]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies)))
- )
- def clear_cookies(
- self,
- *,
- name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- domain: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- path: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- ) -> None:
- """BrowserContext.clear_cookies
- Removes cookies from context. Accepts optional filter.
- **Usage**
- ```py
- context.clear_cookies()
- context.clear_cookies(name=\"session-id\")
- context.clear_cookies(domain=\"my-origin.com\")
- context.clear_cookies(path=\"/api/v1\")
- context.clear_cookies(name=\"session-id\", domain=\"my-origin.com\")
- ```
- Parameters
- ----------
- name : Union[Pattern[str], str, None]
- Only removes cookies with the given name.
- domain : Union[Pattern[str], str, None]
- Only removes cookies with the given domain.
- path : Union[Pattern[str], str, None]
- Only removes cookies with the given path.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.clear_cookies(name=name, domain=domain, path=path)
- )
- )
- def grant_permissions(
- self, permissions: typing.Sequence[str], *, origin: typing.Optional[str] = None
- ) -> None:
- """BrowserContext.grant_permissions
- Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
- specified.
- Parameters
- ----------
- permissions : Sequence[str]
- A list of permissions to grant.
- **NOTE** Supported permissions differ between browsers, and even between different versions of the same browser.
- Any permission may stop working after an update.
- Here are some permissions that may be supported by some browsers:
- - `'accelerometer'`
- - `'ambient-light-sensor'`
- - `'background-sync'`
- - `'camera'`
- - `'clipboard-read'`
- - `'clipboard-write'`
- - `'geolocation'`
- - `'gyroscope'`
- - `'local-fonts'`
- - `'local-network-access'`
- - `'magnetometer'`
- - `'microphone'`
- - `'midi-sysex'` (system-exclusive midi)
- - `'midi'`
- - `'notifications'`
- - `'payment-handler'`
- - `'storage-access'`
- origin : Union[str, None]
- The [origin] to grant permissions to, e.g. "https://example.com".
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.grant_permissions(
- permissions=mapping.to_impl(permissions), origin=origin
- )
- )
- )
- def clear_permissions(self) -> None:
- """BrowserContext.clear_permissions
- Clears all permission overrides for the browser context.
- **Usage**
- ```py
- context = browser.new_context()
- context.grant_permissions([\"clipboard-read\"])
- # do stuff ..
- context.clear_permissions()
- ```
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.clear_permissions()))
- def set_geolocation(self, geolocation: typing.Optional[Geolocation] = None) -> None:
- """BrowserContext.set_geolocation
- Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
- **Usage**
- ```py
- browser_context.set_geolocation({\"latitude\": 59.95, \"longitude\": 30.31667})
- ```
- **NOTE** Consider using `browser_context.grant_permissions()` to grant permissions for the browser context
- pages to read its geolocation.
- Parameters
- ----------
- geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.set_geolocation(geolocation=geolocation))
- )
- def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None:
- """BrowserContext.set_extra_http_headers
- The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are
- merged with page-specific extra HTTP headers set with `page.set_extra_http_headers()`. If page overrides a
- particular header, page-specific header value will be used instead of the browser context header value.
- **NOTE** `browser_context.set_extra_http_headers()` does not guarantee the order of headers in the outgoing
- requests.
- Parameters
- ----------
- headers : Dict[str, str]
- An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_extra_http_headers(headers=mapping.to_impl(headers))
- )
- )
- def set_offline(self, offline: bool) -> None:
- """BrowserContext.set_offline
- Parameters
- ----------
- offline : bool
- Whether to emulate network being offline for the browser context.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.set_offline(offline=offline))
- )
- def add_init_script(
- self,
- script: typing.Optional[str] = None,
- *,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- ) -> None:
- """BrowserContext.add_init_script
- Adds a script which would be evaluated in one of the following scenarios:
- - Whenever a page is created in the browser context or is navigated.
- - Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is
- evaluated in the context of the newly attached frame.
- The script is evaluated after the document was created but before any of its scripts were run. This is useful to
- amend the JavaScript environment, e.g. to seed `Math.random`.
- **Usage**
- An example of overriding `Math.random` before the page loads:
- ```py
- # in your playwright script, assuming the preload.js file is in same directory.
- browser_context.add_init_script(path=\"preload.js\")
- ```
- **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and
- `page.add_init_script()` is not defined.
- Parameters
- ----------
- script : Union[str, None]
- Script to be evaluated in all pages in the browser context. Optional.
- path : Union[pathlib.Path, str, None]
- Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
- directory. Optional.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.add_init_script(script=script, path=path))
- )
- def expose_binding(
- self,
- name: str,
- callback: typing.Callable,
- *,
- handle: typing.Optional[bool] = None,
- ) -> None:
- """BrowserContext.expose_binding
- The method adds a function called `name` on the `window` object of every frame in every page in the context. When
- called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
- If the `callback` returns a [Promise], it will be awaited.
- The first argument of the `callback` function contains information about the caller: `{ browserContext:
- BrowserContext, page: Page, frame: Frame }`.
- See `page.expose_binding()` for page-only version.
- **Usage**
- An example of exposing page URL to all frames in all pages in the context:
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- webkit = playwright.webkit
- browser = webkit.launch(headless=False)
- context = browser.new_context()
- context.expose_binding(\"pageURL\", lambda source: source[\"page\"].url)
- page = context.new_page()
- page.set_content(\"\"\"
- <script>
- async function onClick() {
- document.querySelector('div').textContent = await window.pageURL();
- }
- </script>
- <button onclick=\"onClick()\">Click me</button>
- <div></div>
- \"\"\")
- page.get_by_role(\"button\").click()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- name : str
- Name of the function on the window object.
- callback : Callable
- Callback function that will be called in the Playwright's context.
- handle : Union[bool, None]
- Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
- supported. When passing by value, multiple arguments are supported.
- Deprecated: This option will be removed in the future.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.expose_binding(
- name=name, callback=self._wrap_handler(callback), handle=handle
- )
- )
- )
- def expose_function(self, name: str, callback: typing.Callable) -> None:
- """BrowserContext.expose_function
- The method adds a function called `name` on the `window` object of every frame in every page in the context. When
- called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
- If the `callback` returns a [Promise], it will be awaited.
- See `page.expose_function()` for page-only version.
- **Usage**
- An example of adding a `sha256` function to all pages in the context:
- ```py
- import hashlib
- from playwright.sync_api import sync_playwright
- def sha256(text: str) -> str:
- m = hashlib.sha256()
- m.update(bytes(text, \"utf8\"))
- return m.hexdigest()
- def run(playwright: Playwright):
- webkit = playwright.webkit
- browser = webkit.launch(headless=False)
- context = browser.new_context()
- context.expose_function(\"sha256\", sha256)
- page = context.new_page()
- page.set_content(\"\"\"
- <script>
- async function onClick() {
- document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
- }
- </script>
- <button onclick=\"onClick()\">Click me</button>
- <div></div>
- \"\"\")
- page.get_by_role(\"button\").click()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Parameters
- ----------
- name : str
- Name of the function on the window object.
- callback : Callable
- Callback function that will be called in the Playwright's context.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.expose_function(
- name=name, callback=self._wrap_handler(callback)
- )
- )
- )
- def route(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- handler: typing.Union[
- typing.Callable[["Route"], typing.Any],
- typing.Callable[["Route", "Request"], typing.Any],
- ],
- *,
- times: typing.Optional[int] = None,
- ) -> None:
- """BrowserContext.route
- Routing provides the capability to modify network requests that are made by any page in the browser context. Once
- route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
- **NOTE** `browser_context.route()` will not intercept requests intercepted by Service Worker. See
- [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
- using request interception by setting `serviceWorkers` to `'block'`.
- **Usage**
- An example of a naive handler that aborts all image requests:
- ```py
- context = browser.new_context()
- page = context.new_page()
- context.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort())
- page.goto(\"https://example.com\")
- browser.close()
- ```
- or the same snippet using a regex pattern instead:
- ```py
- context = browser.new_context()
- page = context.new_page()
- context.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort())
- page = await context.new_page()
- page = context.new_page()
- page.goto(\"https://example.com\")
- browser.close()
- ```
- It is possible to examine the request to decide the route action. For example, mocking all requests that contain
- some post data, and leaving all other requests as is:
- ```py
- def handle_route(route: Route):
- if (\"my-string\" in route.request.post_data):
- route.fulfill(body=\"mocked-data\")
- else:
- route.continue_()
- context.route(\"/api/**\", handle_route)
- ```
- Page routes (set up with `page.route()`) take precedence over browser context routes when request matches
- both handlers.
- To remove a route with its handler you can use `browser_context.unroute()`.
- **NOTE** Enabling routing disables http cache.
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
- the context options and the provided URL is a string that does not start with `*`, it is resolved using the
- [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
- handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
- handler function to route the request.
- times : Union[int, None]
- How often a route should be used. By default it will be used every time.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.route(
- url=self._wrap_handler(url),
- handler=self._wrap_handler(handler),
- times=times,
- )
- )
- )
- def unroute(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- handler: typing.Optional[
- typing.Union[
- typing.Callable[["Route"], typing.Any],
- typing.Callable[["Route", "Request"], typing.Any],
- ]
- ] = None,
- ) -> None:
- """BrowserContext.unroute
- Removes a route created with `browser_context.route()`. When `handler` is not specified, removes all routes
- for the `url`.
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
- `browser_context.route()`.
- handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
- Optional handler function used to register a routing with `browser_context.route()`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.unroute(
- url=self._wrap_handler(url), handler=self._wrap_handler(handler)
- )
- )
- )
- def route_web_socket(
- self,
- url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]],
- handler: typing.Callable[["WebSocketRoute"], typing.Any],
- ) -> None:
- """BrowserContext.route_web_socket
- This method allows to modify websocket connections that are made by any page in the browser context.
- Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
- method before creating any pages.
- **Usage**
- Below is an example of a simple handler that blocks some websocket messages. See `WebSocketRoute` for more details
- and examples.
- ```py
- def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
- if message == \"to-be-blocked\":
- return
- ws.send(message)
- def handler(ws: WebSocketRoute):
- ws.route_send(lambda message: message_handler(ws, message))
- ws.connect()
- context.route_web_socket(\"/ws\", handler)
- ```
- Parameters
- ----------
- url : Union[Callable[[str], bool], Pattern[str], str]
- Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
- `baseURL` context option.
- handler : Callable[[WebSocketRoute], Any]
- Handler function to route the WebSocket.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.route_web_socket(
- url=self._wrap_handler(url), handler=self._wrap_handler(handler)
- )
- )
- )
- def unroute_all(
- self,
- *,
- behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None,
- ) -> None:
- """BrowserContext.unroute_all
- Removes all routes created with `browser_context.route()` and `browser_context.route_from_har()`.
- Parameters
- ----------
- behavior : Union["default", "ignoreErrors", "wait", None]
- Specifies whether to wait for already running handlers and what to do if they throw errors:
- - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
- result in unhandled error
- - `'wait'` - wait for current handler calls (if any) to finish
- - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
- after unrouting are silently caught
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.unroute_all(behavior=behavior))
- )
- def route_from_har(
- self,
- har: typing.Union[pathlib.Path, str],
- *,
- url: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- not_found: typing.Optional[Literal["abort", "fallback"]] = None,
- update: typing.Optional[bool] = None,
- update_content: typing.Optional[Literal["attach", "embed"]] = None,
- update_mode: typing.Optional[Literal["full", "minimal"]] = None,
- ) -> None:
- """BrowserContext.route_from_har
- If specified the network requests that are made in the context will be served from the HAR file. Read more about
- [Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).
- Playwright will not serve requests intercepted by Service Worker from the HAR file. See
- [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
- using request interception by setting `serviceWorkers` to `'block'`.
- Parameters
- ----------
- har : Union[pathlib.Path, str]
- Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
- relative path, then it is resolved relative to the current working directory.
- url : Union[Pattern[str], str, None]
- A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
- pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
- not_found : Union["abort", "fallback", None]
- - If set to 'abort' any request not found in the HAR file will be aborted.
- - If set to 'fallback' falls through to the next route handler in the handler chain.
- Defaults to abort.
- update : Union[bool, None]
- If specified, updates the given HAR with the actual network information instead of serving from file. The file is
- written to disk when `browser_context.close()` is called.
- update_content : Union["attach", "embed", None]
- Optional setting to control resource content management. If `attach` is specified, resources are persisted as
- separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
- update_mode : Union["full", "minimal", None]
- When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
- `minimal`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.route_from_har(
- har=har,
- url=url,
- notFound=not_found,
- update=update,
- updateContent=update_content,
- updateMode=update_mode,
- )
- )
- )
- def expect_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager:
- """BrowserContext.expect_event
- Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
- value. Will throw an error if the context closes before the event is fired. Returns the event data value.
- **Usage**
- ```py
- with context.expect_event(\"page\") as event_info:
- page.get_by_role(\"button\").click()
- page = event_info.value
- ```
- Parameters
- ----------
- event : str
- Event name, same one would pass into `browserContext.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_event(
- event=event, predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def close(self, *, reason: typing.Optional[str] = None) -> None:
- """BrowserContext.close
- Closes the browser context. All the pages that belong to the browser context will be closed.
- **NOTE** The default browser context cannot be closed.
- Parameters
- ----------
- reason : Union[str, None]
- The reason to be reported to the operations interrupted by the context closure.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.close(reason=reason)))
- def storage_state(
- self,
- *,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- indexed_db: typing.Optional[bool] = None,
- ) -> StorageState:
- """BrowserContext.storage_state
- Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB
- snapshot.
- Parameters
- ----------
- path : Union[pathlib.Path, str, None]
- The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
- working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
- indexed_db : Union[bool, None]
- Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage
- state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication,
- enable this.
- Returns
- -------
- {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}]}]}
- """
- return mapping.from_impl(
- self._sync(self._impl_obj.storage_state(path=path, indexedDB=indexed_db))
- )
- def wait_for_event(
- self,
- event: str,
- predicate: typing.Optional[typing.Callable] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> typing.Any:
- """BrowserContext.wait_for_event
- **NOTE** In most cases, you should use `browser_context.expect_event()`.
- Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
- and waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed
- before the `event` is fired.
- Parameters
- ----------
- event : str
- Event name, same one typically passed into `*.on(event)`.
- predicate : Union[Callable, None]
- Receives the event data and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.wait_for_event(
- event=event,
- predicate=self._wrap_handler(predicate),
- timeout=timeout,
- )
- )
- )
- def expect_console_message(
- self,
- predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["ConsoleMessage"]:
- """BrowserContext.expect_console_message
- Performs action and waits for a `ConsoleMessage` to be logged by in the pages in the context. If predicate is
- provided, it passes `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to
- return a truthy value. Will throw an error if the page is closed before the `browser_context.on('console')` event
- is fired.
- Parameters
- ----------
- predicate : Union[Callable[[ConsoleMessage], bool], None]
- Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[ConsoleMessage]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_console_message(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def expect_page(
- self,
- predicate: typing.Optional[typing.Callable[["Page"], bool]] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> EventContextManager["Page"]:
- """BrowserContext.expect_page
- Performs action and waits for a new `Page` to be created in the context. If predicate is provided, it passes `Page`
- value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error
- if the context closes before new `Page` is created.
- Parameters
- ----------
- predicate : Union[Callable[[Page], bool], None]
- Receives the `Page` object and resolves to truthy value when the waiting should resolve.
- timeout : Union[float, None]
- Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- default value can be changed by using the `browser_context.set_default_timeout()`.
- Returns
- -------
- EventContextManager[Page]
- """
- return EventContextManager(
- self,
- self._impl_obj.expect_page(
- predicate=self._wrap_handler(predicate), timeout=timeout
- ).future,
- )
- def new_cdp_session(self, page: typing.Union["Page", "Frame"]) -> "CDPSession":
- """BrowserContext.new_cdp_session
- **NOTE** CDP sessions are only supported on Chromium-based browsers.
- Returns the newly created session.
- Parameters
- ----------
- page : Union[Frame, Page]
- Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a
- `Page` or `Frame` type.
- Returns
- -------
- CDPSession
- """
- return mapping.from_impl(self._sync(self._impl_obj.new_cdp_session(page=page)))
- mapping.register(BrowserContextImpl, BrowserContext)
- class CDPSession(SyncBase):
- def send(
- self, method: str, params: typing.Optional[typing.Dict] = None
- ) -> typing.Dict:
- """CDPSession.send
- Parameters
- ----------
- method : str
- Protocol method name.
- params : Union[Dict, None]
- Optional method parameters.
- Returns
- -------
- Dict
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.send(method=method, params=mapping.to_impl(params))
- )
- )
- def detach(self) -> None:
- """CDPSession.detach
- Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
- used to send messages.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.detach()))
- mapping.register(CDPSessionImpl, CDPSession)
- class Browser(SyncContextManager):
- def on(
- self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "None"]
- ) -> None:
- """
- Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
- following:
- - Browser application is closed or crashed.
- - The `browser.close()` method was called."""
- return super().on(event=event, f=f)
- def once(
- self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "None"]
- ) -> None:
- """
- Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
- following:
- - Browser application is closed or crashed.
- - The `browser.close()` method was called."""
- return super().once(event=event, f=f)
- @property
- def contexts(self) -> typing.List["BrowserContext"]:
- """Browser.contexts
- Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
- **Usage**
- ```py
- browser = pw.webkit.launch()
- print(len(browser.contexts)) # prints `0`
- context = browser.new_context()
- print(len(browser.contexts)) # prints `1`
- ```
- Returns
- -------
- List[BrowserContext]
- """
- return mapping.from_impl_list(self._impl_obj.contexts)
- @property
- def browser_type(self) -> "BrowserType":
- """Browser.browser_type
- Get the browser type (chromium, firefox or webkit) that the browser belongs to.
- Returns
- -------
- BrowserType
- """
- return mapping.from_impl(self._impl_obj.browser_type)
- @property
- def version(self) -> str:
- """Browser.version
- Returns the browser version.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.version)
- def is_connected(self) -> bool:
- """Browser.is_connected
- Indicates that the browser is connected.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.is_connected())
- def new_context(
- self,
- *,
- viewport: typing.Optional[ViewportSize] = None,
- screen: typing.Optional[ViewportSize] = None,
- no_viewport: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- java_script_enabled: typing.Optional[bool] = None,
- bypass_csp: typing.Optional[bool] = None,
- user_agent: typing.Optional[str] = None,
- locale: typing.Optional[str] = None,
- timezone_id: typing.Optional[str] = None,
- geolocation: typing.Optional[Geolocation] = None,
- permissions: typing.Optional[typing.Sequence[str]] = None,
- extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
- offline: typing.Optional[bool] = None,
- http_credentials: typing.Optional[HttpCredentials] = None,
- device_scale_factor: typing.Optional[float] = None,
- is_mobile: typing.Optional[bool] = None,
- has_touch: typing.Optional[bool] = None,
- color_scheme: typing.Optional[
- Literal["dark", "light", "no-preference", "null"]
- ] = None,
- reduced_motion: typing.Optional[
- Literal["no-preference", "null", "reduce"]
- ] = None,
- forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
- contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
- accept_downloads: typing.Optional[bool] = None,
- default_browser_type: typing.Optional[str] = None,
- proxy: typing.Optional[ProxySettings] = None,
- record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- record_har_omit_content: typing.Optional[bool] = None,
- record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- record_video_size: typing.Optional[ViewportSize] = None,
- storage_state: typing.Optional[
- typing.Union[StorageState, str, pathlib.Path]
- ] = None,
- base_url: typing.Optional[str] = None,
- strict_selectors: typing.Optional[bool] = None,
- service_workers: typing.Optional[Literal["allow", "block"]] = None,
- record_har_url_filter: typing.Optional[
- typing.Union[typing.Pattern[str], str]
- ] = None,
- record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
- record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
- client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
- ) -> "BrowserContext":
- """Browser.new_context
- Creates a new browser context. It won't share cookies/cache with other browser contexts.
- **NOTE** If directly using this method to create `BrowserContext`s, it is best practice to explicitly close the
- returned context via `browser_context.close()` when your code is done with the `BrowserContext`, and before
- calling `browser.close()`. This will ensure the `context` is closed gracefully and any artifacts—like HARs
- and videos—are fully flushed and saved.
- **Usage**
- ```py
- browser = playwright.firefox.launch() # or \"chromium\" or \"webkit\".
- # create a new incognito browser context.
- context = browser.new_context()
- # create a new page in a pristine context.
- page = context.new_page()
- page.goto(\"https://example.com\")
- # gracefully close up everything
- context.close()
- browser.close()
- ```
- Parameters
- ----------
- viewport : Union[{width: int, height: int}, None]
- Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
- viewport. Learn more about [viewport emulation](../emulation.md#viewport).
- screen : Union[{width: int, height: int}, None]
- Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
- `viewport` is set.
- no_viewport : Union[bool, None]
- Does not enforce fixed viewport, allows resizing window in the headed mode.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- java_script_enabled : Union[bool, None]
- Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- [disabling JavaScript](../emulation.md#javascript-enabled).
- bypass_csp : Union[bool, None]
- Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
- user_agent : Union[str, None]
- Specific user agent to use in this context.
- locale : Union[str, None]
- Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
- `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
- locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
- timezone_id : Union[str, None]
- Changes the timezone of the context. See
- [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
- for a list of supported timezone IDs. Defaults to the system timezone.
- geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
- permissions : Union[Sequence[str], None]
- A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
- more details. Defaults to none.
- extra_http_headers : Union[Dict[str, str], None]
- An object containing additional HTTP headers to be sent with every request. Defaults to none.
- offline : Union[bool, None]
- Whether to emulate network being offline. Defaults to `false`. Learn more about
- [network emulation](../emulation.md#offline).
- http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
- Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- origin is specified, the username and password are sent to any servers upon unauthorized responses.
- device_scale_factor : Union[float, None]
- Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- [emulating devices with device scale factor](../emulation.md#devices).
- is_mobile : Union[bool, None]
- Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- about [mobile emulation](../emulation.md#ismobile).
- has_touch : Union[bool, None]
- Specifies if viewport supports touch events. Defaults to false. Learn more about
- [mobile emulation](../emulation.md#devices).
- color_scheme : Union["dark", "light", "no-preference", "null", None]
- Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
- media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
- Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
- reduced_motion : Union["no-preference", "null", "reduce", None]
- Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'no-preference'`.
- forced_colors : Union["active", "none", "null", None]
- Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'none'`.
- contrast : Union["more", "no-preference", "null", None]
- Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'no-preference'`.
- accept_downloads : Union[bool, None]
- Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
- proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
- Network proxy settings to use with this context. Defaults to none.
- record_har_path : Union[pathlib.Path, str, None]
- Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
- on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
- for the HAR to be saved.
- record_har_omit_content : Union[bool, None]
- Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- record_video_dir : Union[pathlib.Path, str, None]
- Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
- sure to call `browser_context.close()` for videos to be saved.
- record_video_size : Union[{width: int, height: int}, None]
- Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
- 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
- will be scaled down if necessary to fit the specified size.
- 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]
- Learn more about [storage state and auth](../auth.md).
- Populates context with given storage state. This option can be used to initialize context with logged-in
- information obtained via `browser_context.storage_state()`.
- base_url : Union[str, None]
- When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
- `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
- using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
- corresponding URL. Unset by default. Examples:
- - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- `http://localhost:3000/foo/bar.html`
- - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- `http://localhost:3000/bar.html`
- strict_selectors : Union[bool, None]
- If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- selectors that imply single target DOM element will throw when more than one element matches the selector. This
- option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
- more about the strict mode.
- service_workers : Union["allow", "block", None]
- Whether to allow sites to register Service workers. Defaults to `'allow'`.
- - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- registered.
- - `'block'`: Playwright will block all registration of Service Workers.
- record_har_url_filter : Union[Pattern[str], str, None]
- record_har_mode : Union["full", "minimal", None]
- When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- record_har_content : Union["attach", "embed", "omit", None]
- Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
- HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
- 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]
- TLS Client Authentication allows the server to request a client certificate and verify it.
- **Details**
- An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
- a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
- `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
- with an exact match to the request origin that the certificate is valid for.
- Client certificate authentication is only active when at least one client certificate is provided. If you want to
- reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
- does not match any of the domains you plan to visit.
- **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- work by replacing `localhost` with `local.playwright`.
- Returns
- -------
- BrowserContext
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.new_context(
- viewport=viewport,
- screen=screen,
- noViewport=no_viewport,
- ignoreHTTPSErrors=ignore_https_errors,
- javaScriptEnabled=java_script_enabled,
- bypassCSP=bypass_csp,
- userAgent=user_agent,
- locale=locale,
- timezoneId=timezone_id,
- geolocation=geolocation,
- permissions=mapping.to_impl(permissions),
- extraHTTPHeaders=mapping.to_impl(extra_http_headers),
- offline=offline,
- httpCredentials=http_credentials,
- deviceScaleFactor=device_scale_factor,
- isMobile=is_mobile,
- hasTouch=has_touch,
- colorScheme=color_scheme,
- reducedMotion=reduced_motion,
- forcedColors=forced_colors,
- contrast=contrast,
- acceptDownloads=accept_downloads,
- defaultBrowserType=default_browser_type,
- proxy=proxy,
- recordHarPath=record_har_path,
- recordHarOmitContent=record_har_omit_content,
- recordVideoDir=record_video_dir,
- recordVideoSize=record_video_size,
- storageState=storage_state,
- baseURL=base_url,
- strictSelectors=strict_selectors,
- serviceWorkers=service_workers,
- recordHarUrlFilter=record_har_url_filter,
- recordHarMode=record_har_mode,
- recordHarContent=record_har_content,
- clientCertificates=client_certificates,
- )
- )
- )
- def new_page(
- self,
- *,
- viewport: typing.Optional[ViewportSize] = None,
- screen: typing.Optional[ViewportSize] = None,
- no_viewport: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- java_script_enabled: typing.Optional[bool] = None,
- bypass_csp: typing.Optional[bool] = None,
- user_agent: typing.Optional[str] = None,
- locale: typing.Optional[str] = None,
- timezone_id: typing.Optional[str] = None,
- geolocation: typing.Optional[Geolocation] = None,
- permissions: typing.Optional[typing.Sequence[str]] = None,
- extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
- offline: typing.Optional[bool] = None,
- http_credentials: typing.Optional[HttpCredentials] = None,
- device_scale_factor: typing.Optional[float] = None,
- is_mobile: typing.Optional[bool] = None,
- has_touch: typing.Optional[bool] = None,
- color_scheme: typing.Optional[
- Literal["dark", "light", "no-preference", "null"]
- ] = None,
- forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
- contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
- reduced_motion: typing.Optional[
- Literal["no-preference", "null", "reduce"]
- ] = None,
- accept_downloads: typing.Optional[bool] = None,
- default_browser_type: typing.Optional[str] = None,
- proxy: typing.Optional[ProxySettings] = None,
- record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- record_har_omit_content: typing.Optional[bool] = None,
- record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- record_video_size: typing.Optional[ViewportSize] = None,
- storage_state: typing.Optional[
- typing.Union[StorageState, str, pathlib.Path]
- ] = None,
- base_url: typing.Optional[str] = None,
- strict_selectors: typing.Optional[bool] = None,
- service_workers: typing.Optional[Literal["allow", "block"]] = None,
- record_har_url_filter: typing.Optional[
- typing.Union[typing.Pattern[str], str]
- ] = None,
- record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
- record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
- client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
- ) -> "Page":
- """Browser.new_page
- Creates a new page in a new browser context. Closing this page will close the context as well.
- This is a convenience API that should only be used for the single-page scenarios and short snippets. Production
- code and testing frameworks should explicitly create `browser.new_context()` followed by the
- `browser_context.new_page()` to control their exact life times.
- Parameters
- ----------
- viewport : Union[{width: int, height: int}, None]
- Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
- viewport. Learn more about [viewport emulation](../emulation.md#viewport).
- screen : Union[{width: int, height: int}, None]
- Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
- `viewport` is set.
- no_viewport : Union[bool, None]
- Does not enforce fixed viewport, allows resizing window in the headed mode.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- java_script_enabled : Union[bool, None]
- Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- [disabling JavaScript](../emulation.md#javascript-enabled).
- bypass_csp : Union[bool, None]
- Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
- user_agent : Union[str, None]
- Specific user agent to use in this context.
- locale : Union[str, None]
- Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
- `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
- locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
- timezone_id : Union[str, None]
- Changes the timezone of the context. See
- [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
- for a list of supported timezone IDs. Defaults to the system timezone.
- geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
- permissions : Union[Sequence[str], None]
- A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
- more details. Defaults to none.
- extra_http_headers : Union[Dict[str, str], None]
- An object containing additional HTTP headers to be sent with every request. Defaults to none.
- offline : Union[bool, None]
- Whether to emulate network being offline. Defaults to `false`. Learn more about
- [network emulation](../emulation.md#offline).
- http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
- Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- origin is specified, the username and password are sent to any servers upon unauthorized responses.
- device_scale_factor : Union[float, None]
- Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- [emulating devices with device scale factor](../emulation.md#devices).
- is_mobile : Union[bool, None]
- Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- about [mobile emulation](../emulation.md#ismobile).
- has_touch : Union[bool, None]
- Specifies if viewport supports touch events. Defaults to false. Learn more about
- [mobile emulation](../emulation.md#devices).
- color_scheme : Union["dark", "light", "no-preference", "null", None]
- Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
- media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
- Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
- forced_colors : Union["active", "none", "null", None]
- Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'none'`.
- contrast : Union["more", "no-preference", "null", None]
- Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'no-preference'`.
- reduced_motion : Union["no-preference", "null", "reduce", None]
- Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'no-preference'`.
- accept_downloads : Union[bool, None]
- Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
- proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
- Network proxy settings to use with this context. Defaults to none.
- record_har_path : Union[pathlib.Path, str, None]
- Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
- on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
- for the HAR to be saved.
- record_har_omit_content : Union[bool, None]
- Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- record_video_dir : Union[pathlib.Path, str, None]
- Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
- sure to call `browser_context.close()` for videos to be saved.
- record_video_size : Union[{width: int, height: int}, None]
- Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
- 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
- will be scaled down if necessary to fit the specified size.
- 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]
- Learn more about [storage state and auth](../auth.md).
- Populates context with given storage state. This option can be used to initialize context with logged-in
- information obtained via `browser_context.storage_state()`.
- base_url : Union[str, None]
- When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
- `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
- using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
- corresponding URL. Unset by default. Examples:
- - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- `http://localhost:3000/foo/bar.html`
- - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- `http://localhost:3000/bar.html`
- strict_selectors : Union[bool, None]
- If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- selectors that imply single target DOM element will throw when more than one element matches the selector. This
- option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
- more about the strict mode.
- service_workers : Union["allow", "block", None]
- Whether to allow sites to register Service workers. Defaults to `'allow'`.
- - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- registered.
- - `'block'`: Playwright will block all registration of Service Workers.
- record_har_url_filter : Union[Pattern[str], str, None]
- record_har_mode : Union["full", "minimal", None]
- When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- record_har_content : Union["attach", "embed", "omit", None]
- Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
- HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
- 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]
- TLS Client Authentication allows the server to request a client certificate and verify it.
- **Details**
- An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
- a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
- `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
- with an exact match to the request origin that the certificate is valid for.
- Client certificate authentication is only active when at least one client certificate is provided. If you want to
- reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
- does not match any of the domains you plan to visit.
- **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- work by replacing `localhost` with `local.playwright`.
- Returns
- -------
- Page
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.new_page(
- viewport=viewport,
- screen=screen,
- noViewport=no_viewport,
- ignoreHTTPSErrors=ignore_https_errors,
- javaScriptEnabled=java_script_enabled,
- bypassCSP=bypass_csp,
- userAgent=user_agent,
- locale=locale,
- timezoneId=timezone_id,
- geolocation=geolocation,
- permissions=mapping.to_impl(permissions),
- extraHTTPHeaders=mapping.to_impl(extra_http_headers),
- offline=offline,
- httpCredentials=http_credentials,
- deviceScaleFactor=device_scale_factor,
- isMobile=is_mobile,
- hasTouch=has_touch,
- colorScheme=color_scheme,
- forcedColors=forced_colors,
- contrast=contrast,
- reducedMotion=reduced_motion,
- acceptDownloads=accept_downloads,
- defaultBrowserType=default_browser_type,
- proxy=proxy,
- recordHarPath=record_har_path,
- recordHarOmitContent=record_har_omit_content,
- recordVideoDir=record_video_dir,
- recordVideoSize=record_video_size,
- storageState=storage_state,
- baseURL=base_url,
- strictSelectors=strict_selectors,
- serviceWorkers=service_workers,
- recordHarUrlFilter=record_har_url_filter,
- recordHarMode=record_har_mode,
- recordHarContent=record_har_content,
- clientCertificates=client_certificates,
- )
- )
- )
- def close(self, *, reason: typing.Optional[str] = None) -> None:
- """Browser.close
- In case this browser is obtained using `browser_type.launch()`, closes the browser and all of its pages (if
- any were opened).
- In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from
- the browser server.
- **NOTE** This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close
- events, call `browser_context.close()` on any `BrowserContext` instances you explicitly created earlier
- using `browser.new_context()` **before** calling `browser.close()`.
- The `Browser` object itself is considered to be disposed and cannot be used anymore.
- Parameters
- ----------
- reason : Union[str, None]
- The reason to be reported to the operations interrupted by the browser closure.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.close(reason=reason)))
- def new_browser_cdp_session(self) -> "CDPSession":
- """Browser.new_browser_cdp_session
- **NOTE** CDP Sessions are only supported on Chromium-based browsers.
- Returns the newly created browser session.
- Returns
- -------
- CDPSession
- """
- return mapping.from_impl(self._sync(self._impl_obj.new_browser_cdp_session()))
- def start_tracing(
- self,
- *,
- page: typing.Optional["Page"] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- screenshots: typing.Optional[bool] = None,
- categories: typing.Optional[typing.Sequence[str]] = None,
- ) -> None:
- """Browser.start_tracing
- **NOTE** This API controls
- [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
- chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
- [here](https://playwright.dev/python/docs/api/class-tracing).
- You can use `browser.start_tracing()` and `browser.stop_tracing()` to create a trace file that can be
- opened in Chrome DevTools performance panel.
- **Usage**
- ```py
- browser.start_tracing(page, path=\"trace.json\")
- page.goto(\"https://www.google.com\")
- browser.stop_tracing()
- ```
- Parameters
- ----------
- page : Union[Page, None]
- Optional, if specified, tracing includes screenshots of the given page.
- path : Union[pathlib.Path, str, None]
- A path to write the trace file to.
- screenshots : Union[bool, None]
- captures screenshots in the trace.
- categories : Union[Sequence[str], None]
- specify custom categories to use instead of default.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.start_tracing(
- page=page._impl_obj if page else None,
- path=path,
- screenshots=screenshots,
- categories=mapping.to_impl(categories),
- )
- )
- )
- def stop_tracing(self) -> bytes:
- """Browser.stop_tracing
- **NOTE** This API controls
- [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level
- chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found
- [here](https://playwright.dev/python/docs/api/class-tracing).
- Returns the buffer with trace data.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.stop_tracing()))
- mapping.register(BrowserImpl, Browser)
- class BrowserType(SyncBase):
- @property
- def name(self) -> str:
- """BrowserType.name
- Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.name)
- @property
- def executable_path(self) -> str:
- """BrowserType.executable_path
- A path where Playwright expects to find a bundled browser executable.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.executable_path)
- def launch(
- self,
- *,
- executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- channel: typing.Optional[str] = None,
- args: typing.Optional[typing.Sequence[str]] = None,
- ignore_default_args: typing.Optional[
- typing.Union[bool, typing.Sequence[str]]
- ] = None,
- handle_sigint: typing.Optional[bool] = None,
- handle_sigterm: typing.Optional[bool] = None,
- handle_sighup: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- headless: typing.Optional[bool] = None,
- proxy: typing.Optional[ProxySettings] = None,
- downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- slow_mo: typing.Optional[float] = None,
- traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- chromium_sandbox: typing.Optional[bool] = None,
- firefox_user_prefs: typing.Optional[
- typing.Dict[str, typing.Union[str, float, bool]]
- ] = None,
- ) -> "Browser":
- """BrowserType.launch
- Returns the browser instance.
- **Usage**
- You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
- ```py
- browser = playwright.chromium.launch( # or \"firefox\" or \"webkit\".
- ignore_default_args=[\"--mute-audio\"]
- )
- ```
- > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it
- works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other
- version. Use `executablePath` option with extreme caution.
- >
- > If Google Chrome (rather than Chromium) is preferred, a
- [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
- [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
- >
- > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs
- for video playback. See
- [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
- other differences between Chromium and Chrome.
- [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
- describes some differences for Linux users.
- Parameters
- ----------
- executable_path : Union[pathlib.Path, str, None]
- Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
- resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
- Firefox or WebKit, use at your own risk.
- channel : Union[str, None]
- Browser distribution channel.
- Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
- Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
- "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
- args : Union[Sequence[str], None]
- **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
- Additional arguments to pass to the browser instance. The list of Chromium flags can be found
- [here](https://peter.sh/experiments/chromium-command-line-switches/).
- ignore_default_args : Union[Sequence[str], bool, None]
- If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
- given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
- handle_sigint : Union[bool, None]
- Close the browser process on Ctrl-C. Defaults to `true`.
- handle_sigterm : Union[bool, None]
- Close the browser process on SIGTERM. Defaults to `true`.
- handle_sighup : Union[bool, None]
- Close the browser process on SIGHUP. Defaults to `true`.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
- to disable timeout.
- env : Union[Dict[str, Union[bool, float, str]], None]
- Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- headless : Union[bool, None]
- Whether to run browser in headless mode. More details for
- [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
- [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
- proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
- Network proxy settings.
- downloads_path : Union[pathlib.Path, str, None]
- If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
- is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
- created in is closed.
- slow_mo : Union[float, None]
- Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- on.
- traces_dir : Union[pathlib.Path, str, None]
- If specified, traces are saved into this directory.
- chromium_sandbox : Union[bool, None]
- Enable Chromium sandboxing. Defaults to `false`.
- firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
- Firefox user preferences. Learn more about the Firefox user preferences at
- [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
- You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
- `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
- Returns
- -------
- Browser
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.launch(
- executablePath=executable_path,
- channel=channel,
- args=mapping.to_impl(args),
- ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
- handleSIGINT=handle_sigint,
- handleSIGTERM=handle_sigterm,
- handleSIGHUP=handle_sighup,
- timeout=timeout,
- env=mapping.to_impl(env),
- headless=headless,
- proxy=proxy,
- downloadsPath=downloads_path,
- slowMo=slow_mo,
- tracesDir=traces_dir,
- chromiumSandbox=chromium_sandbox,
- firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
- )
- )
- )
- def launch_persistent_context(
- self,
- user_data_dir: typing.Union[str, pathlib.Path],
- *,
- channel: typing.Optional[str] = None,
- executable_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- args: typing.Optional[typing.Sequence[str]] = None,
- ignore_default_args: typing.Optional[
- typing.Union[bool, typing.Sequence[str]]
- ] = None,
- handle_sigint: typing.Optional[bool] = None,
- handle_sigterm: typing.Optional[bool] = None,
- handle_sighup: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- headless: typing.Optional[bool] = None,
- proxy: typing.Optional[ProxySettings] = None,
- downloads_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- slow_mo: typing.Optional[float] = None,
- viewport: typing.Optional[ViewportSize] = None,
- screen: typing.Optional[ViewportSize] = None,
- no_viewport: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- java_script_enabled: typing.Optional[bool] = None,
- bypass_csp: typing.Optional[bool] = None,
- user_agent: typing.Optional[str] = None,
- locale: typing.Optional[str] = None,
- timezone_id: typing.Optional[str] = None,
- geolocation: typing.Optional[Geolocation] = None,
- permissions: typing.Optional[typing.Sequence[str]] = None,
- extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
- offline: typing.Optional[bool] = None,
- http_credentials: typing.Optional[HttpCredentials] = None,
- device_scale_factor: typing.Optional[float] = None,
- is_mobile: typing.Optional[bool] = None,
- has_touch: typing.Optional[bool] = None,
- color_scheme: typing.Optional[
- Literal["dark", "light", "no-preference", "null"]
- ] = None,
- reduced_motion: typing.Optional[
- Literal["no-preference", "null", "reduce"]
- ] = None,
- forced_colors: typing.Optional[Literal["active", "none", "null"]] = None,
- contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None,
- accept_downloads: typing.Optional[bool] = None,
- traces_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- chromium_sandbox: typing.Optional[bool] = None,
- firefox_user_prefs: typing.Optional[
- typing.Dict[str, typing.Union[str, float, bool]]
- ] = None,
- record_har_path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- record_har_omit_content: typing.Optional[bool] = None,
- record_video_dir: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- record_video_size: typing.Optional[ViewportSize] = None,
- base_url: typing.Optional[str] = None,
- strict_selectors: typing.Optional[bool] = None,
- service_workers: typing.Optional[Literal["allow", "block"]] = None,
- record_har_url_filter: typing.Optional[
- typing.Union[typing.Pattern[str], str]
- ] = None,
- record_har_mode: typing.Optional[Literal["full", "minimal"]] = None,
- record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None,
- client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
- ) -> "BrowserContext":
- """BrowserType.launch_persistent_context
- Returns the persistent browser context instance.
- Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
- context will automatically close the browser.
- Parameters
- ----------
- user_data_dir : Union[pathlib.Path, str]
- Path to a User Data Directory, which stores browser session data like cookies and local storage. Pass an empty
- string to create a temporary directory.
- More details for
- [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
- [Firefox](https://wiki.mozilla.org/Firefox/CommandLineOptions#User_profile). Chromium's user data directory is the
- **parent** directory of the "Profile Path" seen at `chrome://version`.
- Note that browsers do not allow launching multiple instances with the same User Data Directory.
- **NOTE** Chromium/Chrome: Due to recent Chrome policy changes, automating the default Chrome user profile is not
- supported. Pointing `userDataDir` to Chrome's main "User Data" directory (the profile used for your regular
- browsing) may result in pages not loading or the browser exiting. Create and use a separate directory (for example,
- an empty folder) as your automation profile instead. See https://developer.chrome.com/blog/remote-debugging-port
- for details.
- channel : Union[str, None]
- Browser distribution channel.
- Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode).
- Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or
- "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge).
- executable_path : Union[pathlib.Path, str, None]
- Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
- resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
- Firefox or WebKit, use at your own risk.
- args : Union[Sequence[str], None]
- **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
- Additional arguments to pass to the browser instance. The list of Chromium flags can be found
- [here](https://peter.sh/experiments/chromium-command-line-switches/).
- ignore_default_args : Union[Sequence[str], bool, None]
- If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
- given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
- handle_sigint : Union[bool, None]
- Close the browser process on Ctrl-C. Defaults to `true`.
- handle_sigterm : Union[bool, None]
- Close the browser process on SIGTERM. Defaults to `true`.
- handle_sighup : Union[bool, None]
- Close the browser process on SIGHUP. Defaults to `true`.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
- to disable timeout.
- env : Union[Dict[str, Union[bool, float, str]], None]
- Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- headless : Union[bool, None]
- Whether to run browser in headless mode. More details for
- [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
- [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`.
- proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
- Network proxy settings.
- downloads_path : Union[pathlib.Path, str, None]
- If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
- is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
- created in is closed.
- slow_mo : Union[float, None]
- Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- on.
- viewport : Union[{width: int, height: int}, None]
- Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed
- viewport. Learn more about [viewport emulation](../emulation.md#viewport).
- screen : Union[{width: int, height: int}, None]
- Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
- `viewport` is set.
- no_viewport : Union[bool, None]
- Does not enforce fixed viewport, allows resizing window in the headed mode.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- java_script_enabled : Union[bool, None]
- Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- [disabling JavaScript](../emulation.md#javascript-enabled).
- bypass_csp : Union[bool, None]
- Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
- user_agent : Union[str, None]
- Specific user agent to use in this context.
- locale : Union[str, None]
- Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
- `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
- locale. Learn more about emulation in our [emulation guide](../emulation.md#locale--timezone).
- timezone_id : Union[str, None]
- Changes the timezone of the context. See
- [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
- for a list of supported timezone IDs. Defaults to the system timezone.
- geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]
- permissions : Union[Sequence[str], None]
- A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for
- more details. Defaults to none.
- extra_http_headers : Union[Dict[str, str], None]
- An object containing additional HTTP headers to be sent with every request. Defaults to none.
- offline : Union[bool, None]
- Whether to emulate network being offline. Defaults to `false`. Learn more about
- [network emulation](../emulation.md#offline).
- http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
- Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- origin is specified, the username and password are sent to any servers upon unauthorized responses.
- device_scale_factor : Union[float, None]
- Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- [emulating devices with device scale factor](../emulation.md#devices).
- is_mobile : Union[bool, None]
- Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- about [mobile emulation](../emulation.md#ismobile).
- has_touch : Union[bool, None]
- Specifies if viewport supports touch events. Defaults to false. Learn more about
- [mobile emulation](../emulation.md#devices).
- color_scheme : Union["dark", "light", "no-preference", "null", None]
- Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
- media feature, supported values are `'light'` and `'dark'`. See `page.emulate_media()` for more details.
- Passing `'null'` resets emulation to system defaults. Defaults to `'light'`.
- reduced_motion : Union["no-preference", "null", "reduce", None]
- Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'no-preference'`.
- forced_colors : Union["active", "none", "null", None]
- Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'none'`.
- contrast : Union["more", "no-preference", "null", None]
- Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See
- `page.emulate_media()` for more details. Passing `'null'` resets emulation to system defaults. Defaults to
- `'no-preference'`.
- accept_downloads : Union[bool, None]
- Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
- traces_dir : Union[pathlib.Path, str, None]
- If specified, traces are saved into this directory.
- chromium_sandbox : Union[bool, None]
- Enable Chromium sandboxing. Defaults to `false`.
- firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None]
- Firefox user preferences. Learn more about the Firefox user preferences at
- [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
- You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via
- `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable.
- record_har_path : Union[pathlib.Path, str, None]
- Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file
- on the filesystem. If not specified, the HAR is not recorded. Make sure to call `browser_context.close()`
- for the HAR to be saved.
- record_har_omit_content : Union[bool, None]
- Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- record_video_dir : Union[pathlib.Path, str, None]
- Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make
- sure to call `browser_context.close()` for videos to be saved.
- record_video_size : Union[{width: int, height: int}, None]
- Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into
- 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page
- will be scaled down if necessary to fit the specified size.
- base_url : Union[str, None]
- When using `page.goto()`, `page.route()`, `page.wait_for_url()`,
- `page.expect_request()`, or `page.expect_response()` it takes the base URL in consideration by
- using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the
- corresponding URL. Unset by default. Examples:
- - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- `http://localhost:3000/foo/bar.html`
- - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- `http://localhost:3000/bar.html`
- strict_selectors : Union[bool, None]
- If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- selectors that imply single target DOM element will throw when more than one element matches the selector. This
- option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See `Locator` to learn
- more about the strict mode.
- service_workers : Union["allow", "block", None]
- Whether to allow sites to register Service workers. Defaults to `'allow'`.
- - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- registered.
- - `'block'`: Playwright will block all registration of Service Workers.
- record_har_url_filter : Union[Pattern[str], str, None]
- record_har_mode : Union["full", "minimal", None]
- When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- record_har_content : Union["attach", "embed", "omit", None]
- Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- `attach` is specified, resources are persisted as separate files and all of these files are archived along with the
- HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification.
- 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]
- TLS Client Authentication allows the server to request a client certificate and verify it.
- **Details**
- An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
- a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
- `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
- with an exact match to the request origin that the certificate is valid for.
- Client certificate authentication is only active when at least one client certificate is provided. If you want to
- reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
- does not match any of the domains you plan to visit.
- **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- work by replacing `localhost` with `local.playwright`.
- Returns
- -------
- BrowserContext
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.launch_persistent_context(
- userDataDir=user_data_dir,
- channel=channel,
- executablePath=executable_path,
- args=mapping.to_impl(args),
- ignoreDefaultArgs=mapping.to_impl(ignore_default_args),
- handleSIGINT=handle_sigint,
- handleSIGTERM=handle_sigterm,
- handleSIGHUP=handle_sighup,
- timeout=timeout,
- env=mapping.to_impl(env),
- headless=headless,
- proxy=proxy,
- downloadsPath=downloads_path,
- slowMo=slow_mo,
- viewport=viewport,
- screen=screen,
- noViewport=no_viewport,
- ignoreHTTPSErrors=ignore_https_errors,
- javaScriptEnabled=java_script_enabled,
- bypassCSP=bypass_csp,
- userAgent=user_agent,
- locale=locale,
- timezoneId=timezone_id,
- geolocation=geolocation,
- permissions=mapping.to_impl(permissions),
- extraHTTPHeaders=mapping.to_impl(extra_http_headers),
- offline=offline,
- httpCredentials=http_credentials,
- deviceScaleFactor=device_scale_factor,
- isMobile=is_mobile,
- hasTouch=has_touch,
- colorScheme=color_scheme,
- reducedMotion=reduced_motion,
- forcedColors=forced_colors,
- contrast=contrast,
- acceptDownloads=accept_downloads,
- tracesDir=traces_dir,
- chromiumSandbox=chromium_sandbox,
- firefoxUserPrefs=mapping.to_impl(firefox_user_prefs),
- recordHarPath=record_har_path,
- recordHarOmitContent=record_har_omit_content,
- recordVideoDir=record_video_dir,
- recordVideoSize=record_video_size,
- baseURL=base_url,
- strictSelectors=strict_selectors,
- serviceWorkers=service_workers,
- recordHarUrlFilter=record_har_url_filter,
- recordHarMode=record_har_mode,
- recordHarContent=record_har_content,
- clientCertificates=client_certificates,
- )
- )
- )
- def connect_over_cdp(
- self,
- endpoint_url: str,
- *,
- timeout: typing.Optional[float] = None,
- slow_mo: typing.Optional[float] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- is_local: typing.Optional[bool] = None,
- ) -> "Browser":
- """BrowserType.connect_over_cdp
- This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
- The default browser context is accessible via `browser.contexts()`.
- **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
- **NOTE** This connection is significantly lower fidelity than the Playwright protocol connection via
- `browser_type.connect()`. If you are experiencing issues or attempting to use advanced functionality, you
- probably want to use `browser_type.connect()`.
- **Usage**
- ```py
- browser = playwright.chromium.connect_over_cdp(\"http://localhost:9222\")
- default_context = browser.contexts[0]
- page = default_context.pages[0]
- ```
- Parameters
- ----------
- endpoint_url : str
- A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
- `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
- `0` to disable timeout.
- slow_mo : Union[float, None]
- Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- on. Defaults to 0.
- headers : Union[Dict[str, str], None]
- Additional HTTP headers to be sent with connect request. Optional.
- is_local : Union[bool, None]
- Tells Playwright that it runs on the same host as the CDP server. It will enable certain optimizations that rely
- upon the file system being the same between Playwright and the Browser.
- Returns
- -------
- Browser
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.connect_over_cdp(
- endpointURL=endpoint_url,
- timeout=timeout,
- slowMo=slow_mo,
- headers=mapping.to_impl(headers),
- isLocal=is_local,
- )
- )
- )
- def connect(
- self,
- ws_endpoint: str,
- *,
- timeout: typing.Optional[float] = None,
- slow_mo: typing.Optional[float] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- expose_network: typing.Optional[str] = None,
- ) -> "Browser":
- """BrowserType.connect
- This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js.
- **NOTE** The major and minor version of the Playwright instance that connects needs to match the version of
- Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
- Parameters
- ----------
- ws_endpoint : str
- A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout).
- slow_mo : Union[float, None]
- Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- on. Defaults to 0.
- headers : Union[Dict[str, str], None]
- Additional HTTP headers to be sent with web socket connect request. Optional.
- expose_network : Union[str, None]
- This option exposes network available on the connecting client to the browser being connected to. Consists of a
- list of rules separated by comma.
- Available rules:
- 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
- 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
- 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
- Some common examples:
- 1. `"*"` to expose all network.
- 1. `"<loopback>"` to expose localhost network.
- 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to expose test/staging deployments and
- localhost.
- Returns
- -------
- Browser
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.connect(
- wsEndpoint=ws_endpoint,
- timeout=timeout,
- slowMo=slow_mo,
- headers=mapping.to_impl(headers),
- exposeNetwork=expose_network,
- )
- )
- )
- mapping.register(BrowserTypeImpl, BrowserType)
- class Playwright(SyncBase):
- @property
- def devices(self) -> typing.Dict:
- """Playwright.devices
- Returns a dictionary of devices to be used with `browser.new_context()` or `browser.new_page()`.
- ```py
- from playwright.sync_api import sync_playwright, Playwright
- def run(playwright: Playwright):
- webkit = playwright.webkit
- iphone = playwright.devices[\"iPhone 6\"]
- browser = webkit.launch()
- context = browser.new_context(**iphone)
- page = context.new_page()
- page.goto(\"http://example.com\")
- # other actions...
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
- ```
- Returns
- -------
- Dict
- """
- return mapping.from_maybe_impl(self._impl_obj.devices)
- @property
- def selectors(self) -> "Selectors":
- """Playwright.selectors
- Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/python/docs/extensibility) for more
- information.
- Returns
- -------
- Selectors
- """
- return mapping.from_impl(self._impl_obj.selectors)
- @property
- def chromium(self) -> "BrowserType":
- """Playwright.chromium
- This object can be used to launch or connect to Chromium, returning instances of `Browser`.
- Returns
- -------
- BrowserType
- """
- return mapping.from_impl(self._impl_obj.chromium)
- @property
- def firefox(self) -> "BrowserType":
- """Playwright.firefox
- This object can be used to launch or connect to Firefox, returning instances of `Browser`.
- Returns
- -------
- BrowserType
- """
- return mapping.from_impl(self._impl_obj.firefox)
- @property
- def webkit(self) -> "BrowserType":
- """Playwright.webkit
- This object can be used to launch or connect to WebKit, returning instances of `Browser`.
- Returns
- -------
- BrowserType
- """
- return mapping.from_impl(self._impl_obj.webkit)
- @property
- def request(self) -> "APIRequest":
- """Playwright.request
- Exposes API that can be used for the Web API testing.
- Returns
- -------
- APIRequest
- """
- return mapping.from_impl(self._impl_obj.request)
- def __getitem__(self, value: str) -> "BrowserType":
- return mapping.from_impl(self._impl_obj.__getitem__(value=value))
- def stop(self) -> None:
- """Playwright.stop
- Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful
- in REPL applications.
- ```py
- from playwright.sync_api import sync_playwright
- playwright = sync_playwright().start()
- browser = playwright.chromium.launch()
- page = browser.new_page()
- page.goto(\"https://playwright.dev/\")
- page.screenshot(path=\"example.png\")
- browser.close()
- playwright.stop()
- ```
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.stop()))
- mapping.register(PlaywrightImpl, Playwright)
- class Tracing(SyncBase):
- def start(
- self,
- *,
- name: typing.Optional[str] = None,
- title: typing.Optional[str] = None,
- snapshots: typing.Optional[bool] = None,
- screenshots: typing.Optional[bool] = None,
- sources: typing.Optional[bool] = None,
- ) -> None:
- """Tracing.start
- Start tracing.
- **NOTE** You probably want to
- [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead
- of using `Tracing.start`.
- The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions
- (like `expect` calls). We recommend
- [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),
- which includes those assertions and provides a more complete trace for debugging test failures.
- **Usage**
- ```py
- context.tracing.start(screenshots=True, snapshots=True)
- page = context.new_page()
- page.goto(\"https://playwright.dev\")
- context.tracing.stop(path = \"trace.zip\")
- ```
- Parameters
- ----------
- name : Union[str, None]
- If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
- `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
- need to pass `path` option to `tracing.stop()` instead.
- title : Union[str, None]
- Trace name to be shown in the Trace Viewer.
- snapshots : Union[bool, None]
- If this option is true tracing will
- - capture DOM snapshot on every action
- - record network activity
- screenshots : Union[bool, None]
- Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.
- sources : Union[bool, None]
- Whether to include source files for trace actions.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.start(
- name=name,
- title=title,
- snapshots=snapshots,
- screenshots=screenshots,
- sources=sources,
- )
- )
- )
- def start_chunk(
- self, *, title: typing.Optional[str] = None, name: typing.Optional[str] = None
- ) -> None:
- """Tracing.start_chunk
- Start a new trace chunk. If you'd like to record multiple traces on the same `BrowserContext`, use
- `tracing.start()` once, and then create multiple trace chunks with `tracing.start_chunk()` and
- `tracing.stop_chunk()`.
- **Usage**
- ```py
- context.tracing.start(screenshots=True, snapshots=True)
- page = context.new_page()
- page.goto(\"https://playwright.dev\")
- context.tracing.start_chunk()
- page.get_by_text(\"Get Started\").click()
- # Everything between start_chunk and stop_chunk will be recorded in the trace.
- context.tracing.stop_chunk(path = \"trace1.zip\")
- context.tracing.start_chunk()
- page.goto(\"http://example.com\")
- # Save a second trace file with different actions.
- context.tracing.stop_chunk(path = \"trace2.zip\")
- ```
- Parameters
- ----------
- title : Union[str, None]
- Trace name to be shown in the Trace Viewer.
- name : Union[str, None]
- If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the
- `tracesDir` directory specified in `browser_type.launch()`. To specify the final trace zip file name, you
- need to pass `path` option to `tracing.stop_chunk()` instead.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.start_chunk(title=title, name=name))
- )
- def stop_chunk(
- self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
- ) -> None:
- """Tracing.stop_chunk
- Stop the trace chunk. See `tracing.start_chunk()` for more details about multiple trace chunks.
- Parameters
- ----------
- path : Union[pathlib.Path, str, None]
- Export trace collected since the last `tracing.start_chunk()` call into the file with the given path.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.stop_chunk(path=path)))
- def stop(
- self, *, path: typing.Optional[typing.Union[pathlib.Path, str]] = None
- ) -> None:
- """Tracing.stop
- Stop tracing.
- Parameters
- ----------
- path : Union[pathlib.Path, str, None]
- Export trace into the file with the given path.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.stop(path=path)))
- def group(
- self, name: str, *, location: typing.Optional[TracingGroupLocation] = None
- ) -> None:
- """Tracing.group
- **NOTE** Use `test.step` instead when available.
- Creates a new group within the trace, assigning any subsequent API calls to this group, until
- `tracing.group_end()` is called. Groups can be nested and will be visible in the trace viewer.
- **Usage**
- ```py
- # All actions between group and group_end
- # will be shown in the trace viewer as a group.
- await page.context.tracing.group(\"Open Playwright.dev > API\")
- await page.goto(\"https://playwright.dev/\")
- await page.get_by_role(\"link\", name=\"API\").click()
- await page.context.tracing.group_end()
- ```
- Parameters
- ----------
- name : str
- Group name shown in the trace viewer.
- location : Union[{file: str, line: Union[int, None], column: Union[int, None]}, None]
- Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the
- `tracing.group()` call.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.group(name=name, location=location))
- )
- def group_end(self) -> None:
- """Tracing.group_end
- Closes the last group created by `tracing.group()`.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.group_end()))
- mapping.register(TracingImpl, Tracing)
- class Locator(SyncBase):
- @property
- def page(self) -> "Page":
- """Locator.page
- A page this locator belongs to.
- Returns
- -------
- Page
- """
- return mapping.from_impl(self._impl_obj.page)
- @property
- def first(self) -> "Locator":
- """Locator.first
- Returns locator to the first matching element.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.first)
- @property
- def last(self) -> "Locator":
- """Locator.last
- Returns locator to the last matching element.
- **Usage**
- ```py
- banana = page.get_by_role(\"listitem\").last
- ```
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.last)
- @property
- def content_frame(self) -> "FrameLocator":
- """Locator.content_frame
- Returns a `FrameLocator` object pointing to the same `iframe` as this locator.
- Useful when you have a `Locator` object obtained somewhere, and later on would like to interact with the content
- inside the frame.
- For a reverse operation, use `frame_locator.owner()`.
- **Usage**
- ```py
- locator = page.locator(\"iframe[name=\\\"embedded\\\"]\")
- # ...
- frame_locator = locator.content_frame
- frame_locator.get_by_role(\"button\").click()
- ```
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.content_frame)
- @property
- def description(self) -> typing.Optional[str]:
- """Locator.description
- Returns locator description previously set with `locator.describe()`. Returns `null` if no custom
- description has been set.
- **Usage**
- ```py
- button = page.get_by_role(\"button\").describe(\"Subscribe button\")
- print(button.description()) # \"Subscribe button\"
- input = page.get_by_role(\"textbox\")
- print(input.description()) # None
- ```
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(self._impl_obj.description)
- def bounding_box(
- self, *, timeout: typing.Optional[float] = None
- ) -> typing.Optional[FloatRect]:
- """Locator.bounding_box
- This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
- The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
- window.
- **Details**
- Scrolling affects the returned bounding box, similarly to
- [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
- That means `x` and/or `y` may be negative.
- Elements from child frames return the bounding box relative to the main frame, unlike the
- [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
- Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
- following snippet should click the center of the element.
- **Usage**
- ```py
- box = page.get_by_role(\"button\").bounding_box()
- page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2)
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[{x: float, y: float, width: float, height: float}, None]
- """
- return mapping.from_impl_nullable(
- self._sync(self._impl_obj.bounding_box(timeout=timeout))
- )
- def check(
- self,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Locator.check
- Ensure that checkbox or radio element is checked.
- **Details**
- Performs the following steps:
- 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- checked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked. If not, this method throws.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **Usage**
- ```py
- page.get_by_role(\"checkbox\").check()
- ```
- Parameters
- ----------
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.check(
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def click(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- click_count: typing.Optional[int] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """Locator.click
- Click an element.
- **Details**
- This method clicks the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element, or the specified `position`.
- 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **Usage**
- Click a button:
- ```py
- page.get_by_role(\"button\").click()
- ```
- Shift-right-click at a specific position on a canvas:
- ```py
- page.locator(\"canvas\").click(
- button=\"right\", modifiers=[\"Shift\"], position={\"x\": 23, \"y\": 32}
- )
- ```
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- click_count : Union[int, None]
- defaults to 1. See [UIEvent.detail].
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
- position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.click(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- clickCount=click_count,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- steps=steps,
- )
- )
- )
- def dblclick(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- delay: typing.Optional[float] = None,
- button: typing.Optional[Literal["left", "middle", "right"]] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """Locator.dblclick
- Double-click an element.
- **Details**
- This method double clicks the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to double click in the center of the element, or the specified `position`.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `element.dblclick()` dispatches two `click` events and a single `dblclick` event.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- delay : Union[float, None]
- Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- button : Union["left", "middle", "right", None]
- Defaults to `left`.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor
- position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dblclick(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- delay=delay,
- button=button,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- steps=steps,
- )
- )
- )
- def dispatch_event(
- self,
- type: str,
- event_init: typing.Optional[typing.Dict] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Locator.dispatch_event
- Programmatically dispatch an event on the matching element.
- **Usage**
- ```py
- locator.dispatch_event(\"click\")
- ```
- **Details**
- The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
- `click` is dispatched. This is equivalent to calling
- [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
- Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
- properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
- Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
- - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
- - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
- - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
- - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
- - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
- - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
- - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
- - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
- ```py
- data_transfer = page.evaluate_handle(\"new DataTransfer()\")
- locator.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer})
- ```
- Parameters
- ----------
- type : str
- DOM event type: `"click"`, `"dragstart"`, etc.
- event_init : Union[Dict, None]
- Optional event-specific initialization properties.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.dispatch_event(
- type=type, eventInit=mapping.to_impl(event_init), timeout=timeout
- )
- )
- )
- def evaluate(
- self,
- expression: str,
- arg: typing.Optional[typing.Any] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> typing.Any:
- """Locator.evaluate
- Execute JavaScript code in the page, taking the matching element as an argument.
- **Details**
- Returns the return value of `expression`, called with the matching element as a first argument, and `arg` as a
- second argument.
- If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
- If `expression` throws or rejects, this method throws.
- **Usage**
- Passing argument to `expression`:
- ```py
- result = page.get_by_testid(\"myId\").evaluate(\"(element, [x, y]) => element.textContent + ' ' + x * y\", [7, 8])
- print(result) # prints \"myId text 56\"
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
- evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.evaluate(
- expression=expression, arg=mapping.to_impl(arg), timeout=timeout
- )
- )
- )
- def evaluate_all(
- self, expression: str, arg: typing.Optional[typing.Any] = None
- ) -> typing.Any:
- """Locator.evaluate_all
- Execute JavaScript code in the page, taking all matching elements as an argument.
- **Details**
- Returns the return value of `expression`, called with an array of all matching elements as a first argument, and
- `arg` as a second argument.
- If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
- If `expression` throws or rejects, this method throws.
- **Usage**
- ```py
- locator = page.locator(\"div\")
- more_than_ten = locator.evaluate_all(\"(divs, min) => divs.length > min\", 10)
- ```
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.evaluate_all(
- expression=expression, arg=mapping.to_impl(arg)
- )
- )
- )
- def evaluate_handle(
- self,
- expression: str,
- arg: typing.Optional[typing.Any] = None,
- *,
- timeout: typing.Optional[float] = None,
- ) -> "JSHandle":
- """Locator.evaluate_handle
- Execute JavaScript code in the page, taking the matching element as an argument, and return a `JSHandle` with the
- result.
- **Details**
- Returns the return value of `expression` as a`JSHandle`, called with the matching element as a first argument, and
- `arg` as a second argument.
- The only difference between `locator.evaluate()` and `locator.evaluate_handle()` is that
- `locator.evaluate_handle()` returns `JSHandle`.
- If `expression` returns a [Promise], this method will wait for the promise to resolve and return its value.
- If `expression` throws or rejects, this method throws.
- See `page.evaluate_handle()` for more details.
- Parameters
- ----------
- expression : str
- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
- function is automatically invoked.
- arg : Union[Any, None]
- Optional argument to pass to `expression`.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved,
- evaluation itself is not limited by the timeout. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- Returns
- -------
- JSHandle
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.evaluate_handle(
- expression=expression, arg=mapping.to_impl(arg), timeout=timeout
- )
- )
- )
- def fill(
- self,
- value: str,
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> None:
- """Locator.fill
- Set a value to the input field.
- **Usage**
- ```py
- page.get_by_role(\"textbox\").fill(\"example value\")
- ```
- **Details**
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an
- `input` event after filling. Note that you can pass an empty string to clear the input field.
- If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- error. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
- instead.
- To send fine-grained keyboard events, use `locator.press_sequentially()`.
- Parameters
- ----------
- value : str
- Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.fill(
- value=value, timeout=timeout, noWaitAfter=no_wait_after, force=force
- )
- )
- )
- def clear(
- self,
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> None:
- """Locator.clear
- Clear the input field.
- **Details**
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, clears it and triggers an
- `input` event after clearing.
- If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- error. However, if the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
- instead.
- **Usage**
- ```py
- page.get_by_role(\"textbox\").clear()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.clear(
- timeout=timeout, noWaitAfter=no_wait_after, force=force
- )
- )
- )
- def locator(
- self,
- selector_or_locator: typing.Union[str, "Locator"],
- *,
- has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has: typing.Optional["Locator"] = None,
- has_not: typing.Optional["Locator"] = None,
- ) -> "Locator":
- """Locator.locator
- The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
- options, similar to `locator.filter()` method.
- [Learn more about locators](https://playwright.dev/python/docs/locators).
- Parameters
- ----------
- selector_or_locator : Union[Locator, str]
- A selector or locator to use when resolving DOM element.
- has_text : Union[Pattern[str], str, None]
- Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- `<article><div>Playwright</div></article>`.
- has_not_text : Union[Pattern[str], str, None]
- Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- When passed a [string], matching is case-insensitive and searches for a substring.
- has : Union[Locator, None]
- Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- the document root. For example, you can find `content` that has `div` in
- `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- has_not : Union[Locator, None]
- Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.locator(
- selectorOrLocator=selector_or_locator,
- hasText=has_text,
- hasNotText=has_not_text,
- has=has._impl_obj if has else None,
- hasNot=has_not._impl_obj if has_not else None,
- )
- )
- def get_by_alt_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.get_by_alt_text
- Allows locating elements by their alt text.
- **Usage**
- For example, this method will find the image by alt text \"Playwright logo\":
- ```html
- <img alt='Playwright logo'>
- ```
- ```py
- page.get_by_alt_text(\"Playwright logo\").click()
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_alt_text(text=text, exact=exact))
- def get_by_label(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.get_by_label
- Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
- `aria-label` attribute.
- **Usage**
- For example, this method will find inputs by label \"Username\" and \"Password\" in the following DOM:
- ```html
- <input aria-label=\"Username\">
- <label for=\"password-input\">Password:</label>
- <input id=\"password-input\">
- ```
- ```py
- page.get_by_label(\"Username\").fill(\"john\")
- page.get_by_label(\"Password\").fill(\"secret\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_label(text=text, exact=exact))
- def get_by_placeholder(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.get_by_placeholder
- Allows locating input elements by the placeholder text.
- **Usage**
- For example, consider the following DOM structure.
- ```html
- <input type=\"email\" placeholder=\"name@example.com\" />
- ```
- You can fill the input after locating it by the placeholder text:
- ```py
- page.get_by_placeholder(\"name@example.com\").fill(\"playwright@microsoft.com\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_placeholder(text=text, exact=exact)
- )
- def get_by_role(
- self,
- role: Literal[
- "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",
- ],
- *,
- checked: typing.Optional[bool] = None,
- disabled: typing.Optional[bool] = None,
- expanded: typing.Optional[bool] = None,
- include_hidden: typing.Optional[bool] = None,
- level: typing.Optional[int] = None,
- name: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- pressed: typing.Optional[bool] = None,
- selected: typing.Optional[bool] = None,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.get_by_role
- Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
- [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- **Usage**
- Consider the following DOM structure.
- ```html
- <h3>Sign up</h3>
- <label>
- <input type=\"checkbox\" /> Subscribe
- </label>
- <br/>
- <button>Submit</button>
- ```
- You can locate each element by it's implicit role:
- ```py
- expect(page.get_by_role(\"heading\", name=\"Sign up\")).to_be_visible()
- page.get_by_role(\"checkbox\", name=\"Subscribe\").check()
- page.get_by_role(\"button\", name=re.compile(\"submit\", re.IGNORECASE)).click()
- ```
- **Details**
- Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
- about the ARIA guidelines.
- Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
- that is recognized by the role selector. You can find all the
- [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
- duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
- Parameters
- ----------
- 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"]
- Required aria role.
- checked : Union[bool, None]
- An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
- Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
- disabled : Union[bool, None]
- An attribute that is usually set by `aria-disabled` or `disabled`.
- **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
- [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
- expanded : Union[bool, None]
- An attribute that is usually set by `aria-expanded`.
- Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
- include_hidden : Union[bool, None]
- Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
- [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
- Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
- level : Union[int, None]
- A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
- for `<h1>-<h6>` elements.
- Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
- name : Union[Pattern[str], str, None]
- Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
- case-insensitive and searches for a substring, use `exact` to control this behavior.
- Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- pressed : Union[bool, None]
- An attribute that is usually set by `aria-pressed`.
- Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
- selected : Union[bool, None]
- An attribute that is usually set by `aria-selected`.
- Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
- exact : Union[bool, None]
- Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.get_by_role(
- role=role,
- checked=checked,
- disabled=disabled,
- expanded=expanded,
- includeHidden=include_hidden,
- level=level,
- name=name,
- pressed=pressed,
- selected=selected,
- exact=exact,
- )
- )
- def get_by_test_id(
- self, test_id: typing.Union[str, typing.Pattern[str]]
- ) -> "Locator":
- """Locator.get_by_test_id
- Locate element by the test id.
- **Usage**
- Consider the following DOM structure.
- ```html
- <button data-testid=\"directions\">Itinéraire</button>
- ```
- You can locate the element by it's test id:
- ```py
- page.get_by_test_id(\"directions\").click()
- ```
- **Details**
- By default, the `data-testid` attribute is used as a test id. Use `selectors.set_test_id_attribute()` to
- configure a different test id attribute if necessary.
- Parameters
- ----------
- test_id : Union[Pattern[str], str]
- Id to locate the element by.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_test_id(testId=test_id))
- def get_by_text(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.get_by_text
- Allows locating elements that contain given text.
- See also `locator.filter()` that allows to match by another criteria, like an accessible role, and then
- filter by the text content.
- **Usage**
- Consider the following DOM structure:
- ```html
- <div>Hello <span>world</span></div>
- <div>Hello</div>
- ```
- You can locate by text substring, exact string, or a regular expression:
- ```py
- # Matches <span>
- page.get_by_text(\"world\")
- # Matches first <div>
- page.get_by_text(\"Hello world\")
- # Matches second <div>
- page.get_by_text(\"Hello\", exact=True)
- # Matches both <div>s
- page.get_by_text(re.compile(\"Hello\"))
- # Matches second <div>
- page.get_by_text(re.compile(\"^hello$\", re.IGNORECASE))
- ```
- **Details**
- Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
- one, turns line breaks into spaces and ignores leading and trailing whitespace.
- Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
- example, locating by text `\"Log in\"` matches `<input type=button value=\"Log in\">`.
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_text(text=text, exact=exact))
- def get_by_title(
- self,
- text: typing.Union[str, typing.Pattern[str]],
- *,
- exact: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.get_by_title
- Allows locating elements by their title attribute.
- **Usage**
- Consider the following DOM structure.
- ```html
- <span title='Issues count'>25 issues</span>
- ```
- You can check the issues count after locating it by the title text:
- ```py
- expect(page.get_by_title(\"Issues count\")).to_have_text(\"25 issues\")
- ```
- Parameters
- ----------
- text : Union[Pattern[str], str]
- Text to locate the element for.
- exact : Union[bool, None]
- Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- regular expression. Note that exact match still trims whitespace.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.get_by_title(text=text, exact=exact))
- def frame_locator(self, selector: str) -> "FrameLocator":
- """Locator.frame_locator
- When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
- that iframe:
- **Usage**
- ```py
- locator = page.frame_locator(\"iframe\").get_by_text(\"Submit\")
- locator.click()
- ```
- Parameters
- ----------
- selector : str
- A selector to use when resolving DOM element.
- Returns
- -------
- FrameLocator
- """
- return mapping.from_impl(self._impl_obj.frame_locator(selector=selector))
- def element_handle(
- self, *, timeout: typing.Optional[float] = None
- ) -> "ElementHandle":
- """Locator.element_handle
- Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
- multiple elements match the locator, throws.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- ElementHandle
- """
- return mapping.from_impl(
- self._sync(self._impl_obj.element_handle(timeout=timeout))
- )
- def element_handles(self) -> typing.List["ElementHandle"]:
- """Locator.element_handles
- Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
- Returns
- -------
- List[ElementHandle]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.element_handles()))
- def nth(self, index: int) -> "Locator":
- """Locator.nth
- Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
- **Usage**
- ```py
- banana = page.get_by_role(\"listitem\").nth(2)
- ```
- Parameters
- ----------
- index : int
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.nth(index=index))
- def describe(self, description: str) -> "Locator":
- """Locator.describe
- Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the
- same element.
- **Usage**
- ```py
- button = page.get_by_test_id(\"btn-sub\").describe(\"Subscribe button\")
- button.click()
- ```
- Parameters
- ----------
- description : str
- Locator description.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.describe(description=description))
- def filter(
- self,
- *,
- has_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has_not_text: typing.Optional[typing.Union[typing.Pattern[str], str]] = None,
- has: typing.Optional["Locator"] = None,
- has_not: typing.Optional["Locator"] = None,
- visible: typing.Optional[bool] = None,
- ) -> "Locator":
- """Locator.filter
- This method narrows existing locator according to the options, for example filters by text. It can be chained to
- filter multiple times.
- **Usage**
- ```py
- row_locator = page.locator(\"tr\")
- # ...
- row_locator.filter(has_text=\"text in column 1\").filter(
- has=page.get_by_role(\"button\", name=\"column 2 button\")
- ).screenshot()
- ```
- Parameters
- ----------
- has_text : Union[Pattern[str], str, None]
- Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- `<article><div>Playwright</div></article>`.
- has_not_text : Union[Pattern[str], str, None]
- Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- When passed a [string], matching is case-insensitive and searches for a substring.
- has : Union[Locator, None]
- Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- the document root. For example, you can find `content` that has `div` in
- `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- has_not : Union[Locator, None]
- Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- Note that outer and inner locators must belong to the same frame. Inner locator must not contain `FrameLocator`s.
- visible : Union[bool, None]
- Only matches visible or invisible elements.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(
- self._impl_obj.filter(
- hasText=has_text,
- hasNotText=has_not_text,
- has=has._impl_obj if has else None,
- hasNot=has_not._impl_obj if has_not else None,
- visible=visible,
- )
- )
- def or_(self, locator: "Locator") -> "Locator":
- """Locator.or_
- Creates a locator matching all elements that match one or both of the two locators.
- Note that when both locators match something, the resulting locator will have multiple matches, potentially causing
- a [locator strictness](https://playwright.dev/python/docs/locators#strictness) violation.
- **Usage**
- Consider a scenario where you'd like to click on a \"New email\" button, but sometimes a security settings dialog
- shows up instead. In this case, you can wait for either a \"New email\" button, or a dialog and act accordingly.
- **NOTE** If both \"New email\" button and security dialog appear on screen, the \"or\" locator will match both of them,
- possibly throwing the [\"strict mode violation\" error](https://playwright.dev/python/docs/locators#strictness). In this case, you can use
- `locator.first()` to only match one of them.
- ```py
- new_email = page.get_by_role(\"button\", name=\"New\")
- dialog = page.get_by_text(\"Confirm security settings\")
- expect(new_email.or_(dialog).first).to_be_visible()
- if (dialog.is_visible()):
- page.get_by_role(\"button\", name=\"Dismiss\").click()
- new_email.click()
- ```
- Parameters
- ----------
- locator : Locator
- Alternative locator to match.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.or_(locator=locator._impl_obj))
- def and_(self, locator: "Locator") -> "Locator":
- """Locator.and_
- Creates a locator that matches both this locator and the argument locator.
- **Usage**
- The following example finds a button with a specific title.
- ```py
- button = page.get_by_role(\"button\").and_(page.get_by_title(\"Subscribe\"))
- ```
- Parameters
- ----------
- locator : Locator
- Additional locator to match.
- Returns
- -------
- Locator
- """
- return mapping.from_impl(self._impl_obj.and_(locator=locator._impl_obj))
- def focus(self, *, timeout: typing.Optional[float] = None) -> None:
- """Locator.focus
- Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.focus(timeout=timeout))
- )
- def blur(self, *, timeout: typing.Optional[float] = None) -> None:
- """Locator.blur
- Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur) on the element.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.blur(timeout=timeout)))
- def all(self) -> typing.List["Locator"]:
- """Locator.all
- When the locator points to a list of elements, this returns an array of locators, pointing to their respective
- elements.
- **NOTE** `locator.all()` does not wait for elements to match the locator, and instead immediately returns
- whatever is present in the page.
- When the list of elements changes dynamically, `locator.all()` will produce unpredictable and flaky
- results.
- When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before
- calling `locator.all()`.
- **Usage**
- ```py
- for li in page.get_by_role('listitem').all():
- li.click();
- ```
- Returns
- -------
- List[Locator]
- """
- return mapping.from_impl_list(self._sync(self._impl_obj.all()))
- def count(self) -> int:
- """Locator.count
- Returns the number of elements matching the locator.
- **NOTE** If you need to assert the number of elements on the page, prefer `locator_assertions.to_have_count()`
- to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- count = page.get_by_role(\"listitem\").count()
- ```
- Returns
- -------
- int
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.count()))
- def drag_to(
- self,
- target: "Locator",
- *,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- trial: typing.Optional[bool] = None,
- source_position: typing.Optional[Position] = None,
- target_position: typing.Optional[Position] = None,
- steps: typing.Optional[int] = None,
- ) -> None:
- """Locator.drag_to
- Drag the source element towards the target element and drop it.
- **Details**
- This method drags the locator to another target locator or target position. It will first move to the source
- element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
- **Usage**
- ```py
- source = page.locator(\"#source\")
- target = page.locator(\"#target\")
- source.drag_to(target)
- # or specify exact positions relative to the top-left corners of the elements:
- source.drag_to(
- target,
- source_position={\"x\": 34, \"y\": 7},
- target_position={\"x\": 10, \"y\": 20}
- )
- ```
- Parameters
- ----------
- target : Locator
- Locator of the element to drag to.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- source_position : Union[{x: float, y: float}, None]
- Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
- specified, some visible point of the element is used.
- target_position : Union[{x: float, y: float}, None]
- Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
- specified, some visible point of the element is used.
- steps : Union[int, None]
- Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between the `mousedown` and `mouseup`
- of the drag. When set to 1, emits a single `mousemove` event at the destination location.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.drag_to(
- target=target._impl_obj,
- force=force,
- noWaitAfter=no_wait_after,
- timeout=timeout,
- trial=trial,
- sourcePosition=source_position,
- targetPosition=target_position,
- steps=steps,
- )
- )
- )
- def get_attribute(
- self, name: str, *, timeout: typing.Optional[float] = None
- ) -> typing.Optional[str]:
- """Locator.get_attribute
- Returns the matching element's attribute value.
- **NOTE** If you need to assert an element's attribute, prefer `locator_assertions.to_have_attribute()` to
- avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- Parameters
- ----------
- name : str
- Attribute name to get the value for.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.get_attribute(name=name, timeout=timeout))
- )
- def hover(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Locator.hover
- Hover over the matching element.
- **Usage**
- ```py
- page.get_by_role(\"link\").hover()
- ```
- **Details**
- This method hovers over the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to hover over the center of the element, or the specified `position`.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.hover(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- noWaitAfter=no_wait_after,
- force=force,
- trial=trial,
- )
- )
- )
- def inner_html(self, *, timeout: typing.Optional[float] = None) -> str:
- """Locator.inner_html
- Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.inner_html(timeout=timeout))
- )
- def inner_text(self, *, timeout: typing.Optional[float] = None) -> str:
- """Locator.inner_text
- Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
- **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
- `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.inner_text(timeout=timeout))
- )
- def input_value(self, *, timeout: typing.Optional[float] = None) -> str:
- """Locator.input_value
- Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
- **NOTE** If you need to assert input value, prefer `locator_assertions.to_have_value()` to avoid flakiness.
- See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- value = page.get_by_role(\"textbox\").input_value()
- ```
- **Details**
- Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
- element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
- control.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.input_value(timeout=timeout))
- )
- def is_checked(self, *, timeout: typing.Optional[float] = None) -> bool:
- """Locator.is_checked
- Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
- **NOTE** If you need to assert that checkbox is checked, prefer `locator_assertions.to_be_checked()` to avoid
- flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- checked = page.get_by_role(\"checkbox\").is_checked()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_checked(timeout=timeout))
- )
- def is_disabled(self, *, timeout: typing.Optional[float] = None) -> bool:
- """Locator.is_disabled
- Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/python/docs/actionability#enabled).
- **NOTE** If you need to assert that an element is disabled, prefer `locator_assertions.to_be_disabled()` to
- avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- disabled = page.get_by_role(\"button\").is_disabled()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_disabled(timeout=timeout))
- )
- def is_editable(self, *, timeout: typing.Optional[float] = None) -> bool:
- """Locator.is_editable
- Returns whether the element is [editable](https://playwright.dev/python/docs/actionability#editable). If the target element is not an `<input>`,
- `<textarea>`, `<select>`, `[contenteditable]` and does not have a role allowing `[aria-readonly]`, this method
- throws an error.
- **NOTE** If you need to assert that an element is editable, prefer `locator_assertions.to_be_editable()` to
- avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- editable = page.get_by_role(\"textbox\").is_editable()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_editable(timeout=timeout))
- )
- def is_enabled(self, *, timeout: typing.Optional[float] = None) -> bool:
- """Locator.is_enabled
- Returns whether the element is [enabled](https://playwright.dev/python/docs/actionability#enabled).
- **NOTE** If you need to assert that an element is enabled, prefer `locator_assertions.to_be_enabled()` to
- avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- enabled = page.get_by_role(\"button\").is_enabled()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_enabled(timeout=timeout))
- )
- def is_hidden(self, *, timeout: typing.Optional[float] = None) -> bool:
- """Locator.is_hidden
- Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/python/docs/actionability#visible).
- **NOTE** If you need to assert that element is hidden, prefer `locator_assertions.to_be_hidden()` to avoid
- flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- hidden = page.get_by_role(\"button\").is_hidden()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Deprecated: This option is ignored. `locator.is_hidden()` does not wait for the element to become hidden and returns immediately.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_hidden(timeout=timeout))
- )
- def is_visible(self, *, timeout: typing.Optional[float] = None) -> bool:
- """Locator.is_visible
- Returns whether the element is [visible](https://playwright.dev/python/docs/actionability#visible).
- **NOTE** If you need to assert that element is visible, prefer `locator_assertions.to_be_visible()` to avoid
- flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- visible = page.get_by_role(\"button\").is_visible()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Deprecated: This option is ignored. `locator.is_visible()` does not wait for the element to become visible and returns immediately.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.is_visible(timeout=timeout))
- )
- def press(
- self,
- key: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Locator.press
- Focuses the matching element and presses a combination of the keys.
- **Usage**
- ```py
- page.get_by_role(\"textbox\").press(\"Backspace\")
- ```
- **Details**
- Focuses the element, and then uses `keyboard.down()` and `keyboard.up()`.
- `key` can specify the intended
- [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- to generate the text for. A superset of the `key` values can be found
- [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- etc.
- Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
- Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- texts.
- Shortcuts such as `key: \"Control+o\"`, `key: \"Control++` or `key: \"Control+Shift+T\"` are supported as well. When
- specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- Parameters
- ----------
- key : str
- Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- delay : Union[float, None]
- Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- navigating to inaccessible pages. Defaults to `false`.
- Deprecated: This option will default to `true` in the future.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.press(
- key=key, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
- )
- )
- )
- def screenshot(
- self,
- *,
- timeout: typing.Optional[float] = None,
- type: typing.Optional[Literal["jpeg", "png"]] = None,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- quality: typing.Optional[int] = None,
- omit_background: typing.Optional[bool] = None,
- animations: typing.Optional[Literal["allow", "disabled"]] = None,
- caret: typing.Optional[Literal["hide", "initial"]] = None,
- scale: typing.Optional[Literal["css", "device"]] = None,
- mask: typing.Optional[typing.Sequence["Locator"]] = None,
- mask_color: typing.Optional[str] = None,
- style: typing.Optional[str] = None,
- ) -> bytes:
- """Locator.screenshot
- Take a screenshot of the element matching the locator.
- **Usage**
- ```py
- page.get_by_role(\"link\").screenshot()
- ```
- Disable animations and save screenshot to a file:
- ```py
- page.get_by_role(\"link\").screenshot(animations=\"disabled\", path=\"link.png\")
- ```
- **Details**
- This method captures a screenshot of the page, clipped to the size and position of a particular element matching
- the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
- element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
- This method waits for the [actionability](https://playwright.dev/python/docs/actionability) checks, then scrolls element into view before taking
- a screenshot. If the element is detached from DOM, the method throws an error.
- Returns the buffer with the captured screenshot.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- type : Union["jpeg", "png", None]
- Specify screenshot type, defaults to `png`.
- path : Union[pathlib.Path, str, None]
- The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
- relative path, then it is resolved relative to the current working directory. If no path is provided, the image
- won't be saved to the disk.
- quality : Union[int, None]
- The quality of the image, between 0-100. Not applicable to `png` images.
- omit_background : Union[bool, None]
- Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
- Defaults to `false`.
- animations : Union["allow", "disabled", None]
- When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
- treatment depending on their duration:
- - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
- - infinite animations are canceled to initial state, and then played over after the screenshot.
- Defaults to `"allow"` that leaves animations untouched.
- caret : Union["hide", "initial", None]
- When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
- changed. Defaults to `"hide"`.
- scale : Union["css", "device", None]
- When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
- will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
- screenshots of high-dpi devices will be twice as large or even larger.
- Defaults to `"device"`.
- mask : Union[Sequence[Locator], None]
- Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
- box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box. The mask is also applied to
- invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable
- that.
- mask_color : Union[str, None]
- Specify the color of the overlay box for masked elements, in
- [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
- style : Union[str, None]
- Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
- elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
- the Shadow DOM and applies to the inner frames.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.screenshot(
- timeout=timeout,
- type=type,
- path=path,
- quality=quality,
- omitBackground=omit_background,
- animations=animations,
- caret=caret,
- scale=scale,
- mask=mapping.to_impl(mask),
- maskColor=mask_color,
- style=style,
- )
- )
- )
- def aria_snapshot(self, *, timeout: typing.Optional[float] = None) -> str:
- """Locator.aria_snapshot
- Captures the aria snapshot of the given element. Read more about [aria snapshots](https://playwright.dev/python/docs/aria-snapshots) and
- `locator_assertions.to_match_aria_snapshot()` for the corresponding assertion.
- **Usage**
- ```py
- page.get_by_role(\"link\").aria_snapshot()
- ```
- **Details**
- This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of
- the element and its children. The snapshot can be used to assert the state of the element in the test, or to
- compare it to state in the future.
- The ARIA snapshot is represented using [YAML](https://yaml.org/spec/1.2.2/) markup language:
- - The keys of the objects are the roles and optional accessible names of the elements.
- - The values are either text content or an array of child elements.
- - Generic static text can be represented with the `text` key.
- Below is the HTML markup and the respective ARIA snapshot:
- ```html
- <ul aria-label=\"Links\">
- <li><a href=\"/\">Home</a></li>
- <li><a href=\"/about\">About</a></li>
- <ul>
- ```
- ```yml
- - list \"Links\":
- - listitem:
- - link \"Home\"
- - listitem:
- - link \"About\"
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.aria_snapshot(timeout=timeout))
- )
- def scroll_into_view_if_needed(
- self, *, timeout: typing.Optional[float] = None
- ) -> None:
- """Locator.scroll_into_view_if_needed
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then tries to scroll element into view, unless
- it is completely visible as defined by
- [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
- See [scrolling](https://playwright.dev/python/docs/input#scrolling) for alternative ways to scroll.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.scroll_into_view_if_needed(timeout=timeout))
- )
- def select_option(
- self,
- value: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- *,
- index: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
- label: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
- element: typing.Optional[
- typing.Union["ElementHandle", typing.Sequence["ElementHandle"]]
- ] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- force: typing.Optional[bool] = None,
- ) -> typing.List[str]:
- """Locator.select_option
- Selects option or options in `<select>`.
- **Details**
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, waits until all specified options are present in
- the `<select>` element and selects these options.
- If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
- instead.
- Returns the array of option values that have been successfully selected.
- Triggers a `change` and `input` event once all the provided options have been selected.
- **Usage**
- ```html
- <select multiple>
- <option value=\"red\">Red</option>
- <option value=\"green\">Green</option>
- <option value=\"blue\">Blue</option>
- </select>
- ```
- ```py
- # single selection matching the value or label
- element.select_option(\"blue\")
- # single selection matching the label
- element.select_option(label=\"blue\")
- # multiple selection for blue, red and second option
- element.select_option(value=[\"red\", \"green\", \"blue\"])
- ```
- Parameters
- ----------
- value : Union[Sequence[str], str, None]
- Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- index : Union[Sequence[int], int, None]
- Options to select by index. Optional.
- label : Union[Sequence[str], str, None]
- Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected,
- otherwise only the first option matching one of the passed options is selected. Optional.
- element : Union[ElementHandle, Sequence[ElementHandle], None]
- Option elements to select. Optional.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.select_option(
- value=mapping.to_impl(value),
- index=mapping.to_impl(index),
- label=mapping.to_impl(label),
- element=mapping.to_impl(element),
- timeout=timeout,
- noWaitAfter=no_wait_after,
- force=force,
- )
- )
- )
- def select_text(
- self,
- *,
- force: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """Locator.select_text
- This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, then focuses the element and selects all its
- text content.
- If the element is inside the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
- the control instead.
- Parameters
- ----------
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.select_text(force=force, timeout=timeout))
- )
- def set_input_files(
- self,
- files: typing.Union[
- str,
- pathlib.Path,
- FilePayload,
- typing.Sequence[typing.Union[str, pathlib.Path]],
- typing.Sequence[FilePayload],
- ],
- *,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Locator.set_input_files
- Upload file or multiple files into `<input type=file>`. For inputs with a `[webkitdirectory]` attribute, only a
- single directory path is supported.
- **Usage**
- ```py
- # Select one file
- page.get_by_label(\"Upload file\").set_input_files('myfile.pdf')
- # Select multiple files
- page.get_by_label(\"Upload files\").set_input_files(['file1.txt', 'file2.txt'])
- # Select a directory
- page.get_by_label(\"Upload directory\").set_input_files('mydir')
- # Remove all the selected files
- page.get_by_label(\"Upload file\").set_input_files([])
- # Upload buffer from memory
- page.get_by_label(\"Upload file\").set_input_files(
- files=[
- {\"name\": \"test.txt\", \"mimeType\": \"text/plain\", \"buffer\": b\"this is a test\"}
- ],
- )
- ```
- **Details**
- Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
- they are resolved relative to the current working directory. For empty array, clears the selected files.
- This method expects `Locator` to point to an
- [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
- the `<label>` element that has an associated
- [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
- Parameters
- ----------
- files : Union[Sequence[Union[pathlib.Path, str]], Sequence[{name: str, mimeType: str, buffer: bytes}], pathlib.Path, str, {name: str, mimeType: str, buffer: bytes}]
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_input_files(
- files=mapping.to_impl(files),
- timeout=timeout,
- noWaitAfter=no_wait_after,
- )
- )
- )
- def tap(
- self,
- *,
- modifiers: typing.Optional[
- typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]]
- ] = None,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Locator.tap
- Perform a tap gesture on the element matching the locator. For examples of emulating other gestures by manually
- dispatching touch events, see the [emulating legacy touch events](https://playwright.dev/python/docs/touch-events) page.
- **Details**
- This method taps the element by performing the following steps:
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.touchscreen` to tap the center of the element, or the specified `position`.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- **NOTE** `element.tap()` requires that the `hasTouch` option of the browser context be set to true.
- Parameters
- ----------
- modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None]
- Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- "Control" on Windows and Linux and to "Meta" on macOS.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it. Note that keyboard
- `modifiers` will be pressed regardless of `trial` to allow testing elements which are only visible when those keys
- are pressed.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.tap(
- modifiers=mapping.to_impl(modifiers),
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def text_content(
- self, *, timeout: typing.Optional[float] = None
- ) -> typing.Optional[str]:
- """Locator.text_content
- Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
- **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
- flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- Returns
- -------
- Union[str, None]
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.text_content(timeout=timeout))
- )
- def type(
- self,
- text: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Locator.type
- Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
- text.
- To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
- **Usage**
- Parameters
- ----------
- text : str
- A text to type into a focused element.
- delay : Union[float, None]
- Time to wait between key presses in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.type(
- text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
- )
- )
- )
- def press_sequentially(
- self,
- text: str,
- *,
- delay: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- no_wait_after: typing.Optional[bool] = None,
- ) -> None:
- """Locator.press_sequentially
- **NOTE** In most cases, you should use `locator.fill()` instead. You only need to press keys one by one if
- there is special keyboard handling on the page.
- Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
- text.
- To press a special key, like `Control` or `ArrowDown`, use `locator.press()`.
- **Usage**
- ```py
- locator.press_sequentially(\"hello\") # types instantly
- locator.press_sequentially(\"world\", delay=100) # types slower, like a user
- ```
- An example of typing into a text field and then submitting the form:
- ```py
- locator = page.get_by_label(\"Password\")
- locator.press_sequentially(\"my password\")
- locator.press(\"Enter\")
- ```
- Parameters
- ----------
- text : str
- String of characters to sequentially press into a focused element.
- delay : Union[float, None]
- Time to wait between key presses in milliseconds. Defaults to 0.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.press_sequentially(
- text=text, delay=delay, timeout=timeout, noWaitAfter=no_wait_after
- )
- )
- )
- def uncheck(
- self,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Locator.uncheck
- Ensure that checkbox or radio element is unchecked.
- **Usage**
- ```py
- page.get_by_role(\"checkbox\").uncheck()
- ```
- **Details**
- This method unchecks the element by performing the following steps:
- 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- unchecked, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now unchecked. If not, this method throws.
- If the element is detached from the DOM at any moment during the action, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.uncheck(
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def all_inner_texts(self) -> typing.List[str]:
- """Locator.all_inner_texts
- Returns an array of `node.innerText` values for all matching nodes.
- **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` with
- `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- texts = page.get_by_role(\"link\").all_inner_texts()
- ```
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.all_inner_texts()))
- def all_text_contents(self) -> typing.List[str]:
- """Locator.all_text_contents
- Returns an array of `node.textContent` values for all matching nodes.
- **NOTE** If you need to assert text on the page, prefer `locator_assertions.to_have_text()` to avoid
- flakiness. See [assertions guide](https://playwright.dev/python/docs/test-assertions) for more details.
- **Usage**
- ```py
- texts = page.get_by_role(\"link\").all_text_contents()
- ```
- Returns
- -------
- List[str]
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.all_text_contents()))
- def wait_for(
- self,
- *,
- timeout: typing.Optional[float] = None,
- state: typing.Optional[
- Literal["attached", "detached", "hidden", "visible"]
- ] = None,
- ) -> None:
- """Locator.wait_for
- Returns when element specified by locator satisfies the `state` option.
- If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
- `timeout` milliseconds until the condition is met.
- **Usage**
- ```py
- order_sent = page.locator(\"#order-sent\")
- order_sent.wait_for()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- state : Union["attached", "detached", "hidden", "visible", None]
- Defaults to `'visible'`. Can be either:
- - `'attached'` - wait for element to be present in DOM.
- - `'detached'` - wait for element to not be present in DOM.
- - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
- without any content or with `display:none` has an empty bounding box and is not considered visible.
- - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
- `visibility:hidden`. This is opposite to the `'visible'` option.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.wait_for(timeout=timeout, state=state))
- )
- def set_checked(
- self,
- checked: bool,
- *,
- position: typing.Optional[Position] = None,
- timeout: typing.Optional[float] = None,
- force: typing.Optional[bool] = None,
- no_wait_after: typing.Optional[bool] = None,
- trial: typing.Optional[bool] = None,
- ) -> None:
- """Locator.set_checked
- Set the state of a checkbox or a radio element.
- **Usage**
- ```py
- page.get_by_role(\"checkbox\").set_checked(True)
- ```
- **Details**
- This method checks or unchecks an element by performing the following steps:
- 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- 1. If the element already has the right checked state, this method returns immediately.
- 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the matched element, unless `force` option is set. If
- the element is detached during the checks, the whole action is retried.
- 1. Scroll the element into view if needed.
- 1. Use `page.mouse` to click in the center of the element.
- 1. Ensure that the element is now checked or unchecked. If not, this method throws.
- When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`.
- Passing zero timeout disables this.
- Parameters
- ----------
- checked : bool
- Whether to check or uncheck the checkbox.
- position : Union[{x: float, y: float}, None]
- A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- the element.
- timeout : Union[float, None]
- Maximum time in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can
- be changed by using the `browser_context.set_default_timeout()` or `page.set_default_timeout()` methods.
- force : Union[bool, None]
- Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`.
- no_wait_after : Union[bool, None]
- This option has no effect.
- Deprecated: This option has no effect.
- trial : Union[bool, None]
- When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults
- to `false`. Useful to wait until the element is ready for the action without performing it.
- """
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.set_checked(
- checked=checked,
- position=position,
- timeout=timeout,
- force=force,
- noWaitAfter=no_wait_after,
- trial=trial,
- )
- )
- )
- def highlight(self) -> None:
- """Locator.highlight
- Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
- `locator.highlight()`.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.highlight()))
- mapping.register(LocatorImpl, Locator)
- class APIResponse(SyncBase):
- @property
- def ok(self) -> bool:
- """APIResponse.ok
- Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
- Returns
- -------
- bool
- """
- return mapping.from_maybe_impl(self._impl_obj.ok)
- @property
- def url(self) -> str:
- """APIResponse.url
- Contains the URL of the response.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.url)
- @property
- def status(self) -> int:
- """APIResponse.status
- Contains the status code of the response (e.g., 200 for a success).
- Returns
- -------
- int
- """
- return mapping.from_maybe_impl(self._impl_obj.status)
- @property
- def status_text(self) -> str:
- """APIResponse.status_text
- Contains the status text of the response (e.g. usually an \"OK\" for a success).
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._impl_obj.status_text)
- @property
- def headers(self) -> typing.Dict[str, str]:
- """APIResponse.headers
- An object with all the response HTTP headers associated with this response.
- Returns
- -------
- Dict[str, str]
- """
- return mapping.from_maybe_impl(self._impl_obj.headers)
- @property
- def headers_array(self) -> typing.List[NameValue]:
- """APIResponse.headers_array
- An array with all the response HTTP headers associated with this response. Header names are not lower-cased.
- Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.
- Returns
- -------
- List[{name: str, value: str}]
- """
- return mapping.from_impl_list(self._impl_obj.headers_array)
- def body(self) -> bytes:
- """APIResponse.body
- Returns the buffer with response body.
- Returns
- -------
- bytes
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.body()))
- def text(self) -> str:
- """APIResponse.text
- Returns the text representation of response body.
- Returns
- -------
- str
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.text()))
- def json(self) -> typing.Any:
- """APIResponse.json
- Returns the JSON representation of response body.
- This method will throw if the response body is not parsable via `JSON.parse`.
- Returns
- -------
- Any
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.json()))
- def dispose(self) -> None:
- """APIResponse.dispose
- Disposes the body of this response. If not called then the body will stay in memory until the context closes.
- """
- return mapping.from_maybe_impl(self._sync(self._impl_obj.dispose()))
- mapping.register(APIResponseImpl, APIResponse)
- class APIRequestContext(SyncBase):
- def dispose(self, *, reason: typing.Optional[str] = None) -> None:
- """APIRequestContext.dispose
- All responses returned by `a_pi_request_context.get()` and similar methods are stored in the memory, so that
- you can later call `a_pi_response.body()`.This method discards all its resources, calling any method on
- disposed `APIRequestContext` will throw an exception.
- Parameters
- ----------
- reason : Union[str, None]
- The reason to be reported to the operations interrupted by the context disposal.
- """
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.dispose(reason=reason))
- )
- def delete(
- self,
- url: str,
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.delete
- Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
- response. The method will populate request cookies from the context and update context cookies from the response.
- The method will automatically follow redirects.
- Parameters
- ----------
- url : str
- Target URL.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.delete(
- url=url,
- params=mapping.to_impl(params),
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def head(
- self,
- url: str,
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.head
- Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its
- response. The method will populate request cookies from the context and update context cookies from the response.
- The method will automatically follow redirects.
- Parameters
- ----------
- url : str
- Target URL.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.head(
- url=url,
- params=mapping.to_impl(params),
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def get(
- self,
- url: str,
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.get
- Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its
- response. The method will populate request cookies from the context and update context cookies from the response.
- The method will automatically follow redirects.
- **Usage**
- Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
- ```python
- query_params = {
- \"isbn\": \"1234\",
- \"page\": \"23\"
- }
- api_request_context.get(\"https://example.com/api/getText\", params=query_params)
- ```
- Parameters
- ----------
- url : str
- Target URL.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.get(
- url=url,
- params=mapping.to_impl(params),
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def patch(
- self,
- url: str,
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.patch
- Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its
- response. The method will populate request cookies from the context and update context cookies from the response.
- The method will automatically follow redirects.
- Parameters
- ----------
- url : str
- Target URL.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.patch(
- url=url,
- params=mapping.to_impl(params),
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def put(
- self,
- url: str,
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.put
- Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its
- response. The method will populate request cookies from the context and update context cookies from the response.
- The method will automatically follow redirects.
- Parameters
- ----------
- url : str
- Target URL.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.put(
- url=url,
- params=mapping.to_impl(params),
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def post(
- self,
- url: str,
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.post
- Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its
- response. The method will populate request cookies from the context and update context cookies from the response.
- The method will automatically follow redirects.
- **Usage**
- JSON objects can be passed directly to the request:
- To send form data to the server use `form` option. Its value will be encoded into the request body with
- `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send
- files):
- ```python
- formData = {
- \"title\": \"Book Title\",
- \"body\": \"John Doe\",
- }
- api_request_context.post(\"https://example.com/api/findBook\", form=formData)
- ```
- The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
- encoding. Use `FormData` to construct request body and pass it to the request as `multipart` parameter:
- ```python
- api_request_context.post(
- \"https://example.com/api/uploadScript'\",
- multipart={
- \"fileField\": {
- \"name\": \"f.js\",
- \"mimeType\": \"text/javascript\",
- \"buffer\": b\"console.log(2022);\",
- },
- })
- ```
- Parameters
- ----------
- url : str
- Target URL.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.post(
- url=url,
- params=mapping.to_impl(params),
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def fetch(
- self,
- url_or_request: typing.Union[str, "Request"],
- *,
- params: typing.Optional[
- typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str]
- ] = None,
- method: typing.Optional[str] = None,
- headers: typing.Optional[typing.Dict[str, str]] = None,
- data: typing.Optional[typing.Union[typing.Any, str, bytes]] = None,
- form: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None,
- multipart: typing.Optional[
- typing.Dict[str, typing.Union[bytes, bool, float, str, FilePayload]]
- ] = None,
- timeout: typing.Optional[float] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- max_retries: typing.Optional[int] = None,
- ) -> "APIResponse":
- """APIRequestContext.fetch
- Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
- update context cookies from the response. The method will automatically follow redirects.
- **Usage**
- JSON objects can be passed directly to the request:
- The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
- encoding, by specifiying the `multipart` parameter:
- ```python
- api_request_context.fetch(
- \"https://example.com/api/uploadScript\", method=\"post\",
- multipart={
- \"fileField\": {
- \"name\": \"f.js\",
- \"mimeType\": \"text/javascript\",
- \"buffer\": b\"console.log(2022);\",
- },
- })
- ```
- Parameters
- ----------
- url_or_request : Union[Request, str]
- Target URL or Request to get all parameters from.
- params : Union[Dict[str, Union[bool, float, str]], str, None]
- Query parameters to be sent with the URL.
- method : Union[str, None]
- If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or
- [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.
- headers : Union[Dict[str, str], None]
- Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- it.
- data : Union[Any, bytes, str, None]
- Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- header will be set to `application/octet-stream` if not explicitly set.
- form : Union[Dict[str, Union[bool, float, str]], None]
- Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- as this request body. If this parameter is specified `content-type` header will be set to
- `application/x-www-form-urlencoded` unless explicitly provided.
- multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], None]
- Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.
- timeout : Union[float, None]
- Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- max_retries : Union[int, None]
- Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- Returns
- -------
- APIResponse
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.fetch(
- urlOrRequest=url_or_request,
- params=mapping.to_impl(params),
- method=method,
- headers=mapping.to_impl(headers),
- data=mapping.to_impl(data),
- form=mapping.to_impl(form),
- multipart=mapping.to_impl(multipart),
- timeout=timeout,
- failOnStatusCode=fail_on_status_code,
- ignoreHTTPSErrors=ignore_https_errors,
- maxRedirects=max_redirects,
- maxRetries=max_retries,
- )
- )
- )
- def storage_state(
- self,
- *,
- path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
- indexed_db: typing.Optional[bool] = None,
- ) -> StorageState:
- """APIRequestContext.storage_state
- Returns storage state for this request context, contains current cookies and local storage snapshot if it was
- passed to the constructor.
- Parameters
- ----------
- path : Union[pathlib.Path, str, None]
- The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
- working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
- indexed_db : Union[bool, None]
- Set to `true` to include IndexedDB in the storage state snapshot.
- Returns
- -------
- {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}]}]}
- """
- return mapping.from_impl(
- self._sync(self._impl_obj.storage_state(path=path, indexedDB=indexed_db))
- )
- mapping.register(APIRequestContextImpl, APIRequestContext)
- class APIRequest(SyncBase):
- def new_context(
- self,
- *,
- base_url: typing.Optional[str] = None,
- extra_http_headers: typing.Optional[typing.Dict[str, str]] = None,
- http_credentials: typing.Optional[HttpCredentials] = None,
- ignore_https_errors: typing.Optional[bool] = None,
- proxy: typing.Optional[ProxySettings] = None,
- user_agent: typing.Optional[str] = None,
- timeout: typing.Optional[float] = None,
- storage_state: typing.Optional[
- typing.Union[StorageState, str, pathlib.Path]
- ] = None,
- client_certificates: typing.Optional[typing.List[ClientCertificate]] = None,
- fail_on_status_code: typing.Optional[bool] = None,
- max_redirects: typing.Optional[int] = None,
- ) -> "APIRequestContext":
- """APIRequest.new_context
- Creates new instances of `APIRequestContext`.
- Parameters
- ----------
- base_url : Union[str, None]
- Methods like `a_pi_request_context.get()` take the base URL into consideration by using the
- [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
- Examples:
- - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`
- - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in
- `http://localhost:3000/foo/bar.html`
- - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- `http://localhost:3000/bar.html`
- extra_http_headers : Union[Dict[str, str], None]
- An object containing additional HTTP headers to be sent with every request. Defaults to none.
- http_credentials : Union[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None]
- Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- origin is specified, the username and password are sent to any servers upon unauthorized responses.
- ignore_https_errors : Union[bool, None]
- Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None]
- Network proxy settings.
- user_agent : Union[str, None]
- Specific user agent to use in this context.
- timeout : Union[float, None]
- Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable
- timeout.
- 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]
- Populates context with given storage state. This option can be used to initialize context with logged-in
- information obtained via `browser_context.storage_state()` or `a_pi_request_context.storage_state()`.
- Either a path to the file with saved storage, or the value returned by one of
- `browser_context.storage_state()` or `a_pi_request_context.storage_state()` methods.
- 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]
- TLS Client Authentication allows the server to request a client certificate and verify it.
- **Details**
- An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,
- a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,
- `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided
- with an exact match to the request origin that the certificate is valid for.
- Client certificate authentication is only active when at least one client certificate is provided. If you want to
- reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that
- does not match any of the domains you plan to visit.
- **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- work by replacing `localhost` with `local.playwright`.
- fail_on_status_code : Union[bool, None]
- Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- codes.
- max_redirects : Union[int, None]
- Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request
- individually.
- Returns
- -------
- APIRequestContext
- """
- return mapping.from_impl(
- self._sync(
- self._impl_obj.new_context(
- baseURL=base_url,
- extraHTTPHeaders=mapping.to_impl(extra_http_headers),
- httpCredentials=http_credentials,
- ignoreHTTPSErrors=ignore_https_errors,
- proxy=proxy,
- userAgent=user_agent,
- timeout=timeout,
- storageState=storage_state,
- clientCertificates=client_certificates,
- failOnStatusCode=fail_on_status_code,
- maxRedirects=max_redirects,
- )
- )
- )
- mapping.register(APIRequestImpl, APIRequest)
- class PageAssertions(SyncBase):
- def to_have_title(
- self,
- title_or_reg_exp: typing.Union[typing.Pattern[str], str],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """PageAssertions.to_have_title
- Ensures the page has the given title.
- **Usage**
- ```py
- import re
- from playwright.sync_api import expect
- # ...
- expect(page).to_have_title(re.compile(r\".*checkout\"))
- ```
- Parameters
- ----------
- title_or_reg_exp : Union[Pattern[str], str]
- Expected title or RegExp.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_title(
- titleOrRegExp=title_or_reg_exp, timeout=timeout
- )
- )
- )
- def not_to_have_title(
- self,
- title_or_reg_exp: typing.Union[typing.Pattern[str], str],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """PageAssertions.not_to_have_title
- The opposite of `page_assertions.to_have_title()`.
- Parameters
- ----------
- title_or_reg_exp : Union[Pattern[str], str]
- Expected title or RegExp.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_title(
- titleOrRegExp=title_or_reg_exp, timeout=timeout
- )
- )
- )
- def to_have_url(
- self,
- url_or_reg_exp: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ignore_case: typing.Optional[bool] = None,
- ) -> None:
- """PageAssertions.to_have_url
- Ensures the page is navigated to the given URL.
- **Usage**
- ```py
- import re
- from playwright.sync_api import expect
- # ...
- expect(page).to_have_url(re.compile(\".*checkout\"))
- ```
- Parameters
- ----------
- url_or_reg_exp : Union[Pattern[str], str]
- Expected URL string or RegExp.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression parameter if specified. A provided predicate ignores this flag.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_url(
- urlOrRegExp=url_or_reg_exp, timeout=timeout, ignoreCase=ignore_case
- )
- )
- )
- def not_to_have_url(
- self,
- url_or_reg_exp: typing.Union[typing.Pattern[str], str],
- *,
- timeout: typing.Optional[float] = None,
- ignore_case: typing.Optional[bool] = None,
- ) -> None:
- """PageAssertions.not_to_have_url
- The opposite of `page_assertions.to_have_url()`.
- Parameters
- ----------
- url_or_reg_exp : Union[Pattern[str], str]
- Expected URL string or RegExp.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_url(
- urlOrRegExp=url_or_reg_exp, timeout=timeout, ignoreCase=ignore_case
- )
- )
- )
- mapping.register(PageAssertionsImpl, PageAssertions)
- class LocatorAssertions(SyncBase):
- def to_contain_text(
- self,
- expected: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- typing.Pattern[str],
- str,
- ],
- *,
- use_inner_text: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ignore_case: typing.Optional[bool] = None,
- ) -> None:
- """LocatorAssertions.to_contain_text
- Ensures the `Locator` points to an element that contains the given text. All nested elements will be considered
- when computing the text content of the element. You can use regular expressions for the value as well.
- **Details**
- When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
- text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
- **Usage**
- ```py
- import re
- from playwright.sync_api import expect
- locator = page.locator('.title')
- expect(locator).to_contain_text(\"substring\")
- expect(locator).to_contain_text(re.compile(r\"\\d messages\"))
- ```
- If you pass an array as an expected value, the expectations are:
- 1. Locator resolves to a list of elements.
- 1. Elements from a **subset** of this list contain text from the expected array, respectively.
- 1. The matching subset of elements has the same order as the expected array.
- 1. Each text value from the expected array is matched by some element from the list.
- For example, consider the following list:
- ```html
- <ul>
- <li>Item Text 1</li>
- <li>Item Text 2</li>
- <li>Item Text 3</li>
- </ul>
- ```
- Let's see how we can use the assertion:
- ```py
- from playwright.sync_api import expect
- # ✓ Contains the right items in the right order
- expect(page.locator(\"ul > li\")).to_contain_text([\"Text 1\", \"Text 3\"])
- # ✖ Wrong order
- expect(page.locator(\"ul > li\")).to_contain_text([\"Text 3\", \"Text 2\"])
- # ✖ No item contains this text
- expect(page.locator(\"ul > li\")).to_contain_text([\"Some 33\"])
- # ✖ Locator points to the outer list element, not to the list items
- expect(page.locator(\"ul\")).to_contain_text([\"Text 3\"])
- ```
- Parameters
- ----------
- expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
- Expected substring or RegExp or a list of those.
- use_inner_text : Union[bool, None]
- Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_contain_text(
- expected=mapping.to_impl(expected),
- useInnerText=use_inner_text,
- timeout=timeout,
- ignoreCase=ignore_case,
- )
- )
- )
- def not_to_contain_text(
- self,
- expected: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- typing.Pattern[str],
- str,
- ],
- *,
- use_inner_text: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ignore_case: typing.Optional[bool] = None,
- ) -> None:
- """LocatorAssertions.not_to_contain_text
- The opposite of `locator_assertions.to_contain_text()`.
- Parameters
- ----------
- expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
- Expected substring or RegExp or a list of those.
- use_inner_text : Union[bool, None]
- Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_contain_text(
- expected=mapping.to_impl(expected),
- useInnerText=use_inner_text,
- timeout=timeout,
- ignoreCase=ignore_case,
- )
- )
- )
- def to_have_attribute(
- self,
- name: str,
- value: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_attribute
- Ensures the `Locator` points to an element with given attribute.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"input\")
- expect(locator).to_have_attribute(\"type\", \"text\")
- ```
- Parameters
- ----------
- name : str
- Attribute name.
- value : Union[Pattern[str], str]
- Expected attribute value.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_attribute(
- name=name, value=value, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def not_to_have_attribute(
- self,
- name: str,
- value: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_attribute
- The opposite of `locator_assertions.to_have_attribute()`.
- Parameters
- ----------
- name : str
- Attribute name.
- value : Union[Pattern[str], str]
- Expected attribute value.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_attribute(
- name=name, value=value, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def to_have_class(
- self,
- expected: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- typing.Pattern[str],
- str,
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_class
- Ensures the `Locator` points to an element with given CSS classes. When a string is provided, it must fully match
- the element's `class` attribute. To match individual classes use `locator_assertions.to_contain_class()`.
- **Usage**
- ```html
- <div class='middle selected row' id='component'></div>
- ```
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"#component\")
- expect(locator).to_have_class(\"middle selected row\")
- expect(locator).to_have_class(re.compile(r\"(^|\\\\s)selected(\\\\s|$)\"))
- ```
- When an array is passed, the method asserts that the list of elements located matches the corresponding list of
- expected class values. Each element's class attribute is matched against the corresponding string or regular
- expression in the array:
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\".list > .component\")
- expect(locator).to_have_class([\"component\", \"component selected\", \"component\"])
- ```
- Parameters
- ----------
- expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
- Expected class or RegExp or a list of those.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_class(
- expected=mapping.to_impl(expected), timeout=timeout
- )
- )
- )
- def not_to_have_class(
- self,
- expected: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- typing.Pattern[str],
- str,
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_class
- The opposite of `locator_assertions.to_have_class()`.
- Parameters
- ----------
- expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
- Expected class or RegExp or a list of those.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_class(
- expected=mapping.to_impl(expected), timeout=timeout
- )
- )
- )
- def to_contain_class(
- self,
- expected: typing.Union[typing.Sequence[str], str],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_contain_class
- Ensures the `Locator` points to an element with given CSS classes. All classes from the asserted value, separated
- by spaces, must be present in the
- [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) in any order.
- **Usage**
- ```html
- <div class='middle selected row' id='component'></div>
- ```
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"#component\")
- expect(locator).to_contain_class(\"middle selected row\")
- expect(locator).to_contain_class(\"selected\")
- expect(locator).to_contain_class(\"row middle\")
- ```
- When an array is passed, the method asserts that the list of elements located matches the corresponding list of
- expected class lists. Each element's class attribute is matched against the corresponding class in the array:
- ```html
- <div class='list'>
- <div class='component inactive'></div>
- <div class='component active'></div>
- <div class='component inactive'></div>
- </div>
- ```
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\".list > .component\")
- await expect(locator).to_contain_class([\"inactive\", \"active\", \"inactive\"])
- ```
- Parameters
- ----------
- expected : Union[Sequence[str], str]
- A string containing expected class names, separated by spaces, or a list of such strings to assert multiple
- elements.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_contain_class(
- expected=mapping.to_impl(expected), timeout=timeout
- )
- )
- )
- def not_to_contain_class(
- self,
- expected: typing.Union[typing.Sequence[str], str],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_contain_class
- The opposite of `locator_assertions.to_contain_class()`.
- Parameters
- ----------
- expected : Union[Sequence[str], str]
- Expected class or RegExp or a list of those.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_contain_class(
- expected=mapping.to_impl(expected), timeout=timeout
- )
- )
- )
- def to_have_count(
- self, count: int, *, timeout: typing.Optional[float] = None
- ) -> None:
- """LocatorAssertions.to_have_count
- Ensures the `Locator` resolves to an exact number of DOM nodes.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"list > .component\")
- expect(locator).to_have_count(3)
- ```
- Parameters
- ----------
- count : int
- Expected count.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_have_count(count=count, timeout=timeout))
- )
- def not_to_have_count(
- self, count: int, *, timeout: typing.Optional[float] = None
- ) -> None:
- """LocatorAssertions.not_to_have_count
- The opposite of `locator_assertions.to_have_count()`.
- Parameters
- ----------
- count : int
- Expected count.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_have_count(count=count, timeout=timeout))
- )
- def to_have_css(
- self,
- name: str,
- value: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_css
- Ensures the `Locator` resolves to an element with the given computed CSS style.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.get_by_role(\"button\")
- expect(locator).to_have_css(\"display\", \"flex\")
- ```
- Parameters
- ----------
- name : str
- CSS property name.
- value : Union[Pattern[str], str]
- CSS property value.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_css(name=name, value=value, timeout=timeout)
- )
- )
- def not_to_have_css(
- self,
- name: str,
- value: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_css
- The opposite of `locator_assertions.to_have_css()`.
- Parameters
- ----------
- name : str
- CSS property name.
- value : Union[Pattern[str], str]
- CSS property value.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_css(name=name, value=value, timeout=timeout)
- )
- )
- def to_have_id(
- self,
- id: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_id
- Ensures the `Locator` points to an element with the given DOM Node ID.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.get_by_role(\"textbox\")
- expect(locator).to_have_id(\"lastname\")
- ```
- Parameters
- ----------
- id : Union[Pattern[str], str]
- Element id.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_have_id(id=id, timeout=timeout))
- )
- def not_to_have_id(
- self,
- id: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_id
- The opposite of `locator_assertions.to_have_id()`.
- Parameters
- ----------
- id : Union[Pattern[str], str]
- Element id.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_have_id(id=id, timeout=timeout))
- )
- def to_have_js_property(
- self, name: str, value: typing.Any, *, timeout: typing.Optional[float] = None
- ) -> None:
- """LocatorAssertions.to_have_js_property
- Ensures the `Locator` points to an element with given JavaScript property. Note that this property can be of a
- primitive type as well as a plain serializable JavaScript object.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\".component\")
- expect(locator).to_have_js_property(\"loaded\", True)
- ```
- Parameters
- ----------
- name : str
- Property name.
- value : Any
- Property value.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_js_property(
- name=name, value=mapping.to_impl(value), timeout=timeout
- )
- )
- )
- def not_to_have_js_property(
- self, name: str, value: typing.Any, *, timeout: typing.Optional[float] = None
- ) -> None:
- """LocatorAssertions.not_to_have_js_property
- The opposite of `locator_assertions.to_have_js_property()`.
- Parameters
- ----------
- name : str
- Property name.
- value : Any
- Property value.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_js_property(
- name=name, value=mapping.to_impl(value), timeout=timeout
- )
- )
- )
- def to_have_value(
- self,
- value: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_value
- Ensures the `Locator` points to an element with the given input value. You can use regular expressions for the
- value as well.
- **Usage**
- ```py
- import re
- from playwright.sync_api import expect
- locator = page.locator(\"input[type=number]\")
- expect(locator).to_have_value(re.compile(r\"[0-9]\"))
- ```
- Parameters
- ----------
- value : Union[Pattern[str], str]
- Expected value.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_have_value(value=value, timeout=timeout))
- )
- def not_to_have_value(
- self,
- value: typing.Union[str, typing.Pattern[str]],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_value
- The opposite of `locator_assertions.to_have_value()`.
- Parameters
- ----------
- value : Union[Pattern[str], str]
- Expected value.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_have_value(value=value, timeout=timeout))
- )
- def to_have_values(
- self,
- values: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_values
- Ensures the `Locator` points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the
- specified values are selected.
- **Usage**
- For example, given the following element:
- ```html
- <select id=\"favorite-colors\" multiple>
- <option value=\"R\">Red</option>
- <option value=\"G\">Green</option>
- <option value=\"B\">Blue</option>
- </select>
- ```
- ```py
- import re
- from playwright.sync_api import expect
- locator = page.locator(\"id=favorite-colors\")
- locator.select_option([\"R\", \"G\"])
- expect(locator).to_have_values([re.compile(r\"R\"), re.compile(r\"G\")])
- ```
- Parameters
- ----------
- values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
- Expected options currently selected.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_values(
- values=mapping.to_impl(values), timeout=timeout
- )
- )
- )
- def not_to_have_values(
- self,
- values: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_values
- The opposite of `locator_assertions.to_have_values()`.
- Parameters
- ----------
- values : Union[Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str]]
- Expected options currently selected.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_values(
- values=mapping.to_impl(values), timeout=timeout
- )
- )
- )
- def to_have_text(
- self,
- expected: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- typing.Pattern[str],
- str,
- ],
- *,
- use_inner_text: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ignore_case: typing.Optional[bool] = None,
- ) -> None:
- """LocatorAssertions.to_have_text
- Ensures the `Locator` points to an element with the given text. All nested elements will be considered when
- computing the text content of the element. You can use regular expressions for the value as well.
- **Details**
- When `expected` parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual
- text and in the expected string before matching. When regular expression is used, the actual text is matched as is.
- **Usage**
- ```py
- import re
- from playwright.sync_api import expect
- locator = page.locator(\".title\")
- expect(locator).to_have_text(re.compile(r\"Welcome, Test User\"))
- expect(locator).to_have_text(re.compile(r\"Welcome, .*\"))
- ```
- If you pass an array as an expected value, the expectations are:
- 1. Locator resolves to a list of elements.
- 1. The number of elements equals the number of expected values in the array.
- 1. Elements from the list have text matching expected array values, one by one, in order.
- For example, consider the following list:
- ```html
- <ul>
- <li>Text 1</li>
- <li>Text 2</li>
- <li>Text 3</li>
- </ul>
- ```
- Let's see how we can use the assertion:
- ```py
- from playwright.sync_api import expect
- # ✓ Has the right items in the right order
- expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
- # ✖ Wrong order
- expect(page.locator(\"ul > li\")).to_have_text([\"Text 3\", \"Text 2\", \"Text 1\"])
- # ✖ Last item does not match
- expect(page.locator(\"ul > li\")).to_have_text([\"Text 1\", \"Text 2\", \"Text\"])
- # ✖ Locator points to the outer list element, not to the list items
- expect(page.locator(\"ul\")).to_have_text([\"Text 1\", \"Text 2\", \"Text 3\"])
- ```
- Parameters
- ----------
- expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
- Expected string or RegExp or a list of those.
- use_inner_text : Union[bool, None]
- Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_text(
- expected=mapping.to_impl(expected),
- useInnerText=use_inner_text,
- timeout=timeout,
- ignoreCase=ignore_case,
- )
- )
- )
- def not_to_have_text(
- self,
- expected: typing.Union[
- typing.Sequence[str],
- typing.Sequence[typing.Pattern[str]],
- typing.Sequence[typing.Union[typing.Pattern[str], str]],
- typing.Pattern[str],
- str,
- ],
- *,
- use_inner_text: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ignore_case: typing.Optional[bool] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_text
- The opposite of `locator_assertions.to_have_text()`.
- Parameters
- ----------
- expected : Union[Pattern[str], Sequence[Pattern[str]], Sequence[Union[Pattern[str], str]], Sequence[str], str]
- Expected string or RegExp or a list of those.
- use_inner_text : Union[bool, None]
- Whether to use `element.innerText` instead of `element.textContent` when retrieving DOM node text.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_text(
- expected=mapping.to_impl(expected),
- useInnerText=use_inner_text,
- timeout=timeout,
- ignoreCase=ignore_case,
- )
- )
- )
- def to_be_attached(
- self,
- *,
- attached: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_be_attached
- Ensures that `Locator` points to an element that is
- [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
- **Usage**
- ```py
- expect(page.get_by_text(\"Hidden text\")).to_be_attached()
- ```
- Parameters
- ----------
- attached : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_be_attached(attached=attached, timeout=timeout)
- )
- )
- def to_be_checked(
- self,
- *,
- timeout: typing.Optional[float] = None,
- checked: typing.Optional[bool] = None,
- indeterminate: typing.Optional[bool] = None,
- ) -> None:
- """LocatorAssertions.to_be_checked
- Ensures the `Locator` points to a checked input.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.get_by_label(\"Subscribe to newsletter\")
- expect(locator).to_be_checked()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- checked : Union[bool, None]
- Provides state to assert for. Asserts for input to be checked by default. This option can't be used when
- `indeterminate` is set to true.
- indeterminate : Union[bool, None]
- Asserts that the element is in the indeterminate (mixed) state. Only supported for checkboxes and radio buttons.
- This option can't be true when `checked` is provided.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_be_checked(
- timeout=timeout, checked=checked, indeterminate=indeterminate
- )
- )
- )
- def not_to_be_attached(
- self,
- *,
- attached: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_be_attached
- The opposite of `locator_assertions.to_be_attached()`.
- Parameters
- ----------
- attached : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_be_attached(attached=attached, timeout=timeout)
- )
- )
- def not_to_be_checked(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.not_to_be_checked
- The opposite of `locator_assertions.to_be_checked()`.
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_be_checked(timeout=timeout))
- )
- def to_be_disabled(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.to_be_disabled
- Ensures the `Locator` points to a disabled element. Element is disabled if it has \"disabled\" attribute or is
- disabled via
- ['aria-disabled'](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled). Note
- that only native control elements such as HTML `button`, `input`, `select`, `textarea`, `option`, `optgroup` can be
- disabled by setting \"disabled\" attribute. \"disabled\" attribute on other elements is ignored by the browser.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"button.submit\")
- expect(locator).to_be_disabled()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_disabled(timeout=timeout))
- )
- def not_to_be_disabled(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.not_to_be_disabled
- The opposite of `locator_assertions.to_be_disabled()`.
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_be_disabled(timeout=timeout))
- )
- def to_be_editable(
- self,
- *,
- editable: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_be_editable
- Ensures the `Locator` points to an editable element.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.get_by_role(\"textbox\")
- expect(locator).to_be_editable()
- ```
- Parameters
- ----------
- editable : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_be_editable(editable=editable, timeout=timeout)
- )
- )
- def not_to_be_editable(
- self,
- *,
- editable: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_be_editable
- The opposite of `locator_assertions.to_be_editable()`.
- Parameters
- ----------
- editable : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_be_editable(editable=editable, timeout=timeout)
- )
- )
- def to_be_empty(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.to_be_empty
- Ensures the `Locator` points to an empty editable element or to a DOM node that has no text.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"div.warning\")
- expect(locator).to_be_empty()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_empty(timeout=timeout))
- )
- def not_to_be_empty(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.not_to_be_empty
- The opposite of `locator_assertions.to_be_empty()`.
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_be_empty(timeout=timeout))
- )
- def to_be_enabled(
- self,
- *,
- enabled: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_be_enabled
- Ensures the `Locator` points to an enabled element.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator(\"button.submit\")
- expect(locator).to_be_enabled()
- ```
- Parameters
- ----------
- enabled : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_enabled(enabled=enabled, timeout=timeout))
- )
- def not_to_be_enabled(
- self,
- *,
- enabled: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_be_enabled
- The opposite of `locator_assertions.to_be_enabled()`.
- Parameters
- ----------
- enabled : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_be_enabled(enabled=enabled, timeout=timeout)
- )
- )
- def to_be_hidden(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.to_be_hidden
- Ensures that `Locator` either does not resolve to any DOM node, or resolves to a
- [non-visible](https://playwright.dev/python/docs/actionability#visible) one.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.locator('.my-element')
- expect(locator).to_be_hidden()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_hidden(timeout=timeout))
- )
- def not_to_be_hidden(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.not_to_be_hidden
- The opposite of `locator_assertions.to_be_hidden()`.
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_be_hidden(timeout=timeout))
- )
- def to_be_visible(
- self,
- *,
- visible: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_be_visible
- Ensures that `Locator` points to an attached and [visible](https://playwright.dev/python/docs/actionability#visible) DOM node.
- To check that at least one element from the list is visible, use `locator.first()`.
- **Usage**
- ```py
- # A specific element is visible.
- expect(page.get_by_text(\"Welcome\")).to_be_visible()
- # At least one item in the list is visible.
- expect(page.get_by_test_id(\"todo-item\").first).to_be_visible()
- # At least one of the two elements is visible, possibly both.
- expect(
- page.get_by_role(\"button\", name=\"Sign in\")
- .or_(page.get_by_role(\"button\", name=\"Sign up\"))
- .first
- ).to_be_visible()
- ```
- Parameters
- ----------
- visible : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_visible(visible=visible, timeout=timeout))
- )
- def not_to_be_visible(
- self,
- *,
- visible: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_be_visible
- The opposite of `locator_assertions.to_be_visible()`.
- Parameters
- ----------
- visible : Union[bool, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_be_visible(visible=visible, timeout=timeout)
- )
- )
- def to_be_focused(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.to_be_focused
- Ensures the `Locator` points to a focused DOM node.
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.get_by_role(\"textbox\")
- expect(locator).to_be_focused()
- ```
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_focused(timeout=timeout))
- )
- def not_to_be_focused(self, *, timeout: typing.Optional[float] = None) -> None:
- """LocatorAssertions.not_to_be_focused
- The opposite of `locator_assertions.to_be_focused()`.
- Parameters
- ----------
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_be_focused(timeout=timeout))
- )
- def to_be_in_viewport(
- self,
- *,
- ratio: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_be_in_viewport
- Ensures the `Locator` points to an element that intersects viewport, according to the
- [intersection observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
- **Usage**
- ```py
- from playwright.sync_api import expect
- locator = page.get_by_role(\"button\")
- # Make sure at least some part of element intersects viewport.
- expect(locator).to_be_in_viewport()
- # Make sure element is fully outside of viewport.
- expect(locator).not_to_be_in_viewport()
- # Make sure that at least half of the element intersects viewport.
- expect(locator).to_be_in_viewport(ratio=0.5)
- ```
- Parameters
- ----------
- ratio : Union[float, None]
- The minimal ratio of the element to intersect viewport. If equals to `0`, then element should intersect viewport at
- any positive ratio. Defaults to `0`.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_be_in_viewport(ratio=ratio, timeout=timeout))
- )
- def not_to_be_in_viewport(
- self,
- *,
- ratio: typing.Optional[float] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_be_in_viewport
- The opposite of `locator_assertions.to_be_in_viewport()`.
- Parameters
- ----------
- ratio : Union[float, None]
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_be_in_viewport(ratio=ratio, timeout=timeout)
- )
- )
- def to_have_accessible_description(
- self,
- description: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_accessible_description
- Ensures the `Locator` points to an element with a given
- [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
- **Usage**
- ```py
- locator = page.get_by_test_id(\"save-button\")
- expect(locator).to_have_accessible_description(\"Save results to disk\")
- ```
- Parameters
- ----------
- description : Union[Pattern[str], str]
- Expected accessible description.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_accessible_description(
- description=description, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def not_to_have_accessible_description(
- self,
- name: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_accessible_description
- The opposite of `locator_assertions.to_have_accessible_description()`.
- Parameters
- ----------
- name : Union[Pattern[str], str]
- Expected accessible description.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_accessible_description(
- name=name, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def to_have_accessible_name(
- self,
- name: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_accessible_name
- Ensures the `Locator` points to an element with a given
- [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- **Usage**
- ```py
- locator = page.get_by_test_id(\"save-button\")
- expect(locator).to_have_accessible_name(\"Save to disk\")
- ```
- Parameters
- ----------
- name : Union[Pattern[str], str]
- Expected accessible name.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_accessible_name(
- name=name, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def not_to_have_accessible_name(
- self,
- name: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_accessible_name
- The opposite of `locator_assertions.to_have_accessible_name()`.
- Parameters
- ----------
- name : Union[Pattern[str], str]
- Expected accessible name.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_accessible_name(
- name=name, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def to_have_role(
- self,
- role: Literal[
- "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",
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_role
- Ensures the `Locator` points to an element with a given [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles).
- Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass
- role `\"checkbox\"` on an element with a subclass role `\"switch\"` will fail.
- **Usage**
- ```py
- locator = page.get_by_test_id(\"save-button\")
- expect(locator).to_have_role(\"button\")
- ```
- Parameters
- ----------
- 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"]
- Required aria role.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.to_have_role(role=role, timeout=timeout))
- )
- def to_have_accessible_error_message(
- self,
- error_message: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.to_have_accessible_error_message
- Ensures the `Locator` points to an element with a given
- [aria errormessage](https://w3c.github.io/aria/#aria-errormessage).
- **Usage**
- ```py
- locator = page.get_by_test_id(\"username-input\")
- expect(locator).to_have_accessible_error_message(\"Username is required.\")
- ```
- Parameters
- ----------
- error_message : Union[Pattern[str], str]
- Expected accessible error message.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_have_accessible_error_message(
- errorMessage=error_message, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def not_to_have_accessible_error_message(
- self,
- error_message: typing.Union[str, typing.Pattern[str]],
- *,
- ignore_case: typing.Optional[bool] = None,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_accessible_error_message
- The opposite of `locator_assertions.to_have_accessible_error_message()`.
- Parameters
- ----------
- error_message : Union[Pattern[str], str]
- Expected accessible error message.
- ignore_case : Union[bool, None]
- Whether to perform case-insensitive match. `ignoreCase` option takes precedence over the corresponding regular
- expression flag if specified.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_have_accessible_error_message(
- errorMessage=error_message, ignoreCase=ignore_case, timeout=timeout
- )
- )
- )
- def not_to_have_role(
- self,
- role: Literal[
- "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",
- ],
- *,
- timeout: typing.Optional[float] = None,
- ) -> None:
- """LocatorAssertions.not_to_have_role
- The opposite of `locator_assertions.to_have_role()`.
- Parameters
- ----------
- 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"]
- Required aria role.
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(self._impl_obj.not_to_have_role(role=role, timeout=timeout))
- )
- def to_match_aria_snapshot(
- self, expected: str, *, timeout: typing.Optional[float] = None
- ) -> None:
- """LocatorAssertions.to_match_aria_snapshot
- Asserts that the target element matches the given [accessibility snapshot](https://playwright.dev/python/docs/aria-snapshots).
- **Usage**
- ```py
- page.goto(\"https://demo.playwright.dev/todomvc/\")
- expect(page.locator('body')).to_match_aria_snapshot('''
- - heading \"todos\"
- - textbox \"What needs to be done?\"
- ''')
- ```
- Parameters
- ----------
- expected : str
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.to_match_aria_snapshot(
- expected=expected, timeout=timeout
- )
- )
- )
- def not_to_match_aria_snapshot(
- self, expected: str, *, timeout: typing.Optional[float] = None
- ) -> None:
- """LocatorAssertions.not_to_match_aria_snapshot
- The opposite of `locator_assertions.to_match_aria_snapshot()`.
- Parameters
- ----------
- expected : str
- timeout : Union[float, None]
- Time to retry the assertion for in milliseconds. Defaults to `5000`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(
- self._sync(
- self._impl_obj.not_to_match_aria_snapshot(
- expected=expected, timeout=timeout
- )
- )
- )
- mapping.register(LocatorAssertionsImpl, LocatorAssertions)
- class APIResponseAssertions(SyncBase):
- def to_be_ok(self) -> None:
- """APIResponseAssertions.to_be_ok
- Ensures the response status code is within `200..299` range.
- **Usage**
- ```py
- import re
- from playwright.sync_api import expect
- # ...
- expect(response).to_be_ok()
- ```
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(self._sync(self._impl_obj.to_be_ok()))
- def not_to_be_ok(self) -> None:
- """APIResponseAssertions.not_to_be_ok
- The opposite of `a_pi_response_assertions.to_be_ok()`.
- """
- __tracebackhide__ = True
- return mapping.from_maybe_impl(self._sync(self._impl_obj.not_to_be_ok()))
- mapping.register(APIResponseAssertionsImpl, APIResponseAssertions)
|