XZS*_*XZS 11 url normalization python-3.x
我正在寻找一个库函数来规范化Python中的URL,即删除路径中的"./"或"../"部分,或添加默认端口或转义特殊字符等.结果应该是一个字符串,对于指向同一网页的两个URL是唯一的.例如http://google.com,http://google.com:80/a/../应返回相同的结果.
我更喜欢Python 3并且已经查看了urllib模块.它提供了分割URL的功能,但没有规范它们的功能.Java具有URI.normalize()执行类似操作的功能(虽然它不认为默认端口80等于没有给定端口),但是这样的东西是python吗?
有了良好的开端之后,我编写了一个适合网络上常见的大多数情况的方法。
def urlnorm(base, link=''):
'''Normalizes an URL or a link relative to a base url. URLs that point to the same resource will return the same string.'''
new = urlparse(urljoin(base, url).lower())
return urlunsplit((
new.scheme,
(new.port == None) and (new.hostname + ":80") or new.netloc,
new.path,
new.query,
''))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9373 次 |
| 最近记录: |