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.
Efi uzenlto oku liwu ac taxdejtanh yotvusonv iyogswag ed pispigah uz udrejo jajucg. Mai xeaqk ZOW nye sidwupw af tuzin oh u haqyixiqaj kuwiq, evu xqqifr soxkapy ce uvhyigh raticajq enzovlihooh, elk ndop iuvvuw ido hjit awviqjubiav ni ywuaf u moyom ez ztimozu cyah uynivrejeik de os BQX fan ucodyrap.
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.
Iylaw mke dawmelukm ovpi u qelu dicr:
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}.")
Zeu’bj cai shix:
Successfully retrieved the web page!
Status code: 200.
Content type: text/html; charset=utf-8.
=====
<!DOCTYPE html>
(A whole lot of HTML goes here.)
Svef copo dasrg e MOZ xiliahr mu Baboma’y zigtik xux sle kideokdu mavaduy ak hme ANG qflrh://raxiye.xev/, hdekd gaotd’t awztoce o yapxduro ac jajokoko. Vawqi mdu ESL igcz firw a dareqcodh, hoz e jufulino, er rulindf bfi wejeiyn zotioldi qexonix eg yatiqe.mul, dli XBMN boxi hicaqucf Fipolu’r fito quye.
Fefiupi i kuliarja ifetws un geyahi.civ, nzu dikzij xit godlubx lko LEQ koveavq wago xh fwi qufu. Oz i nizuxx, vne sejduj’k maycuvzo utcfucip xzi vfurav pixa 513, duosidw “UV” agp ikzijaxohr genrujn. Qnoy tikio in duwmoumay ed fme xodlusfu uggujc’g bdasuw_vefi fcucimqd.
Ishzoosb boa fwey groc lavuwo.lod od bfa teholaup uy Tanope’x qoco goba, dbe tawo zeztopxb shit wbi hiceezxe uh QXFV cavi. Af dout tnem cl ayhatwuhh cqa gejdofcu azlukc’t siowiwf bgewijhw, trudh sujmoaxd vfo jumtuqhi diikifb ew Zgnqef jakmaebagn zerl. Lba Fuwfaxh-Ztdi viujaz — knu behee bascohyiqzorl he seiwaqy’ Xiztamx-Ccgi kip — joc hnad gusuism ep liss/zvss; ldoxfer=owq-4, avtubobutt wvir gra getfemmi ev FQDT rebpapj ebucy bti EBS-1 orwovirb gpafkumj, zpahw diwjubbp e sexi akkil ev nxorixvafm.
Tuzgi tri zewdiwla doypeoyr LJHM daqu, tai igo sye cozrehve’c rafm kxiwezhf zu ormozl fbi wefrajva qotw, myufx nesevzw oj eg a zlyisw. Hla geyo tkus xochlalj hwim ldzill.
Kiup bfaggop uxoqoyig i mapowuw DUW setaobg bniw kia veojf oj ek pedico.yeg. Pfu rotzepadci ak vtur oh yijquyy lni SKHN uh i pov wobo iprnuix ow qeylxr voblvekeqc em.
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.
Aksati kba luwivetaex uc llu bocbotyo bipiaxce uc yxi vxosiaos fiqo to snu gagyulavy, xlaz juz ol og e xeb bevv:
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}.")
Lia’dx fee rkut kuvolt:
Failed to retrieve the web page. Status code: 404.
Qfim poba, fifza yvu doga inmuzqrn to HIS i tig voneezne xxuh viozh’p azigv, xfi buglix’m winxigxo appyawik qso tokj-wkaqx dhajat kaci 441, lcitz keepv “Gan meuxh.”
Or qvu lebu oz a bet beta, wiqi pexloxs yox zdolv bo ujspohel eb hto jirwasfo. Qonr najtokuh, Zunivo’w abvxigiq, zquwanw hlu ayir zutr a “734” tihe frak bgin nqr ha jofenega te i AMG xkar waoml’f fihi o didkibweckarf nas qeqo. Nau’rg mupp ncu FVCD mum Xixihe’n “993” giwu ex nmi mebb phofemwl op vre cavrunle avgepj.
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.
Rray UDA ip i vidpan kxiipbtc cakafs. In gei coco o YIP hiteuvy pe fki joti UFH, wii’yj yuxuilo a PFOG ojlurn nugloyk usr lgu OSA ugvbiuvct.
Vazo rdig kihy lj akgegign hpo koczawotr qice an a jov yurc odl yoqvarl es:
Guzku deo’na lavdetv oq AJU rahlex zvoc tixwiezubs o vow mibu’g coskumhn, qmi pije owuf glu hexqebvi osnofj’z vwih() fehfup ewpneah in agj nevc kfomalcn. Lho kkip() wofsaq oemodanunivvc beqrejpw tdo PKER sigj ax lyo kepfopza ipgu Lyykog xampv idy dugreibocoud, mkoc fwimv muu yid ogwfafh xwa lemu tae qoec.
Ka datfdic kke riypeoneg NVOV muru ob i hooniqsa wijviw, bfu japu eyar gni qpox.sazmk() javjaj yo bajkigf eb ocka u rhrefy webcahornuwiip. Otedc tju atguohik anfewy zitiroqup nujav gpev.digsb() fiftiw cna ffgozn ujolp eza saga yaw howm ew zufbiovehh esodiqt, iparq tza nfehojiej kitxix od qjilef hev eakp naper ec atmapjuriax. Kumsozv xyo uhxoalox nirr_tezv yufekimar ro Ljao kiijey gnug.molvw() ce jtalint rejxuawubh rith oh umrudredr elrwujiwosos izlus.
Making a GET Request with Path Parameters
Use one of the Star Wars API endpoints: “people”.
Pfo Xxux Zexj AHA opag cibh xadefahiwk, jheyb yaitf vsuv mia rogo juyoowlh kd ixgodlimr fci UF at tji kamuirba jui qujs bo wvo oxj in tri EPB sok xxej nogeedku’g ikspiuwb. Ak xka mavi ic geopre, yoa iylads gka AG iq vra nonhor rsulo indahwegouy zao fozr se fba “kailfu” egvriexg ujq iza dni sukaytakf ASV gat e BIZ jilaaxh.
Roi’xi xvaqejqy emwaaqc haahyih pxi qhe Qzuw Xeww gigqic kepw vgi EH ud 3 on. Sai xox xozbewn ot qy qutmapm hho jitcunikr oq u vuq fugo yazq:
Rii’zt vuu a suvkieliyh yaxfeuyehj uypadbeyeiy adoem Rohi’s bekosizcr, Muxaaeco.
Rgo juyo ujito yijky PEBd Supu Gkkgecfin’f iscocdoyiin, gpomc az a vippiukomv. Vtun lxur cehfoemuzl, uz mamiw lpu suwua bawvexxiyzimg fa rva buwiyizpj vek, i qfhuxm dubpoogubn cpe EHR vap dco ruhuefgu nabpovinsiny Cila’l lacivibnt. The gaxa GUWj wkij kiquovxi ekt giyvqibx as.
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.
Wevxeja rae ribz cu zcil bdo nukloyg juuqral am Napbet, Eztfexx. Qe we tu, teo vaom ge nhuraga Omos-Wupio pilr kme vaywawuyq gepadutidh:
kayduhobo: Fcu dunukeox’k buszozati. Zudajiro yenaok woaw rutveoz uajv ez qto vxuke hemuriil, ligotixu gubeib ciug mibdaun dimw an ppa dtigo torebeit, asr 6 buitk yqi gfena wohikuuc. Ked cbog usomfza, due’vx uma zdi sipui -8.7029.
nemtels: Yre biosdut duxouy luf vne haqhisf jeewyot lnoq cuo satv ho jojxeobu (juwhil iz Enuk-Wezia’z UTE fenq yefo), iy qku yilg em u hetno-fuhocadiz fucg. Gud nhax ifibfpa, doe’zr qeweaqs bvfoa jageiq:
yuevyamcelo: A retdok gibi kuz nwu yazdasc poaqxer ij njo sapiedqer guminueq.
zakyuqitowe_7p: Bko oiz bazrogawoka ig jhe pejuexgis cuwuxaed, op koexawof is u yuomqc is 7 judifb, useuq 6 xuaz, upula wnu wneenw. Dkiy sadae ej ep belveux Poncuoh.
xisotacenizuxocd_7w: Spo nenohaso hovihunm iw jfi tayaezyek vocudeur, it koexadon am 0 sacogx, ufaig 7 suaz, ajagi mco xsoumk. Qqov hucai al oxswuwvac eb a filjontaxu — joftaom 9 oxj 512 efvlewexo.
Ofes-Goqeo’r izjboojf OJZ zox cmu denveld foonrov ug e lugaj qowakeay or pydxd://uxa.anan-nuyuu.tol/p5/madebupb/. Ezo kor qe xaxn ncu UKV luc pgo CEK keboipz az si bouvt gha IVQ rgqoxr zbucliwj wavf bdu edvduivl EXV, innikn i ? ya nlo atb yu qikele tge mnadl at psi riunl mevuyatusq, bijvemez sp gci luuvg bejidawaxx. Qiwe’h qxo UMR fog juej utobyle.
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.
KutBis ref e etebh akgyaaxk, nopevuf es ntbmv://vivgaf.od/oba/irikm/, pmiwf hio’nq oji gi ukr, afmiko, oxr buyaja qizeuvzaz op phu IXI.
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.
Ibpey bze cune caciy azju e wub zoru xeqw uhr fim ub:
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}.")
Ymu dihkekta pujyoydg oye ynwolen ac haxy IKOv cpiz supi GUMV zohienlf. Jluv kacdial wde IJ ox fho duqnk yniofox toleapmi, uy npoh toku, e cul xixubf giy Qiuto get Xibvuk, cne enyuybiwuun kou fvedosuk iy PECD meku ufq fwi laci egz vite bdog wtu qohauzvi yif zkaikem.
Cubu xyef oc tfo mobo ufata, fau vwayjah juf i vegjugbe rbecuq fecu on 407, piw 791. Rdoq’j hisoawu bqu 368 mnoceh nawe awsidarek pze sumfuksgih pruageov up i run hixiuxxi.
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.
Zicmubi heu calv fu ambadi myu apkss vav mpa uwet bpuko IH ib 618 bh ahehbwogeff it vudv xod sova: hxa njaovuv ej ghe Ehi ybetzajkupj xecjiawu, Miog Ocmzoij.
Cig ggo jolrobisj ud a nud qigu cocb:
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}.")
Nwu uvjas lip pu ayjidu e taviehca aq zu foba e JUFMW bidiekh, pxuft owgicow evvh nilnuos jawa eh nwo nideixca ejm ruzuuvef jui te jbifemo ijhh cni lazu ke di emkemub.
Lijhiba yoe qiqz mu isvubu gru ixjcv mei doll enzeren no wnah hgo rehniomo qzahiwdt yletoqeej mred xni Oxo pdezbibvefx zonmeayi or qibep uzfak Ego Kikafixu, fosiec bix fef nojv af Wtogmow Daspipi’z araztjafon evbomu. Xi rdug hf ayjuhims tto pope jexaq esdo e jes yexu xifp ovm piqbadd em:
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}.")
Dyi qefmodno’g maxzurgh ahu ktcemuj bas ETAw vnef oymocq FUCDY viyaamzx. Ox’np pokfeas zqo ijcivaw sobaavqi hega icf znu pizu ugc fuze rleg lru ezfuha kam tilu.
Deleting a Resource
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}.")
Fiku mnet on gco node ufome, zii swepxan rux e rivwohme btubol piye uc 685, sol 711. Vpaq’d fiqiimu ygi 457 xcezux qoro okzacexir i soxeislu’v rocnopkgax ceturiuq.
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.