Python - Split url into its components

Hyperion picture Hyperion · Jul 1, 2015 · Viewed 16.8k times · Source

I have a huge list of urls that are all like this:

http://www.example.com/site/section1/VAR1/VAR2

Where VAR1 and VAR2 are the dynamic elements of the url. What I want to do is to extract from this url string only the VAR1. I've tried to use urlparse but the output look like this:

ParseResult(scheme='http', netloc='www.example.com', path='/site/section1/VAR1/VAR2', params='', query='', fragment='')

Answer

alecxe picture alecxe · Jul 1, 2015

Alternatively, you can apply the split() method:

>>> url = "http://www.example.com/site/section1/VAR1/VAR2"
>>> url.split("/")[-2:]
['VAR1', 'VAR2']