如何比较URI编码的字符串?

问题描述 投票:0回答:1

我接受了一家成长型初创公司的采访。问题之一是有关URI编码的问题。

W3.org说这些URI是相同的。我用b93更改了abc。我知道了

>>> url4 = "http://b93.com:80/~smith/home.html"
>>> url5 = "http://b93.com/%7Esmith/home.html"
>>> urllib.parse.quote(url4)
'http%3A//b93.com%3A80/~smith/home.html'
>>> urllib.parse.quote(url5)
'http%3A//b93.com/%257Esmith/home.html'

如何比较编码的字符串以获取正确的信息?如何执行进一步的测试?

我也尝试过带有encodeURIComponenet()的JS

var p1 = encodeURIComponent("http://b93.com:80/~smith/home.html");
var p2 = encodeURIComponent("http://b93.com/%7Esmith/home.html");

console.log(p1);
console.log(p2);

输出

http%3A%2F%2Fb93.com%3A80%2F~smith%2Fhome.html
http%3A%2F%2Fb93.com%2F%257Esmith%2Fhome.html

已解决编辑

deceze建议我规范化我的网址Node.Js代码

var normalizeUrl = require('normalize-url');

var n1 = normalizeUrl("http://b93.com:80/~smith/home.html");
var n2 = normalizeUrl("http://b93.com/%7Esmith/home.html");

console.log(n1);
console.log(n2);

var p1 = encodeURIComponent(n1);
var p2 = encodeURIComponent(n2);

console.log(p1);
console.log(p2);

工作正常

http://b93.com/~smith/home.html
http://b93.com/~smith/home.html
http%3A%2F%2Fb93.com%2F~smith%2Fhome.html
http%3A%2F%2Fb93.com%2F~smith%2Fhome.html
python http encode
1个回答
0
投票

一种方法是首先确保您将比较未引用的URL(通过使用urllib.parse.unquote而不是urllib.parse.quote)。然后,您可以使用urllib.parse.urlparse提取URL的主要部分并进行比较。

from urllib.parse import unquote, urlparse
url4 = "http://b93.com:80/~smith/home.html"
url4 = unquote(url4)
url5 = "http://b93.com/%7Esmith/home.html"
url5 = unquote(url5)
u4 = urlparse(url4)
u5 = urlparse(url5)
if u4.scheme == u5.scheme and u4.hostname == u5.hostname and u4.path == u5.path:
    print('equal')
else:
    print('different')

确实,您可能还想通过schemeport is None时定义端口来比较端口。

© www.soinside.com 2019 - 2024. All rights reserved.