Python 如何读取HTML json文件并获取具有特定ID或类的元素?

Python 如何读取HTML json文件并获取具有特定ID或类的元素?,python,Python,我有以下功能: def html_dict_search(html_dict, selector): 在哪里 html_dict = json.load(f) selector是类/id名称 选择器=.headline项的函数应返回类似的内容: { "name": "li", "attrs": { "class": "headline-item" }, "text": "one",

我有以下功能:

def html_dict_search(html_dict, selector):
在哪里

 html_dict = json.load(f)
selector
是类/id名称

选择器=.headline项的函数应返回类似的内容:

     {
         "name": "li",
         "attrs": {
             "class": "headline-item"
         },
         "text": "one",
         "children": []
     },
     {
         "name": "li",
         "attrs": {
             "class": "headline-item"
         },
         "text": "two",
         "children": []
     }

我似乎想不出一个办法来做这件事,也找不到任何好的读物。任何建议或想法都是最受欢迎的。

您可以使用列表理解来像这样筛选集合

html_json = [{
     "name": "li",
     "attrs": {
         "class": "headline-item"
     },
     "text": "one",
     "children": []
 },
 {
     "name": "li",
     "attrs": {
         "class": "headline-item"
     },
     "text": "two",
     "children": []
 },
 {
     "name": "li",
     "attrs": {
         "class": "subtitle-item"
     },
     "text": "two",
     "children": []
 }]
headline_items = [element for element in html_json if element["attrs"]["class"] == "headline-item"]
这将在
headline\u项目中产生以下数据

[{'name': 'li',
  'attrs': {'class': 'headline-item'},
  'text': 'one',
  'children': []},
 {'name': 'li',
  'attrs': {'class': 'headline-item'},
  'text': 'two',
  'children': []}]

看看你能不能把从这个函数返回的东西保存在字典里,并通过它们的id访问你想要的元素?