Question: I am iterating over multiple URLs in a csv file; the URLs have the next structure:

```
http://www.parool.nl/parool/nl/4024/AMSTERDAM-CENTRUM/article/detail/3751723/2014/09/21
http://www.parool.nl/parool/nl/5/POLITIEK/article/detail/3751624/2014/09/20/VVD-wil-  boete-van-250-euro-voor-het-naroepen-van-vrouwen.dhtml

```

etc., 

I need to get the article category (after the 4th slash, "AMSTERDAM-CENTRUM" and "POLITIEK", in this case), and append them to a list.

I'm working with urllib2:

```
reader=CsvUnicodeReader(open("my.csv","r"))
for row in reader:
    url = row[0]
    req=urllib2.Request(url)

```

Is there a way to parse the URL?

Answer: 
You can use [`urlparse.urlparse`](https://docs.python.org/2/library/urlparse.html#urlparse.urlparse) to split the URL into its components and reliably extract the path component, and then use a [regular expression](https://docs.python.org/2/library/re.html) to extract the category part of the path you're interested in:

```
from urlparse import urlparse
import re

URLS = ["http://www.parool.nl/parool/nl/4024/AMSTERDAM-CENTRUM/article/detail/3751723/2014/09/21",
        "http://www.parool.nl/parool/nl/5/POLITIEK/article/detail/3751624/2014/09/20/VVD-wil-boete-van-250-euro-voor-het-naroepen-van-vrouwen.dhtml"]

pattern = re.compile("/parool/nl/\d*/(.*?)/article/detail/.*$")

for url in URLS:
    parsed = urlparse(url)
    match = pattern.match(parsed.path)
    if match:
        category = match.group(1)
        print category

```

Output:

```
AMSTERDAM-CENTRUM
POLITIEK

```

---

Notes on the regular expression:

* `\d*` matches any digit (0-9) zero to multiple times
* `/(.*?)/` matches any character zero to multiple times between two slashes, non-greedy, and creates a group for the part between the slashes
If all URLs have similar structure you can simply use

```
url.rsplit('/')[6]

```