使用Python 3编码URL

2024-09-30 14:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用像这样的生成的url http://www.viaf.org/viaf/search?query=cql.any+=+%22Jean-Claude%20Moissinac%22&maximumRecords=5&httpAccept=application/json

但是当它和

# -*- encoding: utf-8 -*- import urllib.request # successful trial with the URI urlQuery = u'http://www.viaf.org/viaf/search?query=cql.any%20=%20"Bacache%20Maya"&httpAccept=application%2Fjson&maximumRecords=5' print(urlQuery) req = urllib.request.Request(urlQuery) with urllib.request.urlopen(req) as rep: print("success") # attempt to build the URI; request fails viafBaseUrl = u"http://www.viaf.org" viafCommand = u"/viaf/search?" viafSearchTemplate = u'"__name%20__surname"' name = u"Bacache" surname = u"Maya" searchString = u'cql.any%20=%20' + viafSearchTemplate.replace(u"__surname", surname).replace(u"__name", name) params = u"query="+searchString+u"&httpAccept=application%2Fjson&maximumRecords=5" computedQuery = viafBaseUrl + viafCommand + params print(urlQuery) if computedQuery==urlQuery: print("same strings") req = urllib.request.Request(computedQuery) with urllib.request.urlopen(req) as rep: print("success")

第一个请求成功,而第二个请求失败,错误如下:

^{pr2}$

我试了很多方法来解决这个问题,但没有成功。 使用urllib.parse.urlencode()失败,因为它更改了一些必须保持不变的字符。在

在两个url上打印的结果是相同的,但是字符串不同,但是我不知道如何获得相同的字符串。在


Tags: orghttpsearchrequestwwwurllibsurnamequery
2条回答

字符串application%2F中在n%之间有一个隐藏的unicode字符。只要删除它,它应该可以工作。在

在第二个print语句中,意外地引用了第一个查询urlQuery,而不是{}。在修复print语句之后,计算查询中有一个额外的空间,这一点变得明显。在

更新了下面的代码,其中包含了修复程序和一些注释:

# -*- encoding: utf-8 -*- import urllib.request # successful trial with the URI urlQuery = u'http://www.viaf.org/viaf/search?query=cql.any%20=%20"Bacache%20Maya"&httpAccept=application%2Fjson&maximumRecords=5' print(urlQuery) req = urllib.request.Request(urlQuery) with urllib.request.urlopen(req) as rep: print("success") # attempt to build the URI; request fails viafBaseUrl = u"http://www.viaf.org" viafCommand = u"/viaf/search?" viafSearchTemplate = u'"__name%20__surname"' name = u"Bacache" surname = u"Maya" searchString = u'cql.any%20=%20' + viafSearchTemplate.replace(u"__surname", surname).replace(u"__name", name) params = u"query="+searchString+u"&httpAccept=application%2Fjson&maximumRecords=5" # space after application deleted computedQuery = viafBaseUrl + viafCommand + params print(computedQuery) # was urlQuery if computedQuery==urlQuery: print("same strings") req = urllib.request.Request(computedQuery) with urllib.request.urlopen(req) as rep: print("success")

和13;
和13;

相关问题 更多 >