Python 请求 r.text 没有正确解码 paypal API
Python requests r.text doesn't decode properly paypal API
import requests
import datetime
server_addr = "https://api-3t.paypal.com/nvp"
headers = {'content-type': 'text/plain'}
params = {
'method' :'BMButtonSearch',
'version' :'124.0',
'user' :'xxx',
'pwd' :'xxx',
'signature' :'xxx',
'startdate' :datetime.datetime.now().isoformat()
}
r = requests.post(server_addr, headers=headers, data=params)
r.encoding='utf-8'
print(r.status_code)
print(r.text)
200
TIMESTAMP=2016%2d04%2d07T04%3a40%3a13Z&CORRELATIONID=1b4a043b2afe&ACK=Success&VERSION=124%2e0&BUILD=000000
r.text
u'TIMESTAMP=2016%2d04%2d07T04%3a40%3a13Z&CORRELATIONID=1b4a043b2afe&ACK=Success&VERSION=124%2e0&BUILD=000000'
<-- This isn't decoded or broken into key/value pairs as expected. It is just one large string.
附加信息:
r.encoding
'utf-8'
r.headers
{'Content-Length': '106', 'Set-Cookie': 'X-PP-SILOVER=name%3DLIVE11.APIT.1%26silo_version%3D880%26app%3Dappdispatcher_apit%26TIME%3D2917401943; domain=.paypal.com; path=/; Secure; HttpOnly, X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT', 'Server': 'Apache', 'Connection': 'close', 'Paypal-Debug-Id': '1b4a043b2afe', 'X-PAYPAL-OPERATION-NAME': 'BMButtonSearch', 'Date': 'Thu, 07 Apr 2016 04:40:13 GMT', 'X-PAYPAL-API-RC': '', 'Content-Type': 'text/plain; charset=utf-8', 'HTTP_X_PP_AZ_LOCATOR': 'dcg12.slc'}
由于该格式看起来像一个查询字符串,您可以使用标准库中的 urlparse
来解析它:
print(urlparse.parse_qs(r.text))
编辑:如果您只想取消对字符串的编码(但将其保留为字符串),请使用 urllib.unquote
:
print(urllib.unquote(r.text))
(在此处查看此答案:)
import requests
import datetime
server_addr = "https://api-3t.paypal.com/nvp"
headers = {'content-type': 'text/plain'}
params = {
'method' :'BMButtonSearch',
'version' :'124.0',
'user' :'xxx',
'pwd' :'xxx',
'signature' :'xxx',
'startdate' :datetime.datetime.now().isoformat()
}
r = requests.post(server_addr, headers=headers, data=params)
r.encoding='utf-8'
print(r.status_code)
print(r.text)
200
TIMESTAMP=2016%2d04%2d07T04%3a40%3a13Z&CORRELATIONID=1b4a043b2afe&ACK=Success&VERSION=124%2e0&BUILD=000000
r.text u'TIMESTAMP=2016%2d04%2d07T04%3a40%3a13Z&CORRELATIONID=1b4a043b2afe&ACK=Success&VERSION=124%2e0&BUILD=000000' <-- This isn't decoded or broken into key/value pairs as expected. It is just one large string.
附加信息:
r.encoding
'utf-8'
r.headers
{'Content-Length': '106', 'Set-Cookie': 'X-PP-SILOVER=name%3DLIVE11.APIT.1%26silo_version%3D880%26app%3Dappdispatcher_apit%26TIME%3D2917401943; domain=.paypal.com; path=/; Secure; HttpOnly, X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT', 'Server': 'Apache', 'Connection': 'close', 'Paypal-Debug-Id': '1b4a043b2afe', 'X-PAYPAL-OPERATION-NAME': 'BMButtonSearch', 'Date': 'Thu, 07 Apr 2016 04:40:13 GMT', 'X-PAYPAL-API-RC': '', 'Content-Type': 'text/plain; charset=utf-8', 'HTTP_X_PP_AZ_LOCATOR': 'dcg12.slc'}
由于该格式看起来像一个查询字符串,您可以使用标准库中的 urlparse
来解析它:
print(urlparse.parse_qs(r.text))
编辑:如果您只想取消对字符串的编码(但将其保留为字符串),请使用 urllib.unquote
:
print(urllib.unquote(r.text))
(在此处查看此答案: