在Python请求中转义反斜杠

2024-04-19 03:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问一个API,其中一个参数的名称(Axwell /\ Ingrosso)中有一个\。在

如果我直接使用websiteapi面板访问API,我将使用Axwell /\\ Ingrosso获得结果。在

然后请求URL变成https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150

如果我尝试使用Python请求访问同一个API端点,则得到一个空响应。在

这就是我要做的

r = session.get('https://oauth-api.beatport.com/catalog/3/tracks', 
               params={'facets': 'artistName:Axwell /\\ Ingrosso', 
                       'perPage': 150})

我也尝试过在Python请求中不使用反斜杠,但即使这样也会输出空响应。我错过了什么?在


Tags: https名称comapi参数oauthcatalogtracks
1条回答
网友
1楼 · 发布于 2024-04-19 03:16:17

您需要将反斜杠加倍:

'artistName:Axwell /\\\\ Ingrosso'

或者通过在字符串文本前面加上r前缀来使用原始字符串文本:

^{pr2}$

在Python字符串文本中,反斜杠开始转义序列,\\表示转义序列,例如没有特定含义的常规反斜杠字符:

>>> print 'artistName:Axwell /\\ Ingrosso'
artistName:Axwell /\ Ingrosso
>>> print 'artistName:Axwell /\\\\ Ingrosso'
artistName:Axwell /\\ Ingrosso
>>> print r'artistName:Axwell /\\ Ingrosso'
artistName:Axwell /\\ Ingrosso

或作为requests生成的编码URL:

>>> import requests
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': 'artistName:Axwell /\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C+Ingrosso&perPage=150'
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': 'artistName:Axwell /\\\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150'
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': r'artistName:Axwell /\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150'

相关问题 更多 >