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