我正在尝试构建一个 url,以便我可以使用urllib模块向它发送 get 请求。
假设我的final_url应该是
url = "www.example.com/find.php?data=http%3A%2F%2Fwww.stackoverflow.com&search=Generate+value"
现在为了实现这一点,我尝试了以下方法:
>>> initial_url = "http://www.stackoverflow.com"
>>> search = "Generate+value"
>>> params = {"data":initial_url,"search":search}
>>> query_string = urllib.urlencode(params)
>>> query_string
'search=Generate%2Bvalue&data=http%3A%2F%2Fwww.stackoverflow.com'
现在,如果您将我query_string的格式与您的格式进行比较,final_url您可以观察到两件事
1)参数的顺序是相反的,而不是data=()&search=它是search=()&data=
2)urlencode还编码了+inGenerate+value
我相信第一个变化是由于字典的随机行为。所以,我想用OrderedDict反转字典。正如,我正在使用python 2.6.5我做的
pip install ordereddict
但是当我尝试时,我无法在我的代码中使用它
>>> od = OrderedDict((('a', 'first'), ('b', 'second')))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'OrderedDict' is not defined
所以,我的问题是OrderedDict在 python 2.6.5 中使用的正确方法是什么以及如何urlencode忽略+in Generate+value。
另外,这是构建URL.