• python爬取人民币汇率中间价


    python爬取人民币汇率中间价,从最权威的网站中国外汇交易中心。

    首先找到相关网页,解析链接,这中间需要经验和耐心,在此不多说。

    以人民币兑美元的汇率为例(CNY/USD),脚本详情如下:

    windows:

    ====================================================

    # -*- coding: utf-8 -*-
    import time
    import requests
    import json

    t = time.time()
    # 这里必须是ms级别的时间戳
    timestamp = (int(round(t*1000)))
    url = "http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/ccpr.json?t="+str(timestamp)

    s = requests.Session()
    r = s.post(url,data={})

    sjson = json.loads(r.text)
    #print sjson

    for k in sjson['records']:
      if k['vrtEName'] == 'USD/CNY':
      print k['price']

    =====================================================

    Linux:

    =====================================================

    # -*- coding: utf-8 -*-
    import time
    import urllib
    import urllib2
    import json

    t = time.time()
    # timestamp must be ms
    timestamp = (int(round(t*1000)))
    url = "http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/ccpr.json?t="+str(timestamp)
    data = urllib.urlencode({})

    request = urllib2.Request(url,data)
    response = urllib2.urlopen(request)

    result = response.read()
    rjson = json.loads(result)

    for r in rjson['records']:
      if r['vrtEName'] == 'USD/CNY':
      return r['price']

    ====================================================

    发现在linux环境下用request,返回的是HTML结构。

    而不是data的json格式,所以在linux用urllib和urllib2

  • 相关阅读:
    堆排序
    jdk8 永久代变更
    oracle 区分大小写遇到的坑
    日志统计分析
    zookeeper 服务挂掉重启后,dubbo 服务是不会自动重新注册上的
    代码质量管理
    快速排序算法
    python flask 项目结构
    项目架构
    JS中的循环---最全的循环总结
  • 原文地址:https://www.cnblogs.com/shizouwei/p/8507199.html
Copyright © 2020-2023  润新知