Python2 测试ok
#! /usr/bin/python3
# coding=utf-8import urllib.request
def get_price(code):
url = 'http://hq.sinajs.cn/?list=%s' % code
req = urllib.request.Request(url)
#如果不需要设置代理,下面的set_proxy就不用调用了。由于公司网络要代理才能连接外网,所以这里有set_proxy…
req.set_proxy('proxy.XXX.com:911', 'http')
content = urllib.request.urlopen(req).read()
str = content.decode('gbk')
data = str.split('"')[1].split(',')
name = "%-6s" % data[0]
price_current = "%-6s" % float(data[3])
change_percent = (float(data[3]) - float(data[2]) )*100 / float(data[2])
change_percent = "%-6s" % round (change_percent, 2)
print("股票名称:{0} 涨跌幅:{1} 最新价:{2}".format(name, change_percent, price_current) )
def get_all_price(code_list):
for code in code_list:
get_price(code)
code_list = ['sz300036', 'sz000977', 'sh600718', 'sh600452', 'sh600489']
get_all_price(code_list)
--------------------------------------------------------------------------------------------------------------------------------------
#! /usr/bin/python2 # coding=utf-8 import sys import urllib2 #import urllib #import requests #import request #import urllib.request #from urllib import request #from urllib.request import Request, urlopen #import urllib2.Request from urllib2 import Request from urllib2 import urlopen print sys.getdefaultencoding() reload(sys) sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() def get_price(code): url = 'http://hq.sinajs.cn/?list=%s' % code print url req = urllib2.Request(url) print req # 如果不需要设置代理,下面的set_proxy就不用调用了。由于公司网络要代理才能连接外网,所以这里有set_proxy… # req.set_proxy('proxy.XXX.com:911', 'http') content = urllib2.urlopen(req).read() str = content.decode('gbk', 'ignore') data = str.split('"')[1].split(',') name = "%-6s" % data[0] price_current = "%-6s" % float(data[3]) change_percent = (float(data[3]) - float(data[2])) * 100 / float(data[2]) change_percent = "%-6s" % round(change_percent, 2) print("股票名称:{0} 涨跌幅:{1} 最新价:{2}".format(name, change_percent, price_current)) def get_all_price(code_list): for code in code_list: get_price(code) code_list = ['sz300036', 'sz000977', 'sh600718', 'sh600452', 'sh600489'] get_all_price(code_list)
ascii
utf-8
http://hq.sinajs.cn/?list=sz300036
<urllib2.Request instance at 0x015C7530>
股票名称:超图软件 涨跌幅:-0.49 最新价:20.15
http://hq.sinajs.cn/?list=sz000977
<urllib2.Request instance at 0x015C7530>
股票名称:浪潮信息 涨跌幅:1.67 最新价:26.72
http://hq.sinajs.cn/?list=sh600718
<urllib2.Request instance at 0x015C7530>
股票名称:东软集团 涨跌幅:0.68 最新价:17.68
http://hq.sinajs.cn/?list=sh600452
<urllib2.Request instance at 0x015C7530>
股票名称:涪陵电力 涨跌幅:-1.31 最新价:37.66
http://hq.sinajs.cn/?list=sh600489
<urllib2.Request instance at 0x015C7530>
股票名称:中金黄金 涨跌幅:-0.76 最新价:11.8
Process finished with exit code 0