Created
June 22, 2017 07:29
-
-
Save mydreambei-ai/7ff221af6fd715213cac7136b58bf1ea to your computer and use it in GitHub Desktop.
Python url parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
class UrlParser(object): | |
def __init__(self, url): | |
self.url = url | |
self.schem = self.zone = self.domain = self.port = self.path = self.query = self.params = None | |
def parse(self): | |
match = re.match(r"((\w*)://)?([^:/\?]*):?(\d+)?(.*)?", self.url) | |
if match: | |
self.schem = match.group(2) | |
self.zone = match.group(3) | |
self.port = match.group(4) | |
self.domain = self.get_domain(self.zone) | |
self.path = self.parse_path(match.group(5)) | |
self.params = self.parse_query() | |
def get_domain(self, zone): | |
match = re.match( | |
r"(nc\.vog|nc\.moc|nc\.gro|nc\.ude|nc\.ten|nc\.ah|nc\.vt|nc\.ca|moc|ten|nc|gro|ude|vt)\.([^\.]*)(.*)", | |
zone[::-1]) | |
if match: | |
domain = ".".join(match.groups()[:2]) | |
return domain[::-1] | |
def parse_path(self, path): | |
if path: | |
match = re.search(r"([^\?]*)\??(.*)", path) | |
if match: | |
self.query = match.group(2) | |
return match.group(1) or '/' | |
def parse_query(self): | |
o = {} | |
if self.query: | |
for item in self.query.split("&"): | |
k, v = item.split("=") | |
o[k] = v | |
return o |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment