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)
第一个问题:数据实际上是在一个框架中的iframe中;您需要查看https://www.schwab.wallst.com/public/research/stocks/summary.asp?user_id=schwabpublic&symbol=APC(在这里,您在URL的末尾替换了适当的符号)。在
第二个问题:从页面中提取数据。我个人喜欢lxml和xpath,但是有很多包可以完成这项工作。我可能会期待一些类似
当被称为
^{pr2}$它回来了
第三个问题:这个页面上的标记是表示性的,而不是结构性的——这意味着基于它的代码可能是脆弱的,即页面结构的任何更改(或页面之间的变化)都需要重新编写XPath。在
希望有帮助!在
使用Beautiful Soup之类的工具来解析来自web站点的HTML响应并将其加载到字典中。使用符号作为键,使用您感兴趣的任何数据的元组作为值。迭代所有返回的符号,并为每个符号添加一个条目。在
你可以在托比·西格兰的《集体智能编程》中看到如何做到这一点的例子。这些示例都是用Python编写的。在
你想过使用雅虎的报价api吗?
请参见:http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20来自%20yahoo.finance.quotes%20where%20symbol%20%3D%20%22YHOO%22在
您将能够动态生成对网站的请求,例如:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20来自%20yahoo.finance.quotes%20where%20symbol%20%3D%20%22YHOO%22&;诊断=真&环境=存储%3A%2F%2Fdatatables.org%2Falltableswithkeys在
只需使用标准的httpget请求进行轮询。响应是XML格式的。在
相关问题 更多 >
编程相关推荐