簡體   English   中英

用 python 3 編碼一個 url

[英]encoding an url with python 3

我正在嘗試使用這樣一個生成的 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")

第一個請求成功,而第二個請求失敗並出現此錯誤:

UnicodeEncodeError: 'ascii' codec can't encode character '\ufeff' in position 76: ordinal not in range(128)

我嘗試了很多方法來解決這個問題,但都沒有成功。 使用urllib.parse.urlencode()失敗,因為它更改了一些必須保持完整的字符。

兩個url上的打印結果是一樣的,但是字符串不同,但是我不明白如何獲得相同的字符串。

n%之間的字符串application%2F有一個隱藏的 unicode 字符application%2F 只需刪除它,它應該可以工作。

在你的第二個print語句你不小心參考第一查詢urlQuery代替computedQuery 計算查詢中有一個額外的空間,在修復打印語句后變得明顯。

使用修復程序和一些評論更新了下面的代碼:

 # -*- 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM