python - 从 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 从对象中提取所有链接?
解决方案
这是一个递归解决方案:
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']
推荐阅读
- wpf - Microsoft.Win32.SystemEvents 事件不适用于 WeakEventManager
- javascript - d3.js 在两种十六进制颜色之间进行插值
- robotframework - 如何在表格列上循环?
- c# - 在首次加载之前通过授权服务器保护 SPA
- wordpress - AWS 上的 Wordpress 多站点服务器水平扩展
- php - 如何使用 PHP 运行 python 脚本并创建文件?
- erlang - 使用 Common Test 测试 gen_server 模块
- google-maps - google maps API geocoding 获取地址组件
- python - 如何使用 Pandas 处理来自 CSV 的不规则格式
- mapbox - mapbox setPaintProperty 方法是否处理表达式?