0
我想查詢一個API,我需要填寫partNumber
和manufacturer
。在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
我想我可以總結我的問題納入以下兩個問題:
爲什麼某些字符進行編碼,有些不是。
什麼是正確的方式和實際的方式來編碼的對象,而不是使用佔位符硬編碼它。