2013-07-19 25 views
1

我的建築內,做下面的事情的任務的小模塊: - 讀取網頁(cavirtex.com/orderbook) - 獲得與urllib的來源和使用beautifulsoup -parse打開現在得到body.div(id='xx') ,我卡在這裏。我想重新美化結果並在更大的tr內迭代兩行td並獲取值並對它們進行求和。如果有人知道如何做到這一點,請向我解釋,因爲我在這裏呆了幾個小時。哦,這裏是我的源代碼:BeautifulSoup雙層

myurl = urllib.urlopen('http://cavirtex.com/orderbook').read() 
soup = BeautifulSoup(myurl) 

selling = soup.body.div(id ='orderbook_buy') 
selling = str(selling) 
selling = BeautifulSoup(selling) 
Sresult = selling.find_all(['tr']) 
amount = 30 
count = 0 
cadtot = 0 
locamount = 0 
for rows in Sresult: 
    #agarrar string especifico para vez 
    Wresult = Sresult[count] 
    #crear lista 
    Eresult = [Wresult] 
    Eresult = str(Eresult) 
    cosito = str(Eresult[count]) 

    print cosito 
    count = int(count) + 1 
    cadtot = cadtot + locamount 

回答

0

您需要總結表中的價格和價值?這樣做並將結果存儲爲以1至21的整數作爲鍵的字典以及CAD中的價格和值的總和作爲值。如果您需要其他輸出,您可以輕鬆調整以適應您的特定需求。

import urllib 
from bs4 import * 

myurl = urllib.urlopen('http://cavirtex.com/orderbook').read() 
soup = BeautifulSoup(myurl) 

selling = soup.body.div(id ='orderbook_buy') 
Sresult = selling[0].find_all(['tr']) 
data = {} 
c = 0 
for item in Sresult: 
    # You need to sum price and value? this sums up price and value 
    tds = item.find_all(["td"])[2:] 
    c += 1 
    summa = 0 
    for elem in tds: 
     elemVal = float(elem.text.replace(" CAD", "")) 
     summa += elemVal 
     data[c] = summa 
print data 

這給我們:

{2: 200.16001, 3: 544.5600000000001, 4: 543.072, 5: 6969.35103, 6: 1000.14005, 7: 108.601, 8: 472.95, 9: 533.26, 10: 180.0, 11: 271.34000000000003, 12: 178.0, 13: 242.94, 14: 334.85, 15: 176.0, 16: 320.08000000000004, 17: 1269.05023, 18: 1071.33022, 19: 2618.9202, 20: 97.12008999999999, 21: 656.48005} 

2號是200.16001等於90.76001 + 109.40,等等...

+0

謝謝Pawelmhm!這正是我需要的。 – user2542929

2

不是直接回答你的問題,但如果您的目標是從cavirtex.com下載和處理訂單,我建議您改用圖表API:

https://www.cavirtex.com/api/CAD/orderbook.json

該鏈接具有友好JSON中所需的所有信息。

例子:

import urllib 
import json 

url = "https://www.cavirtex.com/api/CAD/orderbook.json" 
orderbook_json = urllib.urlopen(url).read() 
orderbook = json.loads(orderbook_json) 

print(orderbook['bids']) 
print(orderbook['asks']) 

還有:

https://www.cavirtex.com/api/CAD/trades.json

大多數比特幣交易平臺支持相同的API,如記錄由bitcoincharts.com:http://bitcoincharts.com/about/exchanges/

享受!

+0

謝謝你的數據!這非常有用 – user2542929