I need to know how to build URLs in python like:
JavaScript
x
2
1
http://subdomain.domain.com?arg1=someargument&arg2=someotherargument
2
In the python standard library, how would you build a URL?
Advertisement
Answer
urlparse
in the python standard library is all about building valid urls. Check the documentation of urlparse
Example:
JavaScript
1
27
27
1
from collections import namedtuple
2
from urllib.parse import urljoin, urlencode, urlparse, urlunparse
3
4
# namedtuple to match the internal signature of urlunparse
5
Components = namedtuple(
6
typename='Components',
7
field_names=['scheme', 'netloc', 'url', 'path', 'query', 'fragment']
8
)
9
10
query_params = {
11
'param1': 'some data',
12
'param2': 42
13
}
14
15
url = urlunparse(
16
Components(
17
scheme='https',
18
netloc='example.com',
19
query=urlencode(query_params),
20
path='',
21
url='/',
22
fragment='anchor'
23
)
24
)
25
26
print(url)
27
Output:
JavaScript
1
2
1
https://example.com/?param1=some+data¶m2=42#anchor
2