我在Windows 10上运行python 3.6 - 标准安装,jupyter notebooks IDE
代码:
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 :(得分:2)
因为您获得了URL重定向。 HTTP状态代码为302,您被重定向到新的URL。
您可以在此处获取更多信息: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections 和 http://docs.python-requests.org/en/master/user/quickstart/#redirection-and-history
我们可以使用Response对象的history属性来跟踪重定向。试试这个:
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)
答案 1 :(得分:0)
这不是一个真正的答案,但它是我使用字符串连接的解决方法
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)