我正在尝试使用Python以编程方式生成URL。使用Java Script方法(encodeURIComponent)时可以使用,但使用Python(urllib.urlencode)时不会提供相同的输出
这是架构:
{
"page": {
"filters": {
"power": {
"keywordArray": [{
"keyword": "random word",
"isNegated": false
}],
"date": {
"from": "2019-04-22T08:00:00.000Z",
"to": "2019-05-22T08:00:00.000Z"
}
}
}
}
}
我使用(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent成功地尝试了Java脚本方法encodeURIComponent ):
console.log(encodeURIComponent('({"page":{"filters":{"power":{"keywordArray":[{"keyword":"random word", "isNegated":False}],"date":{"from":"2019-04-22T08:00:00.000Z","to":"2019-05-22T08:00:00.000Z"}}}}})'));
(%7B%22page%22%3A%7B%22filters%22%3A%7B%22power%22%3A%7B%22keywordArray%22%3A%5B%7B%22keyword%22%3A%22random%20word%22%2C%20%22isNegated%22%3AFalse%7D%5D%2C%22date%22%3A%7B%22from%22%3A%222019-04-22T08%3A00%3A00.000Z%22%2C%22to%22%3A%222019-05-22T08%3A00%3A00.000Z%22%7D%7D%7D%7D%7D)
我无法使用Python生成相同的输出:
params = {
"page": {
"filters": {
"power": {
"keywordArray": [{
"keyword": "random word",
"isNegated": False
}],
"date": {
"from": "2019-04-22T08:00:00.000Z",
"to": "2019-05-22T08:00:00.000Z"
}
}
}
}
}
urllib.urlencode(params )
Output :
'page=%7B%27filters%27%3A+%7B%27power%27%3A+%7B%27date%27%3A+%7B%27to%27%3A+%272019-05-22T08%3A00%3A00.000Z%27%2C+%27from%27%3A+%272019-04-22T08%3A00%3A00.000Z%27%7D%2C+%27keywordArray%27%3A+%5B%7B%27keyword%27%3A+%27random+word%27%2C+%27isNegated%27%3A+False%7D%5D%7D%7D%7D'
使用Python的输出与使用Java脚本的输出不同(正确)
答案 0 :(得分:1)
在javascript中,您正在将整个对象编码为url的字符串,而Python urllib.urlencode“将映射对象或两个元素的元组序列转换为“百分比编码”串”。也就是说,传递的对象将被解释为类似
的网址page => <restOfTheObject>
要具有与javascript中相同的行为,您应该首先将对象转换为json字符串,然后将其传递给urllib.parse.quote
import urllib.parse
import json
params = {
"page": {
"filters": {
"power": {
"keywordArray": [{
"keyword": "random word",
"isNegated": False
}],
"date": {
"from": "2019-04-22T08:00:00.000Z",
"to": "2019-05-22T08:00:00.000Z"
}
}
}
}
}
urllib.parse.quote(json.dumps(params, separators=(',', ':')))