[英]Python - Requests: Correctly Using Params?
在開始之前,我只想說一遍,我對使用代碼進行Web常規通信非常陌生。 話雖如此,誰能協助我獲取這些參數,
'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')
我相信參數的名稱或值可能有問題,但是我不確定。 在此先感謝您-任何幫助都將不勝感激! (包括批評,只要它至少具有建設性!)
您只是不需要submit
參數,而是需要g
。 d
表示daily
:
def getHistoricData(symbol, stMonth, stDate, stYear, enMonth, enDate, enYear):
url = 'http://finance.yahoo.com/q/hp'
params = {
's': symbol,
'a': stMonth,
'b': stDate,
'c': stYear,
'd': enMonth,
'e': enDate,
'f': enYear,
'g': 'd'
}
response = requests.get(url, params=params)
tree = html.document_fromstring(response.content)
print tree.xpath('.//table[@class="yfnc_datamodoutline1"]//tr/td[1]/text()')
例如,如果您調用:
getHistoricData('^GSPC', '02', '3', '1950', '10', '30', '2014')
打印以下內容(日期從第一列開始):
[
'Nov 28, 2014',
'Nov 26, 2014',
'Nov 25, 2014',
'Nov 24, 2014',
...
]
我認為您不需要使用參數。 只需格式化URL就足夠了。 像這樣:
# -*- coding: utf-8 -*-
#!/usr/bin/python
import requests
symbol = raw_input("Symbol: ")
params = (symbol, '00', '11', '2010', '00', '13', '2010')
url = 'http://finance.yahoo.com/q/hp?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=d' % params
response = requests.get(url)
# you will get 200 OK here
print response
# and page info is in response.text
name
屬性的<input>
元素等於:
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,請簽出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.