快速网页分析-page_parser-2

来源:互联网 发布:淘宝店铺装修全能助手 编辑:程序博客网 时间:2024/06/10 11:12

以前从证券之星的 API接口获取数据

http://q.ssajax.cn/webhandler/futures.ashx?fn=jQuery161043026683991774917_1465260997239&debug=1&code=ALRC&jys=LME&_=1465261192468

获取的是 JQuery回调的数据格式。

后来发现 数据接口少了 昨结,就从网页抓取数据

http://futures.quote.stockstar.com/LME/ALRC.shtml.


JQuery版本的数据,可以考虑删除一些字符串,转换为 JSON格式,使用 json模块加载。

对于 html格式数据,使用 lxml的xpath语法,非常简洁。

from page_parser import parser_resourcefrom datetime import datetime#===============================================================================# #===============================================================================url = 'http://futures.quote.stockstar.com/LME/ALRC.shtml'def callback(page):    _code = page.xpath('//h2[@class="h1"]')[0].text.strip().strip('()')    _price = page.xpath('//span[@id="stock_quoteinfo_xj"]')[0].text.strip()    _open = page.xpath('//span[@id="stock_quoteinfo_jk"]')[0].text    _high = page.xpath('//span[@id="stock_quoteinfo_zg"]')[0].text    _volume = page.xpath('//span[@id="stock_quoteinfo_cj"]')[0].text    _buy = page.xpath('//span[@id="stock_quoteinfo_br"]')[0].text    _buy_volume = page.xpath('//span[@id="stock_quoteinfo_bl"]')[0].text    _date = page.xpath('//span[@id="stock_quoteinfo_date"]')[0].text        _close = page.xpath('//span[@id="stock_quoteinfo_zs"]')[0].text    _low = page.xpath('//span[@id="stock_quoteinfo_zd"]')[0].text    _open_interest = page.xpath('//span[@id="stock_quoteinfo_chicang"]')[0].text    _sell = page.xpath('//span[@id="stock_quoteinfo_sc"]')[0].text    _sell_volume = page.xpath('//span[@id="stock_quoteinfo_sl"]')[0].text    _pre_settle_price = page.xpath('//span[@id="stock_quoteinfo_zj"]')[0].text    _time = page.xpath('//span[@id="stock_quoteinfo_time"]')[0].text    _date_time = datetime.strptime( _date + " " + _time  , "%Y-%m-%d %H:%M:%S")    print 'date time: %s' % _date_time.strftime("%Y%m%d %H%M%S")    print 'code' , _code    print 'price' , _price    print 'open' , _open    print 'high' , _high    print 'volume' , _volume    print 'buy' , _buy    print 'buy_volume' , _buy_volume    print 'close' , _close    print 'low' , _low    print 'open interest' , _open_interest    print 'sell', _sell    print 'sell volume' , _sell_volume    print 'pre settle price' , _pre_settle_priceif __name__ == '__main__':    parser_resource(url , page_callback=callback)



测试的效果如下:

detect_coding>gbk, cvt to utf-8requests save filename => futures.quote.stockstar.com_LME_ALRC.shtml.htmldate time: 20161013 202509code ALRCprice 1680.8open 1680.8high 1680.8volume 33buy 0buy_volume 0close 1675.5low 1680.8open interest 0sell 0sell volume 0pre settle price 1675.5

成功提取了网页上的所需字段。


0 0