python
  • beautifulsoup
  • 2014-03-12 154 views 0 likes 
    0

    我有一些凌亂的湯,我一直試圖解析,我無法弄清楚我會怎麼做。在頁面上有一堆<div>標籤,我可以成功遍歷它們以找到我想要的div。獲得屬性值的美麗湯(python)

    這個div有一個自定義的屬性叫"data-series",它的值似乎是一些包含列表的字典列表。數據系列屬性的值如下所示:

    <div data-series= 
    '[{"label":"Series 1","data":[[0,0.01214697],[1,0.01139803],[2,0.0101848]],"color":"#27a9e3"}, 
    {"label":"series 2","data":[[0,0.00745604375],[1,0.00885196875],[2,0.009824050833]],"color":"#ffb848"}]'.... 
    

    然後繼續處理其他一些自定義屬性。我正在尋找這個嵌套混亂中的數字

    我想最終打印出的值是0.01139803。在列表中,它在第一個字典中找到,並且是"data"鍵的值。但"data"鍵的值本身就是一個列表,並且是第二個嵌套元素的第二個元素([1][1]

    如何使用美麗的湯將此數字拉出?

    回答

    4

    data-series的字符串是「JSON」(JavaScript Object Notation)數據。您可以使用json.loads()處理此的字符串爲Python數據結構,然後操縱的結果,就像任何listdict

    >>> import json 
    >>> s = '[{"label":"Series 1","data":[[0,0.01214697],[1,0.01139803],[2,0.0101848]],"color":"#27a9e3"},{"label":"series 2","data":[[0,0.00745604375],[1,0.00885196875],[2,0.009824050833]],"color":"#ffb848"}]' 
    >>> d = json.loads(s) 
    >>> d[0]['data'][1][1] 
    0.01139803 
    
    +0

    作品完美,謝謝! – Simon

    相關問題