Using urljoin to add query-parameter value

Question:

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.

Asked By: Mehdi Aria

||

Answers:

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

Answered By: hc_dev
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.