我试图通过提供开始日期、结束日期并通过 POST 方法单击“获取价格”按钮来取消该网站的基金价格历史记录。
但是页面 requests.post() 返回不包含结果,就好像“获取价格”按钮从未被按下一样。这是我通过代码放在一起的 URL:
我在 Stackoverflow 上阅读了其他关于在 Python 中通过 POST 提交表单的帖子,但我无法让它工作。能否请你帮忙?非常感谢!
import requests
import datetime
startDate = datetime.datetime(2016,1,1).strftime('%m/%d/%Y')
endDate = datetime.datetime(2016,2,20).strftime('%m/%d/%Y')
serviceurl = 'https://www.nysaves.org/nytpl/fundperform/fundHistory.do?'
payload = {'fundid':1003022, 'startDate':startDate, 'endDate': endDate, 'submit':'Get Prices'}
r = requests.post(serviceurl, params=payload)
#from IPython.core.display import HTML
#HTML(r.content.decode('utf-8'))
最佳答案
- 您需要使用“数据”,而不是“参数”。 “params”用于编码到 URL 中的 GET 参数,但“data”在正文中发送。
- 正确的网址是
https://www.nysaves.org/nytpl/fundperform/fundHistorySearch.do
,而不是https://www.nysaves.org/nytpl/fundperform/fundHistory.do?
. - 您不需要
submit
关键字。但添加它不会有什么坏处。
此代码将起作用:
startDate = datetime.datetime(2016,1,1).strftime('%m/%d/%Y')
endDate = datetime.datetime(2016,2,20).strftime('%m/%d/%Y')
serviceurl = 'https://www.nysaves.org/nytpl/fundperform/fundHistorySearch.do'
payload = {'fundid': 1003022, 'startDate': startDate, 'endDate': endDate}
r = requests.post(serviceurl, data=payload)
print(r.text)
关于python - 如何点击表单中的提交按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35569447/