作者:mkmkunming | 来源:互联网 | 2023-05-23 14:33
我正在使用这个令人敬畏的库requests
来维护python 2和3兼容性并简化我的应用程序请求管理.
我有一个案例,我需要解析一个网址并替换其中一个参数.例如:
http://example.com?param1=a&token=TOKEN_TO_REPLACE¶m2=c
我希望得到这个:
http://example.com?param1=a&token=NEW_TOKEN¶m2=c
随着urllib
我可以这样做:
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
你如何使用requests
图书馆实现同样的目标?
1> Martijn Piet..:
你不能用requests
它; 如果为参数传递Python结构,则库会构建此类URL,但不提供任何解析它们的工具.这不是该项目的目标.
坚持urllib.parse
解析参数的方法.获得字典或键值元组列表后,只需将其传递requests
给再次构建URL:
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中同时获得urlparse
和parse_qs
函数,如果你得到一个例外,你需要做的就是调整导入位置.
在Python 3上演示(没有导入异常保护)来演示已构建的URL:
>>> 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"
}
2> 小智..:
requests
仅使用:
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)