1. 程式人生 > >Python 解決位址列中文編碼問題

Python 解決位址列中文編碼問題

一、場景簡述

筆者發現在天貓搜尋店鋪頁面,如果輸入中文,在url中會進行轉碼,輸入英文則不變,如下圖

url中的將男裝進行了轉碼,本應q=男裝

具體url:https://list.tmall.com/search_product.htm?spm=a220m.1000858.1000724.7.1f281602JoXnuH&q=%C4%D0%D7%B0&sort=s&style=w&from=..pc_1_searchbutton&active=2#J_Filter

所以筆者需要在python3.6中將中文字元進行編碼,使其匹配其url


二、解決方案

type = ['女裝', '男裝', '計算機書籍', '電腦']
    for index in type:
        #解決位址列中 中文編碼問題
        typename = urllib.parse.quote(index)
        logging.info('type {}'.format(typename))
        #解碼
        retypename = urllib.parse.unquote(typename)
        logging.info('retype {}'.format(retypename))

結果

好了,問題解決