2017-10-11 41 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)