gpt4 book ai didi

python - 在 Python 中比较两个 url

转载 作者:太空狗 更新时间:2023-10-29 17:14:47 25 4
gpt4 key购买 nike

在 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"

相同是指它们访问相同的资源 - 因此示例中的两个 url 是相同的。

最佳答案

这是一个简单的类,可让您执行此操作:

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

尽管这些对象是可散列的,但它可以很容易地修改为一个函数,因此您可以使用集合或字典将它们添加到缓存中:

# Python 2
# from urlparse import urlparse, parse_qsl
# from urllib import unquote_plus
# Python 3
from urllib.parse import urlparse, parse_qsl, 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)

关于python - 在 Python 中比较两个 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5371992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com