python URL解析转换成字典

引用包:

import urlparse

获取URL:

url="https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=300200&rsv_spt=1&oq=python%20nonetype&rsv_pq=ddeee0430002a4d3&rsv_t=52bbRWiHUtsbsalW02NaxFrDqU5UVJ5TYaaeofTn0oNP0TZh2BQe7Fyh5viROnY%2BuYJg&rqlang=cn&rsv_enter=1&rsv_sug3=6&rsv_sug1=1&rsv_sug7=100&rsv_sug2=0&inputT=2497&rsv_sug4=2497"

将URL解析转换成字典:

def url2Dict(url):
    query = urlparse.urlparse(url).query
    return dict([(k, v[0]) for k, v in urlparse.parse_qs(query).items()])


过程如下:

In [1]: import urlparse


In [2]: url="https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=300200&rsv_spt=1&oq=python%20nonetype&rsv_pq=ddeee0430002a4d3&rsv_t=52bbRWiHUtsbsalW02NaxFrDqU5UVJ5TYaaeofTn0oNP0TZh2BQe7Fyh5viROnY%2BuYJg&rqlang=cn&rsv_enter=1&rsv_sug3=6&rsv_sug1=1&rsv_sug7=100&rsv_sug2=0&inputT=2497&rsv_sug4=2497"


In [3]: def url2Dict(url):

   ...:         query = urlparse.urlparse(url).query

   ...:         return dict([(k, v[0]) for k, v in urlparse.parse_qs(query).items()])

   ...: 


In [4]: aa = url2Dict(url)


In [5]: print aa

{'wd': '300200', 'rsv_spt': '1', 'inputT': '2497', 'rsv_enter': '1', 'f': '8', 'rsv_bp': '1', 'rsv_t': '52bbRWiHUtsbsalW02NaxFrDqU5UVJ5TYaaeofTn0oNP0TZh2BQe7Fyh5viROnY+uYJg', 'rsv_idx': '2', 'tn': 'baiduhome_pg', 'rsv_sug4': '2497', 'rsv_sug7': '100', 'rsv_pq': 'ddeee0430002a4d3', 'rsv_sug1': '1', 'oq': 'python nonetype', 'rsv_sug3': '6', 'rsv_sug2': '0', 'ie': 'utf-8', 'rqlang': 'cn'}


你可能感兴趣的:(Python)