2

So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address http://www.stackoverflow.com/questions/ask. I would need the protocol and domain (e.g. http://www.stackoverflow.com) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?

cHao
  • 82,321
  • 20
  • 145
  • 171
The.Anti.9
  • 41,164
  • 46
  • 118
  • 158
  • Duplicate. See http://stackoverflow.com/questions/258746/slicing-url-with-python and http://stackoverflow.com/questions/163009/urllib2-file-name – S.Lott Nov 13 '08 at 10:57

3 Answers3

13

Dan is right: urlparse is your friend:

>>> from urlparse import urlparse
>>>
>>> parts = urlparse("http://www.stackoverflow.com/questions/ask")
>>> parts.scheme + "://" + parts.netloc
'http://www.stackoverflow.com'
>>> parts.path
'/questions/ask'

Note: In Python 3 it's from urllib.parse import urlparse

Paulo Almeida
  • 7,395
  • 26
  • 34
Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649
  • Gotta love that batteries included philosophy. I thought regex at first b/c I didn't know about that battery was included. Thanks. – Sam Corder Nov 13 '08 at 18:22
7

Use the Python urlparse module:

https://docs.python.org/library/urlparse.html

For a well-defined and well-traveled problem like this, don't bother with writing your own code, let alone your own regular expressions. They cause too much trouble ;-).

twasbrillig
  • 14,704
  • 9
  • 39
  • 61
Dan Fego
  • 13,016
  • 5
  • 45
  • 58
-1
import re
url = "http://stackoverflow.com/questions/ask"
protocol, domain = re.match(r"(http://[^/]*)(.*)", url).groups()
Cybis
  • 9,487
  • 2
  • 35
  • 37