2017-10-11 87 views
2

我在Windows 10上運行的Python 3.6 - 標準安裝,jupyter筆記本IDEPython3 get.requests URL中缺少PARAMS

代碼:

import requests 

params={'q': 'NASDAQ:AAPL','expd': 19, 'expm': 1, 'expy': 2018, 'output': 'json'} 
response = requests.get('https://www.google.com/finance/option_chain', params=params) 

print(response.url) 

預期輸出:

https://finance.google.com/finance/option_chain?q=NASDAQ:AAPL&expd=19&expm=1&expy=2018&output=json 

實際輸出:

https://finance.google.com/finance/option_chain?q=NASDAQ:AAPL&output=json 

感謝您看看我的代碼!

-E

回答

0

因爲你得到一個URL重定向。 HTTP狀態碼是302,你被重定向到一個新的URL。

你可以在這裏得到更多的信息: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirectionshttp://docs.python-requests.org/en/master/user/quickstart/#redirection-and-history

我們可以使用Response對象的歷史屬性以跟蹤重定向。試試這個:

import requests 

params={'q': 'NASDAQ:AAPL','expd': 19, 'expm': 1, 'expy': 2018, 'output': 
'json'} 
response = requests.get('https://www.google.com/finance/option_chain', 
params=params) 
print(response.history) # use the history property of the Response object to track redirection. 
print(response.history[0].url) # print the redirect history's url 
print(response.url) 

您將獲得:

[<Response [302]>] 
https://www.google.com/finance/option_chain?q=NASDAQ%3AAAPL&expm=1&output=json&expy=2018&expd=19 
https://finance.google.com/finance/option_chain?q=NASDAQ:AAPL&output=json 

您可以禁用重定向與allow_redirects參數處理:

import requests 

params={'q': 'NASDAQ:AAPL','expd': 19, 'expm': 1, 'expy': 2018, 'output': 'json'} 
response = requests.get('https://www.google.com/finance/option_chain', params=params, allow_redirects=False) 
print(response.status_code) 
print(response.url) 
0

這是不是一個真正的答案,但它是用字符串我的解決方法CONCAT

response = requests.get(url, params=params) 
    response_url = response.url 
    added_param = False 
    for i in params: 
     if response_url.find(i)==-1: 
      added_param = True 
      response_url = response_url+"&"+str(i)+"="+str(params[i]) 
      print("added:",str(i)+"="+str(params[i]), str(response_url)) 
    if added_param: 
     response = requests.get(response_url)