Python请求:正确使用Params?

2024-09-30 12:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在我开始之前,我可以说,我对用代码与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代码中工作。目前包括:

^{pr2}$
^{3}$

我相信参数的名称或值可能有问题,但我不能确定。提前感谢-任何和所有的帮助是非常感谢!(包括批评,只要是建设性的!)在


Tags: 代码webhttp参数交流yahoosubmitfinance
3条回答

具有name属性的<input>元素等于:

a, b, c, d, e, f, g(the radio button Daily/Weekly/Monthly)

{cd3>{cd3>里面有^这个标记:

^{pr2}$

它将像常规的<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

{eem>它实际上是由发送到的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,请查看:

  1. 美体
  2. lxml公司

您不需要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()')

例如,如果您调用:

^{pr2}$

打印以下内容(日期为第一列):

[
    'Nov 28, 2014', 
    'Nov 26, 2014', 
    'Nov 25, 2014', 
    'Nov 24, 2014',
    ...
]

我想你不需要用params。只需格式化一个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

相关问题 更多 >

    热门问题