如何使用Python从相同的id中提取多个字符串

时间:2016-12-05 23:57:57

标签: python json web-scraping

我写了这段代码,以便从网站中提取id和roll。

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
    },

我的问题是如何让我的程序识别出有多层数据供它读取和存储,到目前为止它只会获取最高结果并在运行时包含它。

2 个答案:

答案 0 :(得分:0)

检查len(roll)以确保至少为1,然后只设置第一个元素的值,例如top_id = obj [' rolls'] [0] [' id& #39;]或top_state = obj [' roll'] [0] ['州']希望有所帮助。

答案 1 :(得分:0)

如果我理解正确,你想要做的就是每1000秒重复一次循环,并在每次迭代时打印<!DOCTYPE html> <html> <head> </head> <body> <p id="output"></p> <button onclick="collectWood()">collect wood</button> <script> var wood = +localStorage.getItem("woodSave"); document.getElementById('output').innerHTML = parseInt(wood); localStorage.setItem("woodSave", wood); if(wood >= 1000){ replace = (wood / 1000).toFixed(2) + "k"; wood = replace; document.getElementById('output').innerHTML = wood; } function collectWood() { wood = wood + 1; document.getElementById('output').innerHTML = wood; } </script> </body> </html>中的所有数据。

rolls