Daniela
Daniela

Reputation: 911

Python: compose a search results URL

I would like to compose a form results URL whereas certain parts can be programatically changed. I've read similar questions were requests urljoin() is used but it can take only two parameters. Is there anything more appropriate for this scenario?

This is the base

https://navlib.forth-crs.gr/italian_b2c/npgres.exe?func=TT&ReservationType=npgres.exe%3FPM%3DBO&Leg1i=

This part is the route which will need to change

BEV&Leg1ii=PRJ

This is the date which will need to change

&Leg1Date=28%2F02%2F2019

This part will not need changing

&TotalPassengers=1&TotalPassengersHuman=1&TotalPassengersAcce=0&TotalVehicles=0

Upvotes: 0

Views: 50

Answers (1)

cody
cody

Reputation: 11157

Use urllib.parse.urlencode, it takes a mapping or two-element tuple sequence and produces a properly-encoded query string:

import urllib.parse

params = urllib.parse.urlencode({
    "Leg1ii": "PRJ",
    "Leg1Date": "28/02/2019",
    "TotalPassengers": "1",
    "TotalPassengersHuman": "1",
    "TotalPassengersAcce": "0",
    "TotalVehicles": "0",
})

print(f"https://navlib.forth-crs.gr/italian_b2c/npgres.exe?{params}")

Result:

https://navlib.forth-crs.gr/italian_b2c/npgres.exe?Leg1ii=PRJ&Leg1Date=28%2F02%2F2019&TotalPassengers=1&TotalPassengersHuman=1&TotalPassengersAcce=0&TotalVehicles=0

Upvotes: 1

Related Questions