python请求给出“None”响应,其中需要json数据

8yoxcaq7  于 12个月前  发布在  Python
关注(0)|答案(4)|浏览(158)

首先,我应该补充一下,你可以通过以下方式找到这个请求:

1- Go to [airline site][1]
2- Type in "From" = "syd"
3- Type in "To" = "sin"
4- Make the departure date sep.3 and click one-way and search
5- On the search result page check your network get request when you click on an available seat option radio button

我尝试使用requests模块来获取响应,例如从this site
这就是我在尝试的:

url = "http://www.singaporeair.com/chooseFlightJson.form?"
payload = {'selectedFlightIdDetails[0]':amount_data,'hid_flightIDs':'','hid_recommIDs':'','tripType':"O",'userPreferedCurrency':""}

response = requests.get(url, params=payload)
print response.json()

答案应该是:

{"price":{"total":"595.34","currency":{"code":"AUD","label":""},"adult":{"count":1,"label":"Adult","cost":"328.00","total":"328.00"},"child":{"count":0,"label":"Child","cost":"0.00","total":"0.00"},"infant":{"count":0,"label":"Infant","cost":"0.00","total":"0.00"},"addOns":[{"label":"Airport / Government taxes ","cost":"83.24"},{"label":"Carrier Surcharges","cost":"184.10"}],"disclaimer":"Prices are shown in Canadian Dollar(CAD)","rate":"595.34 AUD \u003d 913.80 CAD","ratehint":"Estimated","unFormattedTotal":"595.34"},"messages":{"O3FF11SYD":"A few seats left","O1FF31SYD":" ","R0FF31SYD":"A few seats left","O2FF31SYD":"A few seats left","O0FF31SYD":" ","O1FF11SYD":"A few seats left","O0FF21SYD":" ","O2FF21SYD":" ","O3FF21SYD":" ","O1FF21SYD":" "},"cabinClass":{"onwardCabin":["Economy"]}}
r6l8ljro

r6l8ljro1#

响应None,以JSON编码;服务器返回null\r\n,这与Python中的None相同。
这里的内容类型错误;它被设置为text/html,但response.json()返回值对于服务器发送的内容是完全正确的:

>>> import requests
>>> url = "http://www.singaporeair.com/chooseFlightJson.form?"
>>> amount_data = 0
>>> payload = {'selectedFlightIdDetails[0]':amount_data,'hid_flightIDs':'','hid_recommIDs':'','tripType':"O",'userPreferedCurrency':""}
>>> response = requests.get(url, params=payload)
>>> response
<Response [200]>
>>> response.headers['content-type']
'text/html; charset=ISO-8859-1'
>>> response.text
'null\r\n'
>>> response.json() is None
True
i34xakig

i34xakig2#

将方案从http变更为https

url = "https://www.singaporeair.com/chooseFlightJson.form?"
7uhlpewt

7uhlpewt3#

解决方案是使用requests session,如下所示:

session = requests.Session()

然后调用所有的URL,你只需要做:

response = session.get(url)

这将设置检索数据所需的cookie和会话变量。我见过jsessionid以不同的方式使用,在url中,或者在这种情况下在cookie中。但可能还需要其他会话信息,这些信息由requests session对象处理。

vaj7vani

vaj7vani4#

在进行http请求时,请确保response_type设置为您正在尝试的确切用例。在我的例子中,**response_type='object'**消除了响应中的None类型。

相关问题