是否有一种标准方法来比较Python中的两个URL - are_url_the_same在此示例中实现:
url_1 = 'http://www.foo.com/bar?a=b&c=d'
url_2 = 'http://www.foo.com:80/bar?c=d;a=b'
if are_urls_the_same(url_1, url2):
print "URLs are the same"
Run Code Online (Sandbox Code Playgroud)
同样我的意思是他们访问相同的资源 - 所以示例中的两个网址是相同的.
twn*_*ale 11
这是一个简单的类,使您可以执行此操作:
if Url(url1) == Url(url2):
pass
Run Code Online (Sandbox Code Playgroud)
它可以很容易地作为一个函数进行修改,虽然这些对象是可以清除的,因此可以使用set或dictionary将它们添加到缓存中:
from urlparse import urlparse, parse_qsl
from urllib import unquote_plus
class Url(object):
'''A url object that can be compared with other url orbjects
without regard to the vagaries of encoding, escaping, and ordering
of parameters in query strings.'''
def __init__(self, url):
parts = urlparse(url)
_query = frozenset(parse_qsl(parts.query))
_path = unquote_plus(parts.path)
parts = parts._replace(query=_query, path=_path)
self.parts = parts
def __eq__(self, other):
return self.parts == other.parts
def __hash__(self):
return hash(self.parts)
Run Code Online (Sandbox Code Playgroud)
使用urlparse并将compare函数与您需要的字段一起编写
>>> from urllib.parse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
Run Code Online (Sandbox Code Playgroud)
你可以比较以下任何一个: