在我开始之前,我可以说,我对用代码与网络进行一般通信还很陌生。话虽如此,谁能帮我获取这些参数,
'a': stMonth,
'b': stDate,
'c': stYear,
'd': enMonth,
'e': enDate,
'f': enYear,
'submit': 'submit'
用于此页面上的“设置日期范围”框, http://finance.yahoo.com/q/hp?s=gspc&a=00&b=3&c=1951&d=11&e=29&f=2014&g=d&z=66&y=0
,在我的 Python 代码中工作。目前包括:
def getHistoricData(symbol, stMonth, stDate, stYear, enMonth, enDate, enYear):
url = 'http://finance.yahoo.com/q/hp?s=%s&a=00&b=3&c=1951&d=11&e=29&f=2014&g=d&z=66&y=0' % symbol
params = {
'a': stMonth,
'b': stDate,
'c': stYear,
'd': enMonth,
'e': enDate,
'f': enYear,
'submit': 'submit',
}
response = requests.get(url, params=params)
tree = html.document_fromstring(response.content)
symbol = raw_input("Symbol: ")
getHistoricData(symbol, '00', '11', '2010', '00', '13', '2010')
我相信参数的名称或值可能有问题,但我不能确定。提前致谢 - 非常感谢您的帮助! (包括批评,只要它至少有点建设性!)
最佳答案
<input>
带有 name
的元素属性等于:
a, b, c, d, e, f, g(the radio button Daily/Weekly/Monthly)
在<form>
里面标签,其中有这个 hidden form field
:
<input type="hidden" name="s" value="^GSPC" data-rapid_p="11">
这将像常规 <input>
一样向服务器发送一个名称/值对元素。
您需要在请求中包含该名称/值对,以便服务器端程序知道您请求的是哪只股票的数据。
submit button
在一个表单中也会向服务器发送一个名称/值对,但它很少很重要,在这种情况下你可以省略它:
import requests
url = 'http://finance.yahoo.com/q/hp'
params = {
's': '^GSPC', #<input type="hidden" name="s" value="^GSPC" data-rapid_p="11">
'a': 1, #stMonth,
'b': 16, #stDate,
'c': 2014, #stYear,
'd': 1, #enMonth,
'e': 18, #enDate,
'f': 2014, #enYear,
'g': 'd', #daily/weekly/monthly
}
resp = requests.get(url, params=params)
print resp.text
print resp.url
resp.url
实际上是 请求 发送到的 url,您可以通过打印它来检查它:
http://finance.yahoo.com/q/hp?a=1&c=2014&b=16&e=18&d=1&g=d&f=2014&s=%5EGSPC
如果将其复制到浏览器的地址栏中,您将看到结果。 resp.text
是包含您的结果的页面的 html 标记。您必须知道如何搜索 html 以查找特定结果。要使用 python 搜索 html,请查看:
- 美丽汤
- lxml
关于Python-请求 : Correctly Using Params?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27701822/