urlencode calling method
urlencode parameter must be Dictionary
import urllib d = {'name1':'www.pythontab.com','name2':'bbs.pythontab.com'} print urllib.urlencode(d)
Output:
name2=bbs.pythontab.com&name1=www.pythontab.com
is equivalent to splicing two url parameters. This usage is similar to http_build_query() in PHP, which is not mentioned here. How to use it in most PHP? If you are interested, check it out yourself.
urlencode encoding
The function urlencode will not change the original encoding of the incoming parameters, which means that the encoding of the post or get parameters needs to be adjusted before calling.
Question: Now simulate requests to Google and baidu. Since baidu uses gb2312 encoding and google uses utf8 encoding, the urlencode values of the Chinese parameters submitted to the URL by the two sites are different. The following is "PythonTab Chinese Network" For example:
# coding: UTF-8 str = u'PythonTab中文网' str = str.encode('gb2312') d = {'name':str} q = urllib.urlencode(d) print q
Result:
name=PythonTab%D6%D0%CE%C4%CD%F8
Note: The parameter of urlencode must be Dictionary
Other usage
The urlencode in django is similar, the method is as follows:
from django.utils.http import urlquote a = urlquote('PythonTab中文网') print a
get Chinese characters GBK encoding
urllib conversion string
In fact, you can use urllib's quote function to convert the Chinese in the URL, convert the Chinese into GBK encoding, and the resulting encoding is a URL that conforms to the URI standard.
>>> import urllib >>> a = "PythonTab中文网" >>> a 'PythonTab\xe4\xb8\xad\xe6\x96\x87\xe7\xbd\x91' >>> urllib.quote(a) 'PythonTab%E4%B8%AD%E6%96%87%E7%BD%91' >>>