百度和Google的URL編碼方式探索

來源:互聯網
上載者:User

今天才注意到,百度和Google的URL編碼方式不一樣。

比如我們搜“技術”這個詞,然後觀察IE地址欄。

用Baidu得到的結果是
http://www.baidu.com/s?wd=%BC%BC%CA%F5&cl=3

用Google得到的結果是
http://www.google.com/search?hl=zh-CN&q=%E6%8A%80%E6%9C%AF&lr=

即,baidu_urlencode("技術")=%BC%BC%CA%F5  , google_urlencode("技術")=%E6%8A%80%E6%9C%AF
,很明顯不一樣,那麼兩者分別用的是什麼編碼演算法呢?

趕快拿出可愛的Python來幫我們解決問題吧。
>>> import urllib
>>> url=urllib.unquote('http://www.baidu.com/s?wd=%BC%BC%CA%F5&cl=3')
>>> url
'http://www.baidu.com/s?wd=/xbc/xbc/xca/xf5&cl=3'
>>> print url.decode('gb2312')
http://www.baidu.com/s?wd=技術&cl=3
>>>

很明顯,baidu的url編碼方式是gb2312。那麼google呢?能否如法泡製?

>>> url2=urllib.unquote('http://www.google.com/search?hl=zh-CN&q=%E6%8A%80%E6%9C%AF&lr=')
>>> url2
'http://www.google.com/search?hl=zh-CN&q=/xe6/x8a/x80/xe6/x9c/xaf&lr='
>>> print url2.decode('gb2312')
Traceback (most recent call last):
  File "<input>", line 1, in ?
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 40-41: illegal multibyte sequence

很遺憾,報錯了,這是因為選擇了gb2312解碼是不對的。那就試試別的吧,可能是'utf-8'吧,go on

>>> print url2.decode('utf-8')
http://www.google.com/search?hl=zh-CN&q=技術&lr=
yeah,成功了。這說明google對url的編碼是utf-8

 

Python is so cool!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.