Detailed explanation of Python urlencode encoding and url splicing methods

高洛峰
Release: 2017-03-17 16:28:31
Original
5866 people have browsed it

urlencode calling method

The parameters of urlencode must be Dictionary

Copy after login

Output:

name2=bbs.pythontab.com&name1=www.pythontab.com
Copy after login

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
Copy after login

Result:

name=PythonTab%D6%D0%CE%C4%CD%F8
Copy after login

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
Copy after login

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'
>>>
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!