要在 python 中列出的网址代码
Urlencode to list in python
finalKeywords = []
#after populating finalKeywords
query = {
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"kw" : finalKeywords,
"t" : int(time.time())
}
uri = urllib.urlencode(query, True)
print uri
解码uri后我得到
country=&apiKey=5f0092f1777c3a5ed0de&kw=iphone&kw=android&t=1496924489¤cy=usd
虽然我的预期输出是
country=&apiKey=5f0092f1777c3a5ed0de&kw[0]=iphone&kw[1]=android&t=1496924489¤cy=usd
怎么办..?我一直在寻找解决方案,但无法得到。
像这样?
query = {
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"kw[]" : finalKeywords,
"t" : int(time.time())
}
如果出于某种原因您也需要在其中包含位置值,这是一种方法:
query = {
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"t" : int(time.time())
}
for p,q in enumerate(finalKeywords):
query["kw[{pos}]".format(pos=p)] = q
基于 the W3C spec for URLs,[
和 ]
在搜索字符串中无效,因此将被 urlencode
转义。有了这个警告,您可以通过使用字典理解来构建具有唯一键的字典:
kw_dict = { "kw[{}]".format(n): finalKeywords[n] for n in range(0, len(finalKeywords)) }
然后您可以将其添加到查询的其他部分,如下所示:
query = dict({
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"t" : int(time.time())
}, **kw_dict)
finalKeywords = []
#after populating finalKeywords
query = {
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"kw" : finalKeywords,
"t" : int(time.time())
}
uri = urllib.urlencode(query, True)
print uri
解码uri后我得到
country=&apiKey=5f0092f1777c3a5ed0de&kw=iphone&kw=android&t=1496924489¤cy=usd
虽然我的预期输出是
country=&apiKey=5f0092f1777c3a5ed0de&kw[0]=iphone&kw[1]=android&t=1496924489¤cy=usd
怎么办..?我一直在寻找解决方案,但无法得到。
像这样?
query = {
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"kw[]" : finalKeywords,
"t" : int(time.time())
}
如果出于某种原因您也需要在其中包含位置值,这是一种方法:
query = {
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"t" : int(time.time())
}
for p,q in enumerate(finalKeywords):
query["kw[{pos}]".format(pos=p)] = q
基于 the W3C spec for URLs,[
和 ]
在搜索字符串中无效,因此将被 urlencode
转义。有了这个警告,您可以通过使用字典理解来构建具有唯一键的字典:
kw_dict = { "kw[{}]".format(n): finalKeywords[n] for n in range(0, len(finalKeywords)) }
然后您可以将其添加到查询的其他部分,如下所示:
query = dict({
"apiKey" : self.apikey,
"country" : country,
"currency" : currency,
"t" : int(time.time())
}, **kw_dict)