59

Python で requests.get() を使用して、次の形式の URL を取得しようとしています。

http://api.example.com/export/?format=json&key=site:dummy+type:example+group:wheel

#!/usr/local/bin/python

import requests

print(requests.__versiom__)
url = 'http://api.example.com/export/'
payload = {'format': 'json', 'key': 'site:dummy+type:example+group:wheel'}
r = requests.get(url, params=payload)
print(r.url)

ただし、URL はパーセント エンコードされており、予期した応答が得られません。

2.2.1
http://api.example.com/export/?key=site%3Adummy%2Btype%3Aexample%2Bgroup%3Awheel&format=json

これは、URL を直接渡すと機能します。

url = http://api.example.com/export/?format=json&key=site:dummy+type:example+group:wheel
r = requests.get(url)

パーセントエンコーディングなしで、パラメータを元の形式で渡す方法はありますか?

ありがとう!

4

6 に答える 6

13

将来、他の誰かがこれに遭遇した場合に備えて、requests.Session をサブクラス化し、send メソッドをオーバーライドし、未加工の URL を変更して、パーセント エンコーディングなどを修正できます。以下の修正は大歓迎です。

import requests, urllib

class NoQuotedCommasSession(requests.Session):
    def send(self, *a, **kw):
        # a[0] is prepared request
        a[0].url = a[0].url.replace(urllib.parse.quote(","), ",")
        return requests.Session.send(self, *a, **kw)

s = NoQuotedCommasSession()
s.get("http://somesite.com/an,url,with,commas,that,won't,be,encoded.")
于 2016-11-17T13:11:57.867 に答える