I need to know how to build URLs in python like:
http://subdomain.domain.com?arg1=someargument&arg2=someotherargument
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:
from collections import namedtuple
from urllib.parse import urljoin, urlencode, urlparse, urlunparse
# namedtuple to match the internal signature of urlunparse
Components = namedtuple(
    typename='Components', 
    field_names=['scheme', 'netloc', 'url', 'path', 'query', 'fragment']
)
query_params = {
    'param1': 'some data', 
    'param2': 42
}
url = urlunparse(
    Components(
        scheme='https',
        netloc='example.com',
        query=urlencode(query_params),
        path='',
        url='/',
        fragment='anchor'
    )
)
print(url)
Output:
https://example.com/?param1=some+data¶m2=42#anchor