【问题标题】:Extracting a javascript object value by key name using regex [closed]使用正则表达式按键名提取javascript对象值[关闭]
【发布时间】:2021-02-11 16:55:55
【问题描述】:

我使用BeautifulSouprequests 抓取了一个网页,以下代码是整个 HTML 页面的一部分。

$create(Web.Scheduler, {
  "model": '{"apt":[0]}',
  "timeZone": "UTC",
  "_uniqueId": "94b3535a4bdaaf329cab5b7fde996f14",
  "allowEdit": false,
  "people":
    "[{\"id\": 1, \"name\": \"John\", \"age\": \"30\"},{\"id\": 2, \"name\": \"Jane\", \"age\": \"27\"}]",
  "attributes": {},
  "groupBy": "name",
});

有一个带有键"people" 的对象。如何使用正则表达式提取此键的值,即

[{"id": 1, "name": "John", "age": "30"},{"id": 2, "name": "Jane", "age": "27"}]

以便我可以将其解析为 Python 字典。我可以确认字符串"people"(带引号)在整个页面上是唯一的。

到目前为止,我已经看到了一些提取用引号括起来的字符串的解决方案。但是在这种情况下,我必须使用与"people": 匹配的模式,也许"attributes" 键也可以用作停止点,我必须提取这两者中间的内容。提前致谢!

【问题讨论】:

    标签: javascript python json regex beautifulsoup


    【解决方案1】:

    您可以使用re/ast 模块来提取数据。例如:

    import re
    from ast import literal_eval
    
    
    txt = r'''
    $create(Web.Scheduler, {
      "model": '{"apt":[0]}',
      "timeZone": "UTC",
      "_uniqueId": "94b3535a4bdaaf329cab5b7fde996f14",
      "allowEdit": false,
      "people":
        "[{\"id\": 1, \"name\": \"John\", \"age\": \"30\"},{\"id\": 2, \"name\": \"Jane\", \"age\": \"27\"}]",
      "attributes": {},
      "groupBy": "name",
    });
    '''
    
    data = re.search(r'("people".*?),\s*\n', txt, flags=re.S).group(1)
    data = literal_eval('{' + data + '}')
    
    # print the result:
    print(data['people'])
    

    打印:

    [{"id": 1, "name": "John", "age": "30"},{"id": 2, "name": "Jane", "age": "27"}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      相关资源
      最近更新 更多