首页 > 解决方案 > 从 Python 中的 json 对象中提取所有 URL

问题描述

我有一个长 json 对象,其中包含值中的 URL 链接,这些链接可以是任何深度和任何键。深度和关键是未知的。前任。,

data = {
  "name": "John Doe",
  "a": "https:/example.com",
  "b": {
    "c": "https://example.com/path",
    "d": {
      "e": "https://example.com/abc/?q=u",
    }
  }
}

我想提取列表中的所有链接,例如

links = ["https://example.com", "https://example.com/path", "https://example.com/abc/?q=u"]

如何使用 Python 从对象中提取所有链接?

标签: python

解决方案


这是一个递归解决方案:

def extract_urls(d):
    urls = []
    for k, v in d.items():
        if isinstance(v, str) and v.lower().startswith("http"):
            urls.append(v)
        elif isinstance(v, dict):
            urls.extend(etract_urls(v))
    return urls

extract_urls(data)

输出:

['https:/example.com',
 'https://example.com/path',
 'https://example.com/abc/?q=u']

推荐阅读