---
title: "python中文转换url编码"
author: "yexin218"
date: "2010-04-24T17:54:11Z"
tags: ["Google", "Python", "百度"]
categories: ["编程语言"]
slug: "python-url"
draft: false
lastmod: "2010-04-24T17:54:11Z"
id: 652188
url: "https://yexin218.iteye.com/blog/652188"
---

转载自 [yyobin](http://hi.baidu.com/yobin)

最终编辑 [codedeveloper](http://hi.baidu.com/codedeveloper)

今天要处理百度贴吧的东西。想要做一个关键词的list，每次需要时，直接添加 到list里面就可以了。但是添加到list里面是中文的情况（比如‘丽江’），url的地址编码却是'%E4%B8%BD%E6%B1%9F'，因此需 要做一个转换。这里我们就用到了模块urllib。  
&gt;&gt;&gt; import urllib  
&gt;&gt;&gt; data = '丽江'  
&gt;&gt;&gt; print data  
丽江  
&gt;&gt;&gt; data  
'\\xe4\\xb8\\xbd\\xe6\\xb1\\x9f'  
&gt;&gt;&gt; urllib.quote (data)  
'%E4%B8%BD%E6%B1%9F'  
那我们想转回去呢？  
&gt;&gt;&gt; urllib.unquote('%E4%B8%BD%E6%B1%9F')  
'\\xe4\\xb8\\xbd\\xe6\\xb1\\x9f'  
&gt;&gt;&gt; print urllib.unquote ('%E4%B8%BD%E6%B1%9F')  
丽江  
细心的同学会发现贴吧url中出现的是%C0%F6%BD%AD，而非'%E4%B8%BD%E6%B1%9F'，其实是编码问题。百度的是gbk，其他 的一般网站比如google就是utf8的。所以可以用下列语句实现。  
&gt;&gt;&gt; import sys,urllib  
&gt;&gt;&gt; s = '丽江'  
&gt;&gt;&gt; urllib.quote(s.decode(sys.stdin.encoding).encode('gbk'))  
'%C0%F6%BD%AD'  
&gt;&gt;&gt; urllib.quote(s.decode(sys.stdin.encoding).encode('utf8'))  
'%E4%B8%BD%E6%B1%9F'  
&gt;&gt;&gt;