2015-02-10 88 views
0

我想查询一个API,我需要填写partNumbermanufacturer在Python中构建包含字典的URL的正确方法

假设我需要填写partNumber为bav99和NXP Semiconductors为制造商。最终的结果应该如下:

https://app.datafireball.com/SearchService/search/listPartSearch? 
partNumber=[{ 
%22partNumber%22:%22bav99wt%22, 
%22manufacturer%22:%22NXP%20Semiconductors%22}]& 
fmt=xml 

我不得不说,我真是由哪些字符应不编码和事实混淆。根据我所见,双引号"应编码为%22,空格编码为%20

我做了什么:

import urllib 
urltemplate = """https://app.datafireball.com/SearchService/search/listPartSearch?partNumber=[{{%22partNumber%22:%22{0}%22,%22manufacturer%22:%22{1}%22}}]&fmt=xml""" 
# I have to recode the curly brackets to be double curly brackets, otherwise place holder won't work. 
url = urltemplate.format(urllib.quote('my partnumber'), urllib.quote('my manufacturer')) 
print url 

我想我可以总结我的问题纳入以下两个问题:

  1. 为什么某些字符进行编码,有些不是。

  2. 什么是正确的方式和实际的方式来编码的对象,而不是使用占位符硬编码它。

回答

0

是否this帮助你......

urllib.urlencode(查询[,doseq])¶

Convert a mapping object or a sequence of two-element tuples 
to a “percent-encoded” string, suitable to pass to urlopen() above as the 
optional data argument. This is useful to pass a dictionary of form 
fields to a POST request. 
相关问题