python實例31[urllib.request.urlopen獲取股票信息]
① 在Python中通過HTTP下載東西是非常簡單的; 實際上,只需要一行代碼。urllib.request模塊有一個方便的函數urlopen() ,它接受你所要獲取的頁面地址,然后返回一個類文件對象,您只要調用它的read()方法就可以獲得網頁的全部內容。沒有比這更簡單的了。
② urlopen().read()方法總是返回bytes對象,而不是字符串。記住字節僅僅是字節,字符只是一種抽象。 HTTP 服務器不關心抽象的東西。如果你請求一個資源,你得到字節。 如果你需要一個字符串,你需要確定字符編碼,并顯式的將其轉化成字符串。
代碼如下:
import urllib.request
debug=False
class Utility:
def ToGB(str):
if(debug): print(str)
return str.decode('gb2312')
class StockInfo:
"""get stock information"""
def GetStockStrByNum(num):
f= urllib.request.urlopen('http://hq.sinajs.cn/list='+ str(num))
if(debug) : print(f.geturl())
if(debug) : print(f.info())
return f.readline()
f.close()
def ParseResultStr(resultstr):
if(debug) : print(resultstr)
slist=resultstr.split(',')
name=slist[0][-4:]
yesterdayendprice=slist[2]
todaystartprice=slist[1]
nowprice=slist[3]
upgraderate=(float(nowprice)-float(yesterdayendprice))/float(yesterdayendprice)
upgraderate= upgraderate * 100
dateandtime=slist[30] + ' ' + slist[31]
print('*******************************')
print('name is :',name)
print('yesterday end price is :', yesterdayendprice)
print('today start price is :', todaystartprice)
print('now price is :', nowprice)
print('upgrade rate is :', upgraderate,'%')
print('date and time is :', dateandtime)
print('*******************************')
def GetStockInfo(num):
str=StockInfo.GetStockStrByNum(num)
strGB=Utility.ToGB(str)
StockInfo.ParseResultStr(strGB)
def Main():
stocks = ['sh600547', 'sh600151', 'sz000593']
for stock in stocks:
StockInfo.GetStockInfo(stock)
Main()
結果:

參考:http://www.rzrgm.cn/blodfox777/archive/2009/02/10/1387229.html
完!


浙公網安備 33010602011771號