简体   繁体   English

美汤(python)获得属性值

[英]Beautiful soup (python) getting value of attribute

I have some messy soup that I've been trying to parse and I can't figure out how I would do it. 我有一些混乱的汤,我一直在尝试解析,但我不知道该怎么做。 On the page there are a bunch of <div> tags, and I can successfully traverse through them all to find the div that I want. 在页面上有一堆<div>标记,我可以成功遍历它们全部以找到所需的div。

This div, has a custom attribute called "data-series" , the value of which seems to be some list of dictionaries containing lists. 该div具有一个名为"data-series"的自定义属性,该属性的值似乎是包含列表的一些词典列表。 The value of the data-series attribute looks like this: 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"}]'....

It then continues on with some other custom attributes. 然后,它将继续使用其他一些自定义属性。 I'm looking to pull out one of the numbers within this nested mess 我想找出嵌套巢中的数字之一

The value I want to end up printing out is 0.01139803 . 我要结束打印的值是0.01139803 Within the list, it is found in the first dictionary, and is the value of the "data" key. 在列表中,它是在第一个字典中找到的,并且是"data"键的值。 But the value of the "data" key is in itself a list, and is the second element of the second nested element ( [1][1] ) 但是"data"键的值本身就是一个列表,并且是第二个嵌套元素( [1][1] )的第二个元素

How would I pull this number out using beautiful soup? 我要如何用漂亮的汤把这个号码拿出来?

The string for data-series is "JSON" (JavaScript Object Notation) data. data-series的字符串是“ JSON”(JavaScript对象表示法)数据。 You can use json.loads() to process this string into Python data structures, then manipulate the result as you would any list and dict : 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM