2017-04-03 73 views
0

我想從這個link數據廢棄使用的urllib

一些數據來獲得開盤價從上面的鏈接我使用下面的代碼

import urllib 
from urllib.request import urlopen 

symbols=['KEL', 'BYCO'] 
def keystats(): 
    try: 
     response = urllib.request.urlopen('http://www.scstrade.com/StockScreening/SS_CompanySnapShot.aspx?symbol='+symbol) 
     sourcecode = response.readlines() 
     sourcecode = str(sourcecode) 
     open_price = sourcecode.split('<span id="MainContent_lbl_open" style="font-weight:bold;">')[1].split('</span>')[0] 
     print(open_price) 

    except: 
     print('Error') 

for symbol in symbols:   
    keystats() 

我相信,上面的代碼應該是能夠給我8.20的公開價格的結果。相反,我得到一個錯誤字符串。任何人都可以告訴上述代碼有什麼不對嗎?

回答

1

問題是您用來分隔的字符串,如果您檢查HTML,您會注意到術語是:<span id="MainContent_lbl_open"><b>8.20</b></span>,因此您應該查找這些術語。

代碼:

import urllib 
from urllib.request import urlopen 

symbols=['KEL', 'BYCO'] 
def keystats(): 
    try: 
     response = urllib.request.urlopen('http://www.scstrade.com/StockScreening/SS_CompanySnapShot.aspx?symbol='+symbol) 
     sourcecode = response.readlines() 
     sourcecode = str(sourcecode) 
     open_price = sourcecode.split('<span id="MainContent_lbl_open"><b>')[1].split('</b></span>')[0] 
     print(open_price) 

    except: 
     print('Error') 

for symbol in symbols:   
    keystats() 

輸出:

8.20 
21.59