Home  >  Article  >  Backend Development  >  Detailed explanation of Python urlencode encoding and url splicing methods

Detailed explanation of Python urlencode encoding and url splicing methods

高洛峰
高洛峰Original
2017-03-17 16:28:315916browse

urlencode calling method

The parameters of urlencode must be Dictionary

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 (), here is not how to use it in most PHP, if you are interested, check it out yourself.

urlencode encoding

Functionurlencode 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

djangoThe urlencode is similar, the method is as follows:

from django.utils.http import urlquote
a = urlquote('PythonTab中文网')
print a

Get the GBK encoding of Chinese characters

urllib converts String

In fact, you can use the quote function of urllib Convert the Chinese in the URL and convert the Chinese into GBK encoding. 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'
>>>


The above is the detailed content of Detailed explanation of Python urlencode encoding and url splicing methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn