2015-02-10 93 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. 
相關問題