import urllib.parse url = ‘http://www.baidu.com/index.html‘; data = { ‘name‘:‘bowen‘, ‘age‘:25, ‘sex‘:‘male‘, } lt = [] for k,v in data.items(): lt.append(k+‘=‘+str(v)) # 这个是在for循环外面的,就是将列表的元素之间用&符号连接起来 query_string = ‘&‘.join(lt) print(lt) print(query_string) url = url + ‘?‘+query_string print(url)
第二种: urllib.parse模块
import urllib.parse url = ‘http://www.baidu.com/index.html‘; data = { ‘name‘:‘bowen‘, ‘age‘:25, ‘sex‘:‘male‘, } data1 = { ‘name‘:‘博文‘, ‘age‘:25, ‘sex‘:‘male‘, } query_string = urllib.parse.urlencode(data) print(query_string) url1 = url + ‘?‘+query_string print(url1) query_string1 = urllib.parse.urlencode(data1) url2 = url + ‘?‘+query_string1 print(url2)