2016-12-05 100 views
0

我寫了這一點的代碼,以便從網站中提取id和roll。如何使用Python從相同的ID中提取多個字符串

import requests 
import json 
import time 
import urllib 


def ColorRequest(a=True): 
url = 'http://csgoroll.com/v1/roulette/state?token=bcb7841fe779ac0ae2a9e4f882ed3961ce0d714215fede3c025a24fc418e123dcb5a0a47a0ba1825225c14b39e08ea399422eb2b012689a79c41f42b529640e37d5374125c3fef409b2d165c223923dbc27f320c53bf10e46e701058251c97b9' # Could add a + pls str(pagesomething) to add on to the url so that it would update 
sourcecode = requests.get(url) # requests the data from the site 
plaintext = sourcecode.text # imports all of the data gathered 

obj = json.loads(plaintext) 
for roll in obj['rolls']: 

    print(roll['id'], roll['roll']) 
    while a == True: 
     ColorRequest() 
     time.sleep(1000) 


if __name__ == '__main__': 
ColorRequest() 

但數據看起來像這樣

{ 
"gameState": 
"1", 
"currentGame": "9965464", 
"startDate": "Mon Dec 05 2016 23:30:42 GMT+0000 (UTC)", 
"rolls": [ 
    { 
     "id": 9965465, 
     "hash": "f39a2391bd589fc217b73c407e316ff440dc920657929bd7ca9b7adddf0cedc9", 
     "roll": 11, 
     "state": 3, 
     "created_at": null, 
     "updated_at": null 
    }, 
    { 
     "id": 9965466, 
     "hash": "45eaa2bddb3281f036932de5839d4ccc2b28ebb1d4ded8f6e67cbff273831c73", 
     "roll": 3, 
     "state": 3, 
     "created_at": null, 
     "updated_at": null 
    }, 
    { 
     "id": 9965467, 
     "hash": "b6142c643816d2913a29518fdf624fcf577397af4ebfb008d61c4f1cf9d6ba3e", 
     "roll": 1, 
     "state": 3, 
     "created_at": null, 
     "updated_at": null 
    }, 

我的問題是如何讓我的計劃要認識到有多個數據層爲它讀取和存儲,到目前爲止,它會只抓取最高結果並在運行時包含它。

+0

什麼是'層'? '卷'? 'len(obj ['rolls'])'?沒有固定的「id」。順便說一下'obj = sourcecode.json()' – furas

+0

目前還不清楚你的代碼:你的代碼在打印第一個'roll'後會進入遞歸循環。這似乎完全沒有必要。那麼,你想達到什麼目的?發出請求,然後打印所有'roll'數據?一旦完成,每1秒鐘重複一次? – sal

回答

0

檢查len(roll)以確保至少爲1,然後設置第一個元素的值,例如top_id = obj ['rolls'] [0] ['id']或top_state = obj [ 'roll'] [0] ['state']希望有所幫助。

0

如果我理解正確,那麼您所要做的就是每1000秒重複循環,並在每次迭代中打印rolls中的所有數據。

import requests 
import time 

def ColorRequest(): 
    url = 'http://csgoroll.com/v1/roulette/state?token=bcb7841fe779ac0ae2a9e4f882ed3961ce0d714215fede3c025a24fc418e123dcb5a0a47a0ba1825225c14b39e08ea399422eb2b012689a79c41f42b529640e37d5374125c3fef409b2d165c223923dbc27f320c53bf10e46e701058251c97b9' # Could add a + pls str(pagesomething) to add on to the url so that it would update 
    sourcecode = requests.get(url) # requests the data from the site 
    obj = sourcecode.json() 
    for roll in obj['rolls']: 
     print(roll['id'], roll['roll']) 

if __name__ == '__main__': 
    while True: 
     ColorRequest() 
     time.sleep(1000) # these are seconds, ~17min 
相關問題