Search code examples
pythonurllib

Using urljoin to add query-parameter value


I have a prepared URL https://my.comp.com/Online/SendToken?token= that I want to append the parameter value 123 to.

What I have tried so far:

from urllib.parse import urljoin

urljoin('https://my.comp.com/Online/SendToken?token=','123')
# prints 'https://my.comp.com/Online/123'

What I want to get is:

'https://my.comp.com/Online/SendToken?token=123'

I know I can use + to concatenate two strings, but I want to use the urljoin for it.


Solution

  • Issue

    If you only pass a query-parameter value, it will not join them as expected.

    Second argument

    The second argument is interpreted as path, so it needs to be a valid

    • complete path,
    • path segment (may include query-parameter or fragment)
    • query (prefixed with ?
    • fragment (prefixed with #)

    See the docs for urljoin, use the first 2 examples:

    from urllib.parse import urljoin
    
    # the complete query-parameter (question-mark, key, value)
    urljoin('https://my.comp.com/Online/SendToken?token=','?token=123')
    # 'https://my.comp.com/Online/SendToken?token=123'
    
    # the complete path-segment including query
    urljoin('https://my.comp.com/Online/SendToken?token=','SendToken?token=123')
    # 'https://my.comp.com/Online/SendToken?token=123'
    
    # a fragment (denoted by hash-symbol) will also work, but not desired
    urljoin('https://my.comp.com/Online/SendToken?token=','#123')
    # 'https://my.comp.com/Online/SendToken?token=#123'
    

    See also Python: confusions with urljoin