Python-Requests, extract url parameters from a string
我使用这个名为
我有一个案例需要解析一个URL并替换它的一个参数。例如:
1 | http://example.com?param1=a&token=TOKEN_TO_REPLACE¶m2=c |
我想知道:
1 | http://example.com?param1=a&token=NEW_TOKEN¶m2=c |
号
用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from urllib.parse import urlparse from urllib.parse import parse_qs from urllib.parse import urlencode url = 'http://example.com?param1=a&token=TOKEN_TO_REPLACE¶m2=c' o = urlparse(url) query = parse_qs(o.query) if query.get('token'): query['token'] = ['NEW_TOKEN', ] new_query = urlencode(query, doseq=True) url.split('?')[0] + '?' + new_query >>> http://example.com?param2=c¶m1=a&token=NEW_TOKEN |
如何使用
您不能为此使用
坚持使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | try: # Python 3 from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs o = urlparse(url) query = parse_qs(o.query) # extract the URL without query parameters url = o._replace(query=None).geturl() if 'token' in query: query['token'] = 'NEW_TOKEN' requests.get(url, params=query) |
您可以在python 2和3中同时获得
在python 3上演示(不带导入异常保护),以演示已构建的URL:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | >>> from urllib.parse import urlparse, parse_qs >>> url ="http://httpbin.org/get?token=TOKEN_TO_REPLACE¶m2=c" >>> o = urlparse(url) >>> query = parse_qs(o.query) >>> url = o._replace(query=None).geturl() >>> if 'token' in query: ... query['token'] = 'NEW_TOKEN' ... >>> response = requests.get(url, params=query) >>> print(response.text) { "args": { "param2":"c", "token":"NEW_TOKEN" }, "headers": { "Accept":"*/*", "Accept-Encoding":"gzip, deflate", "Host":"httpbin.org", "User-Agent":"python-requests/2.5.1 CPython/3.4.2 Darwin/14.1.0" }, "origin":"188.29.165.245", "url":"http://httpbin.org/get?token=NEW_TOKEN¶m2=c" } |
号
仅使用请求….
1 2 3 4 5 6 7 | query = requests.utils.urlparse(url).query params = dict(x.split('=') for x in query.split('&')) if 'token' in params: params['token'] = 'NEW_TOKEN' requests.get(url, params=params) |