用Python下载价格数据

4 投票
4 回答
1382 浏览
提问于 2025-04-16 07:17

我之前试过这个,但完全不知道该怎么做。

在这个页面上,有一个对话框可以获取报价。 http://www.schwab.com/public/schwab/non_navigable/marketing/email/get_quote.html?

我用的是SPY、XLV、IBM和MSFT。

输出结果是上面的内容,还有一个表格。

如果你有账户,报价是实时的——通过cookie来实现。

我想知道怎么把这个表格导入到Python 2.6中,数据格式可以是列表或字典。

4 个回答

3

你有没有想过使用雅虎的股票报价接口呢?
可以看看这个链接: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20* 这里可以查询到雅虎财经的报价数据,像是你想要的“YHOO”这个股票。

你可以动态生成一个请求,像这样:
http://query.yahooapis.com/v1/public/yql?q=select%20* 这个链接也是用来获取雅虎财经的报价数据,只需要把“YHOO”放在请求里就可以了,并且可以加一些参数来调试。

然后你只需要用标准的HTTP GET请求去访问这个链接就可以了。返回的数据是XML格式的。

5

可以使用像Beautiful Soup这样的工具来解析网站返回的HTML内容,然后把它放进一个字典里。用符号作为字典的键,把你感兴趣的数据放成一个元组作为值。然后遍历所有返回的符号,为每个符号添加一条记录。

你可以在Toby Segaran的《编程集体智能》一书中看到如何做到这一点的例子。书里的示例都是用Python写的。

4

第一个问题:数据实际上是在一个框架里的一个子框架(iframe)中;你需要查看这个链接 https://www.schwab.wallst.com/public/research/stocks/summary.asp?user_id=schwabpublic&symbol=APC (在网址的末尾替换成合适的股票代码)。

第二个问题:从页面中提取数据。我个人比较喜欢用 lxml 和 xpath,但还有很多其他工具也能完成这个任务。我可能会期待一些像这样的代码

import urllib2
import lxml.html
import re
re_dollars = '\$?\s*(\d+\.\d{2})'

def urlExtractData(url, defs):
    """
    Get html from url, parse according to defs, return as dictionary

    defs is a list of tuples ("name", "xpath", "regex", fn )
      name becomes the key in the returned dictionary
      xpath is used to extract a string from the page
      regex further processes the string (skipped if None)
      fn casts the string to the desired type (skipped if None)
    """

    page = urllib2.urlopen(url) # can modify this to include your cookies
    tree = lxml.html.parse(page)

    res = {}
    for name,path,reg,fn in defs:
        txt = tree.xpath(path)[0]

        if reg != None:
            match = re.search(reg,txt)
            txt = match.group(1)

        if fn != None:
            txt = fn(txt)

        res[name] = txt

    return res

def getStockData(code):
    url = 'https://www.schwab.wallst.com/public/research/stocks/summary.asp?user_id=schwabpublic&symbol=' + code
    defs = [
        ("stock_name", '//span[@class="header1"]/text()', None, str),
        ("stock_symbol", '//span[@class="header2"]/text()', None, str),
        ("last_price", '//span[@class="neu"]/text()', re_dollars, float)
        # etc
    ]
    return urlExtractData(url, defs)

当调用时

print repr(getStockData('MSFT'))

它会返回

{'stock_name': 'Microsoft Corp', 'last_price': 25.690000000000001, 'stock_symbol': 'MSFT:NASDAQ'}

第三个问题:这个页面的标记是为了展示而不是结构,这意味着基于它的代码可能会比较脆弱,也就是说,页面结构的任何变化(或者不同页面之间的差异)都会需要你重新调整你的 xpath。

希望这些信息对你有帮助!

撰写回答