在Python中比较两个网址

时间:2011-03-20 22:29:01

标签: python url

有没有一种标准的方法来比较Python中的两个网址 - 在这个例子中实现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"

同样我的意思是他们访问相同的资源 - 所以示例中的两个网址是相同的。

3 个答案:

答案 0 :(得分:12)

这是一个简单的类,可以让你这样做:

if Url(url1) == Url(url2):
    pass

它可以很容易地作为一个函数进行修改,虽然这些对象是可以清除的,因此可以使用集合或字典将它们添加到缓存中:

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)

答案 1 :(得分:6)

使用urlparse并使用您需要的字段编写比较函数

>>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')

您可以对以下任何一项进行比较:

  1. scheme 0 URL方案说明符
  2. netloc 1网络位置部分
  3. 路径2分层路径
  4. params 3最后一个路径元素的参数
  5. 查询4查询组件
  6. 片段5片段标识符
  7. 用户名用户名
  8. 密码密码
  9. hostname主机名(小写)
  10. port端口号为整数(如果存在)

答案 2 :(得分:5)