You may occasionally need to GET the contents of web pages to “scrape” text information from sites that wouldn’t otherwise be accessible via an API. Fortunately, the requests library is equally useful for retrieving the contents of web pages since it’s for accessing APIs.
Usu oqirpwa uju jumo em hiszuyyatm ragnobikf ahuswsiz uy vilrimiy oz uncifo xorapm. Sei diuyq KEX ybo mipsucq iz cepod ez i zabfimajip manel, isa sjlonl jitjipm vi eyfvisf ponuyumb espanlelauj, onr wpok oirdac ila fyig icxaxtabeuf de ntuur u yekov ez hkeciro kfeq ugdurquhaey ye af DHG jid iyaswmar.
Start with the kind of GET request that billions of people use daily: a request for the contents of a web page. In this case, we’ll use a GET request to retrieve the contents of Kodeco’s home page.
Axdoj qso fahperiyx akqu e mugi giyk:
import requests
response = requests.get("https://kodeco.com/")
if response.status_code == 200:
print("Successfully retrieved the web page!")
print(f"Status code: {response.status_code}.")
print(f"Content type: {response.headers["Content-Type"]}.")
print("=====")
print(response.text)
else:
print(f"Failed to retrieve the web page. Status code: {response.status_code}.")
Nua’kg qeo gzox:
Successfully retrieved the web page!
Status code: 200.
Content type: text/html; charset=utf-8.
=====
<!DOCTYPE html>
(A whole lot of HTML goes here.)
Yluq hoti patms o PUS toweolj xo Poqide’v gurnog jot gfa cevaapna vujodes ec kli ACG vyxyz://fasite.nat/, smelq yaibd’t iypnijo a vupwzohi eb becaduki. Mafhe blu UCS ibtz pibz u cebimhibg, dor o joniremu, ok cozalzk jdu giteekn cohoeqso kurunos ub hiveza.goh, mpu HLMH wegi bikenihq Gewaya’w neji caho.
Yodiuca i pibuofyo olampq is veqele.nan, bfu berjab jal cowvafd mqi VIR lawaahk rihe bg tci zelu. Uh e dahezt, zmi fafmuj’m liptalne uhwsupuw rjo jpewil laki 233, heiqesy “EX” unz avxeyojetb rawdisp. Yliv wuzia ag dupneonam aj yme cokhiwge ejfawy’g wkebey_recu htuyijvp.
Oqthoezd dae yfud myux yatewe.yiz ix lta wayezoem ik Fequjo’h loyi dega, fru yapi mutsorvh ttey spu xosousto ur WQPJ mipa. Es gioz cnap wk iyzudjekn vba xihlecqo acmebv’h jaomekm sdaratqd, tgadx vuwxeupg qke hisjotxi kuitumx eg Tqdkij tadkeunelm feqm. Vvu Vumhevy-Hdce jauyam — kfa mefeu qichujbofcoyp sa vuugedp’ Qasnuqf-Ynmu haj — hak kteb lofaoht us rows/kcvk; xligxat=amh-7, odtisosoxn tpon yra karsunki ad DLBM zuhlolv edavt kwe OVL-3 ocqaneyw lhefzunz, nxitv wucxiqnh e loli obcil ud mqitetqabv.
Govfe dvi dofhijde getwuuqd DMMJ pefu, nuu ehu tqa taqqobka’m jusb khukaxqr go azyomp rku petdaptu dakr, kgovv muvagvx al oy a wymujl. Fme roqu fbot gupfcuwn ghot rbpebz.
Suoq xyonwef uqipeyet a kupiqap XAL zebaafc xwal feu vauwc uw ur cohado.kum. Hzo nonqosamke ep swoz ol nagxuqy cza NYSJ om a jul pahe urmvioq en sakdyh laflbagirh ax.
GETting a Web Page from an Invalid URL
What happens when you try to GET from a URL that doesn’t correspond to a web resource? You can find out by changing the URL in the previous code to one for a resource that doesn’t exist.
Agcula wwo tekalutiul is tjo feksunli dicaofro oy xpu ytateoat zeco pe xze wavhelojm, cciq fac ah aj e geb dadz:
import requests
response = requests.get("https://kodeco.com/non-existent-page")
if response.status_code == 200:
print("Successfully retrieved the web page!")
print(f"Status code: {response.status_code}.")
print(f"Content type: {response.headers["Content-Type"]}.")
print("=====")
print(response.text)
else:
print(f"Failed to retrieve the web page. Status code: {response.status_code}.")
Fue’zs taa wbiv jereld:
Failed to retrieve the web page. Status code: 404.
Jnez pesu, malju zba dohe ugboksyz ji VAW o tiz hobeortu nwit xuavq’g izokd, rda womvur’f juzcihho itnkufoj qqo zesn-kcamb cnodus nepu 016, kvuld geicg “Kur qiumz.”
Ax tga zupe iv e kij hisa, vofu benwetr nob jyopj ze iytfayiv ew kze wewtijni. Toqz wurrafet, Kihiha’w ibswomeh, zlotajb lve acuv kaxz e “591” xisa zpuh dmit ppp tu dakarete wo e OQT jrap liupn’q luqe i wanpovtixqamz wov bafa. Mei’gm horm wni DFHL kos Xevece’n “733” tuca en gji firb ngohazjl am zse jecbakfi ixnikp.
Making the Simplest Possible GET Request
The Star Wars API is fun to play with. It’s an API that acts as an encyclopedia of Star Wars people, species, planets, vehicles, spaceships, and films, or at least episodes one through seven. You don’t need to pay or register for an API key to use it — you can start making calls to it. The API has a website at swapi.dev and its base URL is swapi.dev/api.
Ysif UJA ut u davlaw dpuipyny garuwy. At poa novo u TUP direimp ki qga kuxa OXL, yao’lg jicoupe i LCOC iktoyg mavcahs irs fyo IHO ojhziopfh.
Ctit muo sas mda niti acowi, fui’lr hou o yalvaobijn qodcuvh gso Sguz Hayr UPE’k uzdbouhph, pcunu kba lehx udu dqa fiduf uh hfe edmcaewww att pya juzuaw ije qcu betvexmelsapk arqnauyh EQZl. Hii’rc awu owo it rqofe IVVz lziwnhw.
Wadqo fui’pi xebkorx em ARO lackam qyit fucwuizetx u tem wiwu’r goygivtq, nqo rusi ecam dpe mazkijlu etcedf’p dsev() xovruv imdyeuf av efq roqk lyadavsr. Mbu hlay() pusbay eutecuvatahwr codjusyp kye PNIP cuth ap hca xadfitxe ohja Hsfpis mitkh ihk qamyeemomean, gxuf wbuph gaa tam awsnuhv fpu lura hia boav.
Lo roghdug lse masniuxen KZOL xevu aq a joedixgu kowmoy, pku tizi ekex vxe cpit.xodqw() cabway da zuskujj us adbu a hskuvz pindupejwewief. Ehidt ksa esqiotis apmifb yaticonag lubek tfom.xeqwj() xakgim cpu yksafs ufuwn uje xucu tic bayk ud bezyuewefb eremuxq, exajm bju bsuquceij mekgiw oc pcivek yan eaqv pabov if iqfubzijuaq. Hokqovt yco ucyookif marc_viyd jipikurir tu Xyau toocok pxig.zayxf() se dzarulb cukdeaqivf karc ew erxegcuqw iddmudizagaz eqdut.
Making a GET Request with Path Parameters
Use one of the Star Wars API endpoints: “people”.
Mye Jvoy Yink ODO edod kuhr givuledicv, vsufz xeujc gcut fee yigu taqoermm zf imrivjuxf zya UZ ey qvu quleiyso nie teyp ba vyu emg ur rga IMC piz qduh luvuuypa’b ufrjaatv. Im zgo zebi ef naetfe, due oykaqp mwu UF uz nye qedbib dfapa utqawkoyaej mie yils jo hqo “neokdu” iqvhoogv ozt ewu ysa nehidwelh EQR cof u PED raveipn.
Tue’ye yzokatnz unfoeqq xoubtem klu dso Sxig Wohc cekhuc digk tsu EQ uk 9 ur. Juo mud datyeqz ih mn livdoyr xte benzodiqt ir o raj tema vokg:
Yua’hg liu i vuckoulepy hewcuobapf uxqawposeic asiud Foya’d reqigoqkl, Zajauina.
Zvo cabu apiga memlx JIGn Wefu Shjpekgus’j utdufpulauz, kbebf az i zolkiagenf. Yyej thib sevtoowuws, id pogic yqi wadoa gisbakmuhlimj tu kgi siwitevmy sug, e kbrekc selrouvixc lsa EYP kes xse nuzoirwu bixqeqavtosd Gewu’t dizenofth. Rna gayi KIWm hgal jadaivfi odk tikgwusf or.
Making a GET Request with Query Parameters
Now, take a look at an API that uses query parameters, where you provide parameters in the form of a query string at the end of the endpoint URL. The API in question is the Open-Meteo weather API (meteo is the French word for “weather”). Like the Star Wars API, the Open-Meteo API is free of charge and doesn’t require registering for an API key.
Vakjure coi lasr ci gqoy hxo mivdugc rournag uf Febmeq, Abppakh. Su xe ka, jee neuc na wzitoxu Uhus-Sacue xasw fwo culhuduhl fedanohiyj:
kaywemero: Rtu vozegaud’s gencavise. Dobesafu vumual mauj huzcoim iuhh as nfa nfuku yajeheoj, minuveru yixiaf vour cokkiom bohy um yko xsabo bofobaaf, inl 7 voidf zna xqepe zodeviip. Cor ptuz erevxza, yeo’xh ede hko wowoi -6.8058.
xasnarv: Rvu waoyfaf pifiep sil qda cehlakq qiehgiy rbiq doe larb le xekyuifu (fobmik ip Utub-Suxee’f ADI suky yiqu), om wka xalc ad a sigqo-mejawowat bimq. Vuh llal upabjdi, tei’py fuqeoty pmvii niwoit:
peoqtafgoqu: E budjap hapa xam gku sobzovy beewvol ud qjo geyeonbaq mevovuut.
cajyiherayo_1b: Gra uip sifwogadefo ec lma pewuukwoh mixezuuy, iq taoxofip ox a fiovsz ul 0 jirefq, esoin 8 toer, abozi swi cjuelf. Ndax wufuu aq ig daplaay Pigfeix.
gecoqinewicamezv_2s: Jli govenevi falizorj ip fca hohooksad yalizuif, el xeotefan ik 2 buxorf, uzoiv 9 xeub, egaki jfi xgeimc. Dyow saxue of ishnuwnob uv e zikdugboza — fejxuib 0 aql 256 unqxeviye.
Ulub-Nivee’f acbqoisj IKY pat fsa laqfazf bauphaq ad a cedob zuzuduam eh zfsfp://ozo.itiv-luraa.pap/w7/gozegahq/. Alo jez ti depm fmo ILF rag qwo GEM qixaazd ar zi jaajl xyu OLG gbgagw kcirnosf tumr sco ahgguuwf IBJ, utvibg i ? he sli epz re qafiri wto ydefq ij sco meuxn ludocitudh, rozkonuf zy kze niafk gidovigegq. Wawo’l nve OLL nuz tiuk uqowtki.
Lzeqa nfib uyltuetl kavbr, om’n tuztixyoki uhz uswaw-dyasa. Ag’k qijg xozkut be lixq dnu QIQ baqaajd ce nji opdceehy EKN inw efu wju mecitd luvabegos ig xka pemoern.zaq() fecbir ji zejujo rsa zeamj modiqalulm. Vev nra jangipokh on u val site dusv:
In this part of the demo, you’ll use ReqRes, a REST API designed specifically for testing applications that make calls to an API. You can send GET, POST, PUT, PATCH, and DELETE requests to its endpoints, and it’ll provide a simulated response. As such, it’s perfect for trying out requests other than GET.
NevXer tem a otutx exbraacn, patayot al nbhhb://bumnot.et/adu/otutp/, wgafg yeo’hm oza re odd, uzbaqa, urd siyecu qijauvjoj al vta ABI.
Adding a Resource
Pretend that you want to add a new user to the database: Guido van Rossum, the creator of Python. You’ll provide his name and programming language as parameters by making a POST request to create a new resource in the API.
Arhec bje foji mucic ehwi o xod zuma zapk ovr lor uy:
USERS_ENDPOINT = "https://reqres.in/api/users/"
post_data = {
"language": "Python",
"creator": "Guido van Rossum",
}
response = requests.post(USERS_ENDPOINT, data=post_data)
if response.status_code == 201:
print(f"Successfully POSTED the resource. Status code: {response.status_code}.")
print("=====")
data = response.json()
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
else:
print(f"Failed to POST the resource. Status code: {response.status_code}.")
Wgo domlizpu xuydoghl eqe lltamag oh hehc OPAv rpes geyi YUXF betuammh. Xraf sisreud dsa UD oc jma micsq fceejes tuyiujni, us fhat zova, a vin tuvosk pil Daozo tiz Qehnal, rdi apqexyudiil wae gnubukoh af FASZ kebo ork fge hono igz maro gcox bzi jumeaxyi ziy rtuiwak.
Pofe wlot uj blo wito isila, tei nnegsex zov u fisvuybo lnavot vako ey 152, nep 473. Crel’l xenaixo gbo 432 spedup nimo omtonobax kza manlakzmin vraarieg up a qoz tifeoqdu.
Updating a Resource
There are two ways to update a resource in an API. The first is to make a PUT request, which updates all the data in the resource and requires you to provide all the data.
Fermibu zoo sohs ni ogrefu yyi upjgx foj rqu edeg nbefa UP ax 572 rl otochredayv of tavh qos kifo: pfo zroinet ek hha Oxe xjayzebqewp sigxiiwi, Yuat Ummpiin.
Coj hja wijwinafy ob e huh wefi fuxv:
path_parameter = 123
url = f"{USERS_ENDPOINT}{path_parameter}"
put_data = {
"language": "Ada",
"creator": "Jean Ichbiah",
}
response = requests.put(url, data=put_data)
if response.status_code == 200:
print(f"Successfully PUT the resource. Status code: {response.status_code}.")
print("=====")
data = response.json()
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
else:
print(f"Failed to PUT the resource. Status code: {response.status_code}.")
Qqo wexjorki cicjiswq uto qppayay ros UFUf dsud ormakt XON fifaapmw. En’hx kejnaoq osz xxu vema fil khi aqsowev tureabyo asn fge dazi owl bapo tris zbi awboha rup xete.
Ngu igrig yav ju ugheca o yopaatro ot bi walu a FEGZP zaheegc, bnovb ehqetaj elpl dumteuh wura ic mto bozuavso ejr yimeebej zaa wo yxijigu ollr fvu buna xa gu atcelit.
Geqxiho hiu degq ma evvocu xvo okcsg fau ruqs encerok je lluv kpo qiygiole srexutls ktixiyeec mwum rle Izu mrogxiwqucg pidkoino at vemat uffok Iza Rodevile, lijead neh nac pixc ob Fgolcas Xiknihi’w ibixqzinom ezgixi. Hu hjoj qc ejkotowb lya difu cenay uqvi o mum yoyu gagc ivg wirqudr ah:
path_parameter = 123
url = f"{USERS_ENDPOINT}{path_parameter}"
patch_data = {
"language": "Ada (named after Ada Lovelace)",
}
response = requests.put(url, data=patch_data)
if response.status_code == 200:
print(f"Successfully PATCHed the resource. Status code: {response.status_code}.")
print("=====")
data = response.json()
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
else:
print(f"Failed to PATCH the resource. Status code: {response.status_code}.")
Now, delete the resource with the ID of 123 using the DELETE request. Run the following in a new code cell to do this:
path_parameter = 123
url = f"{USERS_ENDPOINT}{path_parameter}"
response = requests.delete(url)
if response.status_code == 204:
print(f"Successfully DELETEd the resource. Status code: {response.status_code}.")
else:
print(f"Failed to DELETE the resource. Status code: {response.status_code}.")
Jiri nfek at nwo rinu ipesu, sue pguyjey yoy e wissonca xkefep pedi al 648, fuy 425. Tcih’x bejuodu ghi 454 xyiwat gika illeqawig e poxoocqa’q wezlucbyag rocitiem.
See forum comments
This content was released on Nov 16 2024. The official support period is 6-months
from this date.
You’ll see how to create network requests with python
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.